axiam-sdk 1.3.0 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +130 -14
- package/dist/amqp/index.d.cts +384 -17
- package/dist/amqp/index.d.ts +384 -17
- package/dist/amqp/index.js +639 -66
- package/dist/amqp/index.js.map +1 -1
- package/dist/amqp/index.mjs +631 -67
- package/dist/amqp/index.mjs.map +1 -1
- package/dist/{authzCore-D-hquWSI.d.ts → authzCore-Ced9zDIV.d.ts} +49 -12
- package/dist/{authzCore-CqXzLNmT.d.cts → authzCore-Des2NcKA.d.cts} +49 -12
- package/dist/browser/index.d.cts +1 -1
- package/dist/browser/index.d.ts +1 -1
- package/dist/{client-CaurIxje.d.ts → client-C1kRISf8.d.ts} +15 -1
- package/dist/{client-Bp7riC4k.d.cts → client-Dpd864N9.d.cts} +15 -1
- package/dist/{cookieJar-oKazfbN1.d.cts → cookieJar-CeH2FZIT.d.cts} +3 -3
- package/dist/{cookieJar-DC4GLKrJ.d.ts → cookieJar-DPx9Qtcf.d.ts} +3 -3
- package/dist/grpc/index.d.cts +5 -5
- package/dist/grpc/index.d.ts +5 -5
- package/dist/grpc/index.js +249 -18
- package/dist/grpc/index.js.map +1 -1
- package/dist/grpc/index.mjs +249 -18
- package/dist/grpc/index.mjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +29 -3
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +29 -3
- package/dist/index.mjs.map +1 -1
- package/dist/{jwks-CTVpOWzI.d.cts → jwks-CQtWokVd.d.cts} +62 -7
- package/dist/{jwks-CTVpOWzI.d.ts → jwks-CQtWokVd.d.ts} +62 -7
- package/dist/middleware/index.d.cts +220 -43
- package/dist/middleware/index.d.ts +220 -43
- package/dist/middleware/index.js +587 -149
- package/dist/middleware/index.js.map +1 -1
- package/dist/middleware/index.mjs +579 -150
- package/dist/middleware/index.mjs.map +1 -1
- package/dist/nestjs/index.d.cts +18 -4
- package/dist/nestjs/index.d.ts +18 -4
- package/dist/nestjs/index.js +20 -1
- package/dist/nestjs/index.js.map +1 -1
- package/dist/nestjs/index.mjs +19 -2
- package/dist/nestjs/index.mjs.map +1 -1
- package/dist/node/index.d.cts +5 -5
- package/dist/node/index.d.ts +5 -5
- package/dist/node/index.js +351 -66
- package/dist/node/index.js.map +1 -1
- package/dist/node/index.mjs +348 -67
- package/dist/node/index.mjs.map +1 -1
- package/dist/{oidcState-CZhj0MBP.d.ts → oidcState-CzpXPAHF.d.ts} +54 -14
- package/dist/{oidcState-EnEJmoF5.d.cts → oidcState-XOYEMQP6.d.cts} +54 -14
- package/dist/rest/index.d.cts +3 -3
- package/dist/rest/index.d.ts +3 -3
- package/dist/rest/index.js +29 -3
- package/dist/rest/index.js.map +1 -1
- package/dist/rest/index.mjs +29 -3
- package/dist/rest/index.mjs.map +1 -1
- package/dist/{session-CeIUXgpE.d.cts → session-DoQzoChX.d.cts} +1 -1
- package/dist/{session-Beo11VT_.d.ts → session-Z-6IyaSU.d.ts} +1 -1
- package/package.json +10 -10
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/core/errors.ts","../../src/core/errorMapper.ts","../../src/core/sensitive.ts","../../src/core/authz.ts","../../src/middleware/authzCore.ts","../../src/middleware/cookieHeader.ts","../../src/management/errors.ts","../../src/middleware/mcpCore.ts","../../src/middleware/oidcLoginCore.ts","../../src/node/oidcIdToken.ts","../../src/node/jwks.ts","../../src/middleware/peerCertificate.ts","../../src/middleware/verifyCore.ts","../../src/middleware/express.ts","../../src/middleware/fastify.ts","../../src/rest/bareTransport.ts","../../src/rest/interceptors.ts","../../src/rest/retry.ts","../../src/node/oidcPkce.ts","../../src/node/oidc.ts","../../src/node/revocationFeed.ts","../../src/node/oidcTypes.ts","../../src/node/oidcState.ts"],"names":["retryAfterMs","timingSafeEqual","document","invalidRequestBody","createHash","authzDeniedBody","missingCredentialsBody","invalidTokenBody","cs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AAA,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.js","sourcesContent":["// AxiamError taxonomy (CONTRACT.md §2, D-16).\n//\n// Three concrete TOP-LEVEL error types: AuthError, AuthzError, NetworkError,\n// all extending the abstract AxiamError base. §2 additionally permits\n// language-idiomatic SUB-TYPES of those three (they never replace them):\n// this module ships one, `OAuthProtocolError extends AuthError`, mandated by\n// §12.3 rule 3 for `OAuth2ErrorResponse` bodies returned by `/oauth2/*`.\n// `instanceof AuthError` therefore still matches every authentication\n// failure, including OAuth2 protocol errors — that backward compatibility is\n// what makes contract 1.4 additive rather than breaking.\n//\n// No error message or field may embed a raw token string, client secret, or\n// code verifier (D-16, §12.3 rule 3). The prototype chain is fixed up\n// manually in each constructor so `instanceof` works reliably across the\n// transpiled CJS+ESM outputs (a well-known TS-to-ES5/ES2022-target caveat\n// when extending built-ins like Error).\n\n/**\n * Base class of every error this SDK throws (CONTRACT.md §2).\n *\n * Catch this to handle any AXIAM failure uniformly; catch one of the three\n * concrete subclasses — {@link AuthError}, {@link AuthzError},\n * {@link NetworkError} — to distinguish authentication, authorization and\n * transport failures.\n */\nexport abstract class AxiamError extends Error {\n protected constructor(message: string) {\n super(message);\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Authentication failure (CONTRACT.md §2): wrong credentials, an expired\n * session, a failed MFA challenge, a `401` on refresh, or a failed ID-token\n * validation.\n */\nexport class AuthError extends AxiamError {\n /**\n * Optional stable, machine-readable reason code for the failure.\n *\n * Populated by the CONTRACT.md §12.4 ID-token validation checklist with\n * one of the seven codes §12.3 rule 3 enumerates (see\n * {@link IdTokenFailureReason}); `undefined` for every other `AuthError`.\n * It is a *code*, never free text, so callers can branch on it without\n * parsing `message`.\n */\n readonly reason?: string;\n\n constructor(message: string, reason?: string) {\n super(message);\n this.name = 'AuthError';\n this.reason = reason;\n Object.setPrototypeOf(this, AuthError.prototype);\n }\n}\n\n/**\n * The seven stable reason codes CONTRACT.md §12.3 rule 3 defines for\n * ID-token validation failures, one per §12.4 rule. Surfaced on\n * {@link AuthError.reason}.\n */\nexport type IdTokenFailureReason =\n | 'invalid_alg'\n | 'unknown_kid'\n | 'invalid_signature'\n | 'invalid_issuer'\n | 'invalid_audience'\n | 'token_expired'\n | 'nonce_mismatch';\n\n/**\n * An RFC 6749 protocol error returned by an `/oauth2/*` endpoint as an\n * `OAuth2ErrorResponse` body (CONTRACT.md §2 sub-type table, §12.3 rule 3).\n *\n * @remarks\n * A **sub-type of {@link AuthError}**, not a replacement for it: existing\n * `catch (e) { if (e instanceof AuthError) … }` code keeps working unchanged.\n * Raised for a `400` from `POST /oauth2/token` (e.g. `invalid_grant`) and for\n * a `401` from `POST /oauth2/introspect` / `POST /oauth2/revoke` (client\n * authentication failed) — neither of which may collapse into the generic\n * §2 `400 → NetworkError` / `401 → AuthError` rows.\n *\n * `message` is always exactly `\"<error>: <error_description>\"`, built from\n * the two wire fields, which are also exposed individually.\n *\n * @example\n * ```ts\n * try {\n * await oidc.oidcExchange({ code, codeVerifier, nonce, redirectUri });\n * } catch (err) {\n * if (err instanceof OAuthProtocolError && err.error === 'invalid_grant') {\n * // the authorization code was replayed, expired, or bound to another client\n * }\n * }\n * ```\n */\nexport class OAuthProtocolError extends AuthError {\n /** The RFC 6749 `error` code (e.g. `\"invalid_grant\"`, `\"invalid_client\"`, `\"unsupported_grant_type\"`). */\n readonly error: string;\n /**\n * The server's human-readable `error_description`. Never contains token\n * material. Empty when the server sent none: RFC 6749 §5.2 makes the member\n * OPTIONAL, and §2 (contract 1.53, §28.12.3) dispatches on `error` alone.\n */\n readonly errorDescription: string;\n /**\n * The server's `Retry-After` in milliseconds, when this error is a `429` that carried one in\n * delta-seconds form (contract 1.65 §37.3, C165-17). Absent otherwise; an HTTP-date is not read.\n * Additive: honour it before retrying a rate-limited native sign-in or CIBA call.\n */\n readonly retryAfterMs?: number;\n\n constructor(error: string, errorDescription: string = '', retryAfterMs?: number) {\n // `\"<error>: <error_description>\"`, or just `\"<error>\"` when the server\n // sent no description — never a dangling `\": \"`.\n super(errorDescription ? `${error}: ${errorDescription}` : error);\n this.name = 'OAuthProtocolError';\n this.error = error;\n this.errorDescription = errorDescription;\n if (retryAfterMs !== undefined) this.retryAfterMs = retryAfterMs;\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 /**\n * What is safe to keep of the underlying transport error: its name, message,\n * code and status, and the response's status, body and allow-listed headers\n * (§2, X-3). Never the request — its body or its headers — which may carry a\n * write-only secret (contract 1.59 R-18).\n */\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 * The tolerant `/oauth2/*` error decoder (CONTRACT.md §2, §28.12.3, §33.4):\n * an {@link OAuthProtocolError} for any body that is an object carrying a\n * **non-empty string `error`**, whatever the status, with `error_description`\n * used when it is a string and left empty otherwise.\n *\n * Distinct from {@link isOAuth2ErrorBody}, which requires both members and\n * gates the two status-qualified rows of {@link mapHttpStatusToError}: those\n * rows are unchanged. This is for the call paths whose contract text says to\n * dispatch on `error` at any status — the RFC 7592 client-configuration\n * operations (a `401 {\"error\":\"invalid_token\"}` carries no description) and\n * CIBA (a `429 {\"error\":\"rate_limit_exceeded\"}`).\n *\n * Returns `undefined` for anything else, so the caller falls back to §2's\n * status rows.\n */\nexport function oauth2ErrorFromBody(body: unknown, retryAfterMs?: number): OAuthProtocolError | undefined {\n if (body === null || typeof body !== 'object' || Array.isArray(body)) {\n return undefined;\n }\n const record = body as Record<string, unknown>;\n if (typeof record.error !== 'string' || record.error === '') {\n return undefined;\n }\n const description = typeof record.error_description === 'string' ? record.error_description : '';\n return new OAuthProtocolError(record.error, description, retryAfterMs);\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 * Reduce an axios-error-shaped `err` to the diagnostics that are safe to keep\n * as `NetworkError.cause` (CR-04, D-16, X-3; contract 1.59 R-18).\n *\n * An axios error is a map of everything the request touched: `config` holds\n * the serialized request body (`config.data` — a password, a `bind_secret`, a\n * SCIM `credential`, an SSF `authorization_header`, a form-encoded client\n * secret) and the request headers (the session's bearer and CSRF token);\n * `request` is the live `ClientRequest`, whose buffered output holds the same\n * body; and `response` carries both again (`response.config`,\n * `response.request`) beside the server's headers, which may set cookies. A\n * shallow copy that redacted only the response headers left all of that\n * reachable from `console.log(err)` on any `5xx` or transport failure.\n *\n * So the cause is **rebuilt from an allow-list**, never copied: `name`,\n * `message` and `code` when they are strings, `status` when it is a number,\n * and a `response` of `status`, `statusText`, the server's `data` and its\n * headers with every value not on `SAFE_RESPONSE_HEADERS` replaced by\n * `[REDACTED]`. Nothing else survives — no `config`, no `request`, no stack.\n *\n * Applies to anything carrying `response`, `config` or `request`, or flagged\n * `isAxiosError`, including a transport failure that has no response at all.\n * The caller's original object is never mutated. Other inputs — a plain\n * `Error`, a string, `undefined` — 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 {\n name?: unknown;\n message?: unknown;\n code?: unknown;\n status?: unknown;\n response?: unknown;\n isAxiosError?: unknown;\n };\n const hasResponse = candidate.response !== null && typeof candidate.response === 'object';\n const isRequestError =\n hasResponse || 'config' in candidate || 'request' in candidate || candidate.isAxiosError === true;\n if (!isRequestError) {\n return err;\n }\n\n const sanitized: Record<string, unknown> = {};\n for (const key of ['name', 'message', 'code'] as const) {\n const value = candidate[key];\n if (typeof value === 'string') sanitized[key] = value;\n }\n if (typeof candidate.status === 'number') sanitized.status = candidate.status;\n\n if (hasResponse) {\n const response = candidate.response as {\n status?: unknown;\n statusText?: unknown;\n headers?: unknown;\n data?: unknown;\n };\n const kept: Record<string, unknown> = {};\n if (typeof response.status === 'number') kept.status = response.status;\n if (typeof response.statusText === 'string') kept.statusText = response.statusText;\n if (response.headers !== null && typeof response.headers === 'object') {\n const headers: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(response.headers as Record<string, unknown>)) {\n headers[key] = SAFE_RESPONSE_HEADERS.has(key.toLowerCase()) ? value : REDACTED_HEADER;\n }\n kept.headers = headers;\n }\n if ('data' in response) kept.data = response.data;\n sanitized.response = kept;\n }\n return sanitized;\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","// Shared authz result shape (SDK-Q10, C2) — dependency-free, per D-04's\n// core/*.ts rule (no @grpc/grpc-js, amqplib, axios, jose, or node:util\n// imports here).\n//\n// Both the REST transport (`rest/types.ts`) and the gRPC transport\n// (`grpc/client.ts`) resolve to the exact same public decision shape —\n// `{ allowed, reason? }` — so it is defined once here and re-exported by\n// both `rest/index.ts` and `grpc/index.ts` under the same `AccessDecision`\n// name, rather than declaring two structurally-identical interfaces that\n// could drift out of sync.\n\n/**\n * The outcome of an access check, shared by the REST (`AxiamClient.checkAccess`\n * / `.batchCheck`) and gRPC (`AuthzGrpcClient.checkAccess` / `.batchCheck`)\n * transports (CONTRACT.md §1). `reason` is present (and non-empty) only when\n * `allowed` is `false`.\n */\nexport interface AccessDecision {\n /**\n * Whether the checked action on the checked resource is permitted.\n *\n * **This field alone carries the outcome.** {@link AccessDecision.reasonCode}\n * explains it and never contradicts it.\n */\n allowed: boolean;\n /** Present (and non-empty) only when `allowed` is `false`; a human-readable reason the check was denied. */\n reason?: string;\n /**\n * Machine-readable decision reason (CONTRACT.md §11 rule 9, B1\n * deny-override): `\"allowed\"`, `\"no_grant\"`, or `\"denied_by_rule\"`.\n *\n * **The two refusals mean opposite things to the person on the other end.**\n * `no_grant` says *ask an admin for access*; `denied_by_rule` says *an admin\n * has already decided*. An application that cannot tell them apart sends\n * users to raise tickets that will be refused — which is why the contract\n * forbids collapsing them into a bare `false`.\n *\n * Absent when the server does not send the field: a newer SDK against an\n * older server treats it as absent, never as an error. An unrecognised value\n * is surfaced verbatim and never changes {@link AccessDecision.allowed} —\n * which is why this is a `string` rather than a union, so a code the SDK has\n * never heard of still reaches the caller intact.\n */\n reasonCode?: string;\n}\n\n/**\n * The three `reasonCode` values CONTRACT.md §11 rule 9 defines.\n *\n * @remarks\n * Constants rather than a union type, so an unrecognised server value is still\n * assignable to {@link AccessDecision.reasonCode} and reaches the caller —\n * a closed union would force the SDK to drop it or lie about it.\n */\nexport const ReasonCode = {\n /** An allow grant matched and no deny did. */\n ALLOWED: 'allowed',\n /** Nothing matched — default deny. *Ask an admin for access.* */\n NO_GRANT: 'no_grant',\n /** An explicit deny rule matched and overrode any allow. *An admin has already decided.* */\n DENIED_BY_RULE: 'denied_by_rule',\n} as const;\n","// Shared declarative-authorization core (CONTRACT.md §11) — the ONE\n// resource-resolution + check-access + error-mapping path both the Express\n// and Fastify `requireAccess`/`requireAccessHook` guards call, mirroring how\n// `verifyCore.ts`'s `authenticateRequest` is the one §10 verification path\n// shared by both frameworks.\n//\n// §11.2.1 (composition with the §10 guard): these helpers NEVER perform\n// their own token extraction/verification — they only read the identity\n// already injected onto the request by `axiamMiddleware`/`axiamPlugin` (or\n// by `requireAuth`/`requireAuthHook` mounted earlier in the same chain). If\n// that identity is absent, the caller (express.ts/fastify.ts) responds 401\n// without ever reaching this module.\n\nimport { AuthzError, NetworkError, type Sensitive } from '../core/index.js';\nimport type { AccessCheck, AccessDecision } from '../rest/types.js';\nimport type { VerifiableSession } from './verifyCore.js';\n\n/**\n * The minimal shape `requireAccess`/`requireAccessHook` need from an authz\n * transport — satisfied structurally by `AxiamClient` (`checkAccess`\n * already accepts `subjectId`, §1/FND-04) without importing the class\n * itself, so this module pulls in no axios/grpc dependency.\n */\nexport interface AuthzChecker {\n /** Issue a single access check for the authenticated end user (`subjectId`, §11.2.2). Satisfied structurally by `AxiamClient.checkAccess`. */\n checkAccess(check: AccessCheck): Promise<AccessDecision>;\n}\n\n/**\n * `VerifiableSession` extended with an optional authz-capable client\n * (CONTRACT.md §11). `requireAuth`/`requireRole` only need the base\n * `VerifiableSession` shape; `requireAccess`/`requireAccessHook` additionally\n * require `authzClient` to be set — enforced by {@link assertAuthzClient},\n * which throws synchronously at guard-construction time (route-setup time),\n * not per-request, when it is absent.\n */\nexport interface AuthzVerifiableSession extends VerifiableSession {\n /** Authz transport required by `requireAccess`/`requireAccessHook` (validated by {@link assertAuthzClient}); unused by `requireAuth`/`requireRole`. */\n authzClient?: AuthzChecker;\n}\n\n/** Marker produced by {@link fromParam} — resolve the resource id from a named path/route parameter. */\nexport interface ResourceParamRef {\n /** Discriminant marking the path/route-parameter resolution strategy (§11.2.3.b). */\n readonly kind: 'param';\n /** The path/route parameter name the resource id is read from. */\n readonly name: string;\n}\n\n/**\n * `resource_param` precedence option (§11.2.3.b): resolve the resource id\n * from the named path/route parameter (`req.params[name]` /\n * `request.params[name]`) at request time.\n */\nexport function fromParam(name: string): ResourceParamRef {\n return { kind: 'param', name };\n}\n\n/** `resolver` precedence option (§11.2.3.c): a language-idiomatic callback resolving the resource id from the request. */\nexport type ResourceResolver<TReq> = (req: TReq) => string;\n\n/**\n * The `resource` argument accepted by `requireAccess`/`requireAccessHook`:\n * a static literal (§11.2.3.a, for singleton resources), {@link fromParam}\n * (§11.2.3.b), or a resolver callback (§11.2.3.c).\n */\nexport type ResourceSpec<TReq> = string | ResourceParamRef | ResourceResolver<TReq>;\n\n/** Thrown by {@link resolveResourceId} when the resource id cannot be resolved — mapped to 400 `invalid_request` by callers, never a silent allow (§11.2.3). */\nexport class ResourceResolutionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ResourceResolutionError';\n Object.setPrototypeOf(this, ResourceResolutionError.prototype);\n }\n}\n\n/**\n * Resolve the resource id from `req` per `spec`'s precedence (§11.2.3).\n * `getParams` abstracts over Express's `req.params` and Fastify's\n * `request.params`, both `Record<string, string | undefined>`-shaped at\n * runtime. A missing/empty resolution — a missing path parameter, or a\n * resolver returning an empty string — is a **programming error** raised as\n * {@link ResourceResolutionError}; it is never a silent allow and never a\n * nil/empty-id fallback (§11.2.3).\n */\nexport function resolveResourceId<TReq>(\n req: TReq,\n spec: ResourceSpec<TReq>,\n getParams: (req: TReq) => Record<string, string | undefined> | undefined,\n): string {\n let resourceId: string | undefined;\n if (typeof spec === 'function') {\n resourceId = spec(req);\n } else if (typeof spec === 'string') {\n resourceId = spec;\n } else {\n resourceId = getParams(req)?.[spec.name];\n }\n if (!resourceId) {\n const label = typeof spec === 'object' ? `route param \"${spec.name}\"` : 'resource';\n throw new ResourceResolutionError(`unable to resolve ${label} from request`);\n }\n return resourceId;\n}\n\n/** Optional per-guard settings for `requireAccess`/`requireAccessHook`. */\nexport interface RequireAccessOptions {\n /** Sub-resource scope, passed through to `checkAccess` verbatim (§11.2.4). */\n scope?: string;\n /** Debug-only denial logger (§11.2.8) — never receives the token, only `action`/`resourceId`. */\n logger?: AuthzLogger;\n /**\n * When set, a denial also carries a `WWW-Authenticate: UMA` challenge\n * (§20.3): the guard mints a permission ticket for the action it just refused\n * and tells the caller where to redeem it.\n *\n * Opt-in — see {@link UmaChallenger} for why that matters.\n */\n umaChallenge?: UmaChallenger;\n}\n\n/**\n * Mints a permission ticket. Structurally the `umaRequestTicket` method of an\n * `OidcClient`, taken as a function so this module does not depend on the\n * Node-only OIDC entry point — the middleware core is shared with the browser\n * build, which has no Protection API client.\n */\nexport type UmaTicketMinter = (\n pat: string,\n permissions: ReadonlyArray<{ resourceId: string; resourceScopes: string[] }>,\n) => Promise<Sensitive<string>>;\n\n/**\n * A configured `WWW-Authenticate: UMA` challenge emitter (§20.3, emit half).\n *\n * Attach one via {@link RequireAccessOptions.umaChallenge} and a denial stops\n * being a bare 403: the guard mints a fresh permission ticket for the pairs the\n * caller lacked and returns it in the header, so a UMA-aware client knows where\n * to go for authority instead of only being told \"no\".\n *\n * **Opt-in, and deliberately so.** Emitting a challenge means minting a\n * credential — a wire call to the Protection API, and a live ticket, produced\n * on a path the caller did not explicitly request. A guard that did that on\n * every denial by default would turn each unauthorized request into a\n * Protection API call, which is a denial-of-service amplifier pointed at your\n * own authorization server.\n *\n * **Failure is not escalation.** If minting fails — the PAT expired, the\n * Protection API is down, the resource declares none of the requested scopes —\n * the denial still surfaces as an ordinary 403 without a challenge. A caller\n * who was going to be refused is refused either way; letting a Protection API\n * outage turn a deny into a 500 would hand the outage a second consequence, and\n * letting it turn into an allow would be a security bug.\n */\nexport interface UmaChallenger {\n /** The protection realm to name in the header. */\n realm: string;\n /**\n * The authorization server to send the caller to — normally this\n * deployment's issuer, read from discovery rather than concatenated by hand.\n */\n asUri: string;\n /**\n * A Protection API Token: a *client-credentials* token carrying the\n * `uma_protection` scope (§20.2 rule 1). A user token cannot stand in — a\n * minted ticket is bound to the `client_id` that minted it.\n */\n pat: string;\n /** Typically `oidcClient.umaRequestTicket.bind(oidcClient)`. */\n mint: UmaTicketMinter;\n}\n\n/** Minimal logger seam for the §11.2.8 debug-only denial/error log (mirrors `amqp/consumer.ts`'s `ConsumeLogger`). */\nexport interface AuthzLogger {\n /** Emit a debug-only denial/error record (§11.2.8) — receives `action`/`resourceId` context, never the token. */\n debug(event: string, message: string, context?: Record<string, unknown>): void;\n}\n\n/**\n * Validate that `session.authzClient` is configured, returning it. Throws\n * synchronously (guard-construction time, i.e. route-setup time — not\n * per-request) when absent, per the task's \"helpers throw at construction\n * if absent\" requirement.\n */\nexport function assertAuthzClient(session: AuthzVerifiableSession): AuthzChecker {\n if (!session.authzClient) {\n throw new Error(\n 'requireAccess/requireAccessHook require session.authzClient (an AuthzChecker with checkAccess) to be configured (CONTRACT.md §11)',\n );\n }\n return session.authzClient;\n}\n\n/** Standardized JSON error body shape (§10/§11 — `{ error, message }`). */\nexport interface ErrorBody {\n /** Stable machine-readable error code (e.g. `authentication_failed`, `authorization_denied`). */\n error: string;\n /** Human-readable explanation; never contains token material. */\n message: string;\n}\n\nexport function missingAuthBody(): ErrorBody {\n return {\n error: 'authentication_failed',\n message: 'no authenticated identity on the request — mount axiamMiddleware/axiamPlugin (or requireAuth/requireAuthHook) first',\n };\n}\n\nexport function invalidRequestBody(message: string): ErrorBody {\n return { error: 'invalid_request', message };\n}\n\nexport function authzDeniedBody(message: string): ErrorBody {\n return { error: 'authorization_denied', message };\n}\n\nexport function authzUnavailableBody(message: string): ErrorBody {\n return { error: 'authz_unavailable', message };\n}\n\n/** The outcome of an `evaluateAccess` call — one arm per §11.2.5's error-mapping table (the 401/400 arms are handled by callers before this is ever invoked). */\nexport type CheckOutcome =\n | {\n /** The check passed — the caller proceeds to the handler. */\n kind: 'allowed';\n }\n | {\n /** The check was evaluated and denied (`allowed: false` or a server 403) → HTTP 403. */\n kind: 'denied';\n /** Denial message surfaced in the 403 body. */\n message: string;\n /**\n * The complete `WWW-Authenticate` value, when a {@link UmaChallenger} was\n * configured *and* minting succeeded (§20.3). Absent otherwise, including\n * when minting failed — the denial stands either way.\n */\n challenge?: string;\n /**\n * The decision's `reason_code` (§11 rule 9), surfaced verbatim so the\n * caller can apply §28.5 rule 5 — `no_grant` is the one denial a bearer\n * challenge may invite a client to retry, and `denied_by_rule` is not.\n *\n * Absent when the decision carried none, and absent on the `AuthzError`\n * arm: a server 403 names no reason code, and §11 rule 9 requires an\n * absent one to leave the outcome alone.\n */\n reasonCode?: string;\n }\n | {\n /** The authz transport failed — fail-closed → HTTP 503, never an allow. */\n kind: 'unavailable';\n /** Failure message surfaced in the 503 body. */\n message: string;\n };\n\n/**\n * Call `checker.checkAccess` with `subjectId` set to the *authenticated\n * request's* user id (§11.2.2 — never the app's own service-account\n * identity) and map the outcome per §11.2.5:\n * - `allowed: false` → `denied`\n * - `AuthzError` (server 403/409) → `denied`\n * - `NetworkError`, or any other unexpected failure → `unavailable`\n * (fail-closed: a transport failure is never treated as an allow).\n *\n * Never caches the decision (§11.2.6) — a plain per-call `await`.\n */\nexport async function evaluateAccess(\n checker: AuthzChecker,\n action: string,\n resourceId: string,\n subjectId: string,\n scope?: string,\n challenger?: UmaChallenger,\n): Promise<CheckOutcome> {\n try {\n const decision = await checker.checkAccess({ action, resourceId, scope, subjectId });\n if (!decision.allowed) {\n return deny(\n decision.reason ?? 'access denied',\n action,\n resourceId,\n challenger,\n decision.reasonCode,\n );\n }\n return { kind: 'allowed' };\n } catch (err) {\n if (err instanceof AuthzError) {\n return deny(err.message, action, resourceId, challenger);\n }\n if (err instanceof NetworkError) {\n return { kind: 'unavailable', message: err.message };\n }\n // Fail closed (§11.2.5): any unexpected failure is treated as\n // \"couldn't decide\", never a silent allow.\n return { kind: 'unavailable', message: 'authorization service unavailable' };\n }\n}\n\n/**\n * Build the denial, minting a §20.3 challenge when one was configured.\n *\n * Only ever reached on a path that has already decided to refuse, so minting\n * cannot change the outcome — at worst it fails and the caller gets the plain\n * 403 they would have got anyway.\n */\nasync function deny(\n message: string,\n action: string,\n resourceId: string,\n challenger?: UmaChallenger,\n reasonCode?: string,\n): Promise<CheckOutcome> {\n if (!challenger) return { kind: 'denied', message, reasonCode };\n try {\n // §20.2: the UMA scope is the AXIAM *action*, which is what makes the ticket\n // ask for exactly the authority this check just refused — and what keeps a\n // deny rule vetoing the resulting RPT the same way it vetoed the check.\n const ticket = await challenger.mint(challenger.pat, [{ resourceId, resourceScopes: [action] }]);\n return {\n kind: 'denied',\n message,\n reasonCode,\n challenge: umaChallengeHeaderValue(challenger.realm, challenger.asUri, ticket.expose()),\n };\n } catch {\n // Deliberately swallowed; see UmaChallenger's \"failure is not escalation\".\n // Not logged either: the §11.2.8 logger never receives credentials, and the\n // failure reason from a Protection API call can contain a token echo.\n return { kind: 'denied', message, reasonCode };\n }\n}\n\n/**\n * Format the header value. Duplicated from the Node-only `umaChallengeHeader`\n * rather than imported, because this module is in the browser build's\n * dependency graph and that one is not — the format is four literals and a\n * template, and a shared import would drag the whole OIDC entry point along.\n */\nfunction umaChallengeHeaderValue(realm: string, asUri: string, ticket: string): string {\n return `UMA realm=\"${realm}\", as_uri=\"${asUri}\", ticket=\"${ticket}\"`;\n}\n\n/** Local (no server round-trip) role check (§11.2.9): true iff `roles` and the identity's roles share at least one entry. */\nexport function hasAnyRole(identityRoles: readonly string[], roles: readonly string[]): boolean {\n return roles.some((role) => identityRoles.includes(role));\n}\n","// Internal Cookie header parser + token extractor (D-27, CONTRACT.md §10).\n//\n// No `cookie-parser`/`@fastify/cookie` peer dependency — a small\n// RFC6265-lenient splitter shared by both Express and Fastify middleware,\n// mirroring the Rust extractor's cookie-then-Bearer fallback order\n// (the Rust SDK's src/middleware/actix.rs:129-149).\n\nimport { timingSafeEqual } from 'node:crypto';\n\n/**\n * Parse a raw `Cookie` request header into a name -> value map.\n * Lenient: splits on `;`, trims whitespace, splits each pair on the first\n * `=` only (cookie values may themselves contain `=`, e.g. base64/JWT).\n */\nexport function parseCookieHeader(header: string | undefined): Record<string, string> {\n const cookies: Record<string, string> = {};\n if (!header) {\n return cookies;\n }\n for (const pair of header.split(';')) {\n const trimmed = pair.trim();\n if (!trimmed) {\n continue;\n }\n const eqIndex = trimmed.indexOf('=');\n if (eqIndex === -1) {\n continue;\n }\n const name = trimmed.slice(0, eqIndex).trim();\n const value = trimmed.slice(eqIndex + 1).trim();\n if (name) {\n cookies[name] = value;\n }\n }\n return cookies;\n}\n\n/** Name of the cookie carrying the AXIAM access token (`axiam_access`). */\nexport const ACCESS_COOKIE_NAME = 'axiam_access';\n\n/**\n * Where an extracted bearer credential came from. Load-bearing for the CSRF\n * gate below (CONTRACT.md §3): a token sourced from the `axiam_access`\n * cookie is attached to a request automatically by the browser (including\n * cross-site ones, in a same-site deployment), so it is NOT CSRF-immune the\n * way an `Authorization: Bearer` header is — a cross-site attacker cannot\n * set arbitrary request headers, but the browser will still send cookies.\n */\nexport type CredentialSource = 'cookie' | 'header';\n\n/** A bearer credential together with where it was read from. */\nexport interface ExtractedCredential {\n /** The raw bearer token value. */\n token: string;\n /** Whether the token came from the `axiam_access` cookie or the `Authorization` header — load-bearing for the CSRF gate (§3). */\n source: CredentialSource;\n}\n\n/**\n * Extract the bearer credential and its source: `axiam_access` cookie\n * first, falling back to `Authorization: Bearer <token>` (case-insensitive\n * scheme), else `undefined` — mirrors the Rust extractor's\n * cookie-then-Bearer order.\n */\nexport function extractCredential(\n cookieHeader: string | undefined,\n authHeader: string | undefined,\n): ExtractedCredential | undefined {\n const cookies = parseCookieHeader(cookieHeader);\n const cookieToken = cookies[ACCESS_COOKIE_NAME];\n if (cookieToken) {\n return { token: cookieToken, source: 'cookie' };\n }\n\n if (!authHeader) {\n return undefined;\n }\n\n const trimmed = authHeader.trim();\n const spaceIndex = trimmed.indexOf(' ');\n if (spaceIndex === -1) {\n return undefined;\n }\n const scheme = trimmed.slice(0, spaceIndex);\n const credentials = trimmed.slice(spaceIndex + 1).trim();\n if (scheme.toLowerCase() !== 'bearer' || !credentials) {\n return undefined;\n }\n return { token: credentials, source: 'header' };\n}\n\n/**\n * Extract just the bearer token, discarding its source. Retained for\n * backward compatibility with existing (non-CSRF-aware) callers/exports;\n * new code that needs to gate on credential source should call\n * {@link extractCredential} directly.\n */\nexport function extractToken(\n cookieHeader: string | undefined,\n authHeader: string | undefined,\n): string | undefined {\n return extractCredential(cookieHeader, authHeader)?.token;\n}\n\n/** Name of the double-submit CSRF cookie (`axiam_csrf`). */\nexport const CSRF_COOKIE_NAME = 'axiam_csrf';\n/** Name of the CSRF request header (`x-csrf-token`) matched against {@link CSRF_COOKIE_NAME}. */\nexport const CSRF_HEADER_NAME = 'x-csrf-token';\n\nconst SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);\n\n/**\n * Whether `method` is a \"safe\" (non-state-changing) HTTP method per\n * CONTRACT.md §3 (state-changing = POST/PUT/PATCH/DELETE). An\n * undefined/empty method is treated as safe: real Express/Fastify\n * requests always populate `req.method`, so this only affects\n * hand-constructed callers that omit it, and defaulting to \"no CSRF\n * required\" never weakens the check for a real HTTP request.\n */\nexport function isSafeMethod(method: string | undefined): boolean {\n if (!method) {\n return true;\n }\n return SAFE_METHODS.has(method.toUpperCase());\n}\n\n/**\n * Cookie double-submit check (CONTRACT.md §3): `csrfHeaderValue` (the\n * `X-CSRF-Token` request header) must be present and equal, in constant\n * time, to the `axiam_csrf` cookie value.\n *\n * Rationale: cookie-sourced requests aren't CSRF-immune, and in any\n * same-site deployment where `axiam_access` reaches the app, the\n * non-`httpOnly` `axiam_csrf` cookie does too (§3) — this mirrors, locally,\n * the same double-submit check the AXIAM server performs on its own\n * endpoints.\n *\n * Never throws: a missing header/cookie or a length mismatch both return\n * `false` (mirrors amqp/hmac.ts's `verifyPayload` idiom — `timingSafeEqual`\n * throws on unequal-length buffers, so length is checked first).\n */\nexport function isCsrfValid(\n cookieHeader: string | undefined,\n csrfHeaderValue: string | undefined,\n): boolean {\n if (!csrfHeaderValue) {\n return false;\n }\n const cookies = parseCookieHeader(cookieHeader);\n const csrfCookie = cookies[CSRF_COOKIE_NAME];\n if (!csrfCookie) {\n return false;\n }\n const received = Buffer.from(csrfHeaderValue, 'utf8');\n const expected = Buffer.from(csrfCookie, 'utf8');\n if (received.length !== expected.length) {\n return false;\n }\n return timingSafeEqual(received, expected);\n}\n","/**\n * The §27.4 rule 7 error sub-types.\n *\n * §2 fixes the taxonomy at three error types and §27 does not widen it. What\n * it adds is a *classification* inside two of them, because a management\n * surface produces refusals §2 never had to describe — §2 has no 404 row at\n * all, since nothing before §27 could return one.\n *\n * TypeScript has real subclassing, so these are subclasses: every\n * `catch (e) { if (e instanceof AuthzError) … }` written before §27 keeps\n * working, and a caller who needs the distinction narrows further.\n */\n\nimport { AuthzError, NetworkError } from '../core/errors.js';\n\n/** One field-level complaint inside a {@link ValidationError}. */\nexport interface FieldError {\n /** The offending field's name, as the server names it. */\n field: string;\n /** What is wrong with it. */\n message: string;\n}\n\n/**\n * HTTP 404 — the resource does not exist, **or** belongs to another tenant.\n *\n * The server answers identically in both cases on purpose: a distinguishable\n * \"exists but not yours\" lets a caller enumerate another tenant's ids. That is\n * why this is an {@link AuthzError} rather than a category of its own — in a\n * multi-tenant IAM the two really are one outcome.\n */\nexport class NotFoundError extends AuthzError {\n /** The registry operation that found nothing, e.g. `\"users.get\"`. */\n readonly operation: string;\n\n constructor(operation: string, message: string) {\n super(message);\n this.name = 'NotFoundError';\n this.operation = operation;\n Object.setPrototypeOf(this, NotFoundError.prototype);\n }\n}\n\n/**\n * HTTP 409 — a uniqueness or state conflict, such as a role name already taken.\n *\n * Never retried (§27.4 rule 8): a 409 is the server telling the truth, not a\n * transient fault, and a retry produces the identical answer one round-trip\n * later.\n */\nexport class ConflictError extends AuthzError {\n /** The registry operation that conflicted. */\n readonly operation: string;\n /**\n * The body's `reason_code`, as the server spelled it (contract 1.62, §36.4),\n * or `undefined` when the body carries none (a server that predates it, or a\n * `409` of an operation that does not name one).\n *\n * The `409` of every `network` operation says which conflict it is:\n * `stale_version`, `strands_profile`, `has_children`, `site_gone`,\n * `duplicate_name`, `duplicate_vlan`, `duplicate_rank`, `profile_exists` or\n * `other` (§36.3 rule 2). The vocabulary is **open**: a value this SDK does\n * not know is surfaced verbatim, and a caller branches on this member —\n * never on `message`, which an SDK must not parse. It is not the `reason` of\n * an authorization decision (§3), which is a human string.\n */\n readonly reasonCode?: string;\n\n constructor(operation: string, message: string, reasonCode?: string) {\n super(message);\n this.name = 'ConflictError';\n this.operation = operation;\n this.reasonCode = reasonCode;\n Object.setPrototypeOf(this, ConflictError.prototype);\n }\n}\n\n/**\n * HTTP 400/422 — the request was rejected.\n *\n * §2 maps 400 to `NetworkError`, described as an \"SDK programming error\". That\n * description was written when nothing but the SDK itself could produce a 400.\n * On this surface a 400 is usually a *user's* invalid input — an email that is\n * not an email, a slug already taken — and an application needs to tell that\n * from a broken socket without matching on message text. The parent type is\n * inherited from §2 rather than chosen here.\n */\nexport class ValidationError extends NetworkError {\n /** The HTTP status the server answered with — 400 or 422. */\n readonly status: number;\n /** The registry operation that was rejected. */\n readonly operation: string;\n /** Per-field detail, where the server sent any. Empty is normal. */\n readonly fields: FieldError[];\n\n constructor(operation: string, status: number, message: string, fields: FieldError[]) {\n super(message);\n this.name = 'ValidationError';\n this.status = status;\n this.operation = operation;\n this.fields = fields;\n Object.setPrototypeOf(this, ValidationError.prototype);\n }\n}\n\n/**\n * Pull field-level detail out of an error body, on a best-effort basis.\n *\n * Two shapes are recognised — an array of `{field, message}` and an object\n * keyed by field name. A body in neither shape yields no fields rather than an\n * error: failing to parse an error body would replace a useful message with a\n * useless one.\n *\n * @internal\n */\nexport function parseFieldErrors(body: unknown): FieldError[] {\n if (!body || typeof body !== 'object') return [];\n const errors = (body as { errors?: unknown }).errors;\n if (Array.isArray(errors)) {\n return errors.filter(\n (e): e is FieldError =>\n !!e && typeof e === 'object' && typeof (e as FieldError).field === 'string',\n );\n }\n if (errors && typeof errors === 'object') {\n return Object.entries(errors as Record<string, unknown>)\n .filter(([, v]) => typeof v === 'string')\n .map(([field, message]) => ({ field, message: message as string }));\n }\n return [];\n}\n","// MCP resource-server helpers (CONTRACT.md §28, RFC 9728 + RFC 6750) — the\n// ONE §28 implementation both the Express and Fastify surfaces are built on,\n// mirroring how `verifyCore.ts` is the one §10 verification path and\n// `authzCore.ts` the one §11 decision path.\n//\n// §28.0: this SDK implements the RESOURCE SERVER's half and nothing else.\n// AXIAM is the authorization server and implements none of §28; the MCP\n// client's half (parsing a challenge, fetching a document, deciding whether to\n// trust the authorization server it names) is deliberately not in this\n// contract version, for the same reason §20.3 stops at parsing.\n//\n// **No operation here performs network I/O**, so §16 (retry) and §9\n// (single-flight refresh) do not apply and nothing in this module touches the\n// SDK client's own session. All three operations are pure local computation,\n// like `oidcBegin` (§12.1) and `umaParseChallenge` (§20.5).\n//\n// **Nothing here is a source of truth about a token.** The document is a claim\n// a resource server publishes about itself; the challenge is a hint it gives a\n// caller that already failed. Whether a request is authorized stays §10.1's\n// and §11's decision, unchanged and unreachable from here.\n\nimport type { Request as ExpressRequest, Response as ExpressResponse, Router } from 'express';\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';\nimport { ReasonCode } from '../core/authz.js';\nimport { ValidationError } from '../management/errors.js';\nimport { extractCredential } from './cookieHeader.js';\n\n/**\n * RFC 9728 §3.1's well-known prefix — the segment inserted between a\n * resource's authority and its path to reach the document that describes it.\n */\nexport const PROTECTED_RESOURCE_METADATA_PREFIX = '/.well-known/oauth-protected-resource';\n\n/**\n * The three hosts §28.2 rule 2 lets an `http` URL use, and the only ones.\n *\n * They are AXIAM's RFC 8252 §7.3 loopback hosts, reused verbatim. There is\n * deliberately no flag, environment variable or debug build that widens this:\n * a resource server reachable over plaintext on a routable host publishes an\n * identifier an attacker can impersonate.\n */\nconst LOOPBACK_HOSTS: ReadonlySet<string> = new Set(['127.0.0.1', '[::1]', 'localhost']);\n\n/** RFC 6750 §3.1's three error codes — the complete vocabulary a challenge may name (§28.4). */\nexport type BearerChallengeError = 'invalid_request' | 'invalid_token' | 'insufficient_scope';\n\nconst BEARER_CHALLENGE_ERRORS: ReadonlySet<string> = new Set<BearerChallengeError>([\n 'invalid_request',\n 'invalid_token',\n 'insufficient_scope',\n]);\n\n// ---------------------------------------------------------------------------\n// Refusals (§28.2, §28.4, §28.5) — always `ValidationError`, never a new type\n// ---------------------------------------------------------------------------\n\n/**\n * Raise §28's refusal.\n *\n * §28.6 pins the error taxonomy: \"§28's refusals are `ValidationError`; no new\n * type\". This SDK's {@link ValidationError} is §27.4 rule 7's sub-type of\n * `NetworkError`, so `status` names the HTTP code an AXIAM server would answer\n * with for the same rejected field — **400** — even though no server was asked\n * and no request was made. `operation` names the §28 operation that refused,\n * the way a management refusal names `users.get`.\n */\nfunction refuse(operation: string, field: string, message: string): never {\n throw new ValidationError(operation, 400, `${field}: ${message} (CONTRACT.md §28)`, [\n { field, message },\n ]);\n}\n\n// ---------------------------------------------------------------------------\n// Character classes (RFC 6749 Appendix A) — §28.2 rule 5, §28.4\n// ---------------------------------------------------------------------------\n\n/** `NQCHAR`: `%x21` / `%x23`–`%x5B` / `%x5D`–`%x7E`. No space, no `\"`, no `\\`, no control, no non-ASCII. */\nfunction isNqchar(code: number): boolean {\n return code === 0x21 || (code >= 0x23 && code <= 0x5b) || (code >= 0x5d && code <= 0x7e);\n}\n\n/** `NQSCHAR`: `NQCHAR` plus the space (`%x20`). */\nfunction isNqschar(code: number): boolean {\n return code === 0x20 || isNqchar(code);\n}\n\nfunction isAll(value: string, predicate: (code: number) => boolean): boolean {\n for (let i = 0; i < value.length; i += 1) {\n if (!predicate(value.charCodeAt(i))) return false;\n }\n return true;\n}\n\n// ---------------------------------------------------------------------------\n// Absolute-URI parsing (§28.2 rules 1, 2, 3, 7)\n// ---------------------------------------------------------------------------\n\n/**\n * `scheme://authority[path][?query][#fragment]`, matched against the caller's\n * string exactly as given.\n *\n * Deliberately not `new URL()`: that parser *normalises* — it lowercases the\n * host, resolves `..` segments, appends a path to an authority-only URL and\n * re-encodes. §28.2 forbids adjusting a value to make it pass, and §28.3\n * derives the document's own path from this string, so what is validated must\n * be what was written.\n */\nconst ABSOLUTE_URI = /^([A-Za-z][A-Za-z0-9+.-]*):\\/\\/([^/?#]*)([^?#]*)(\\?[^#]*)?(#[\\s\\S]*)?$/;\n\n/** The pieces of an absolute URI, sliced out of the caller's string without normalisation. */\ninterface ParsedUri {\n /** The scheme, verbatim (compared case-insensitively, stored as written). */\n scheme: string;\n /** The authority, verbatim — `userinfo@host:port` included. */\n authority: string;\n /** The path component: empty, or starting with `/`. A trailing slash is preserved. */\n path: string;\n /** True when the string carried a `?`, even an empty one. */\n hasQuery: boolean;\n /** True when the string carried a `#`, even an empty one. */\n hasFragment: boolean;\n}\n\nfunction parseAbsoluteUri(raw: string): ParsedUri | undefined {\n const match = ABSOLUTE_URI.exec(raw);\n if (!match) return undefined;\n const authority = match[2] ?? '';\n if (authority === '') return undefined;\n return {\n scheme: match[1] ?? '',\n authority,\n path: match[3] ?? '',\n hasQuery: match[4] !== undefined,\n hasFragment: match[5] !== undefined,\n };\n}\n\n/**\n * The host inside an authority: `userinfo@` stripped, port stripped, an IPv6\n * literal's brackets kept (so `[::1]` compares as §28.2 rule 2 spells it).\n *\n * Stripping `userinfo` is what makes `http://localhost@evil.example.com/` a\n * refusal rather than a loopback pass — the host there is `evil.example.com`.\n */\nfunction hostOf(authority: string): string {\n const at = authority.lastIndexOf('@');\n const hostport = at >= 0 ? authority.slice(at + 1) : authority;\n if (hostport.startsWith('[')) {\n const close = hostport.indexOf(']');\n return close < 0 ? hostport : hostport.slice(0, close + 1);\n }\n const colon = hostport.indexOf(':');\n return colon < 0 ? hostport : hostport.slice(0, colon);\n}\n\n/** How much of §28.2 rule 1 a particular member is held to — rule 7 and §28.4's `resource_metadata` relax two parts of it. */\ninterface UriPolicy {\n /** `true` for `resource_documentation` (§28.2 rule 7) and `resource_metadata` (§28.4): a page for a human may be parameterised. */\n allowQuery: boolean;\n /** `true` for the same two members, for the same reason. */\n allowFragment: boolean;\n}\n\nconst IDENTIFIER: UriPolicy = { allowQuery: false, allowFragment: false };\nconst LOCATOR: UriPolicy = { allowQuery: true, allowFragment: true };\n\n/**\n * §28.2 rules 1 and 2, applied to one member. Returns the parse so a caller\n * that needs the path (§28.3) does not parse twice.\n */\nfunction requireAbsoluteUri(\n operation: string,\n field: string,\n raw: unknown,\n policy: UriPolicy,\n): ParsedUri {\n if (typeof raw !== 'string' || raw === '') {\n refuse(operation, field, 'must be a non-empty absolute URI');\n }\n const parsed = parseAbsoluteUri(raw);\n if (!parsed) {\n refuse(\n operation,\n field,\n `must be an absolute URI with a scheme and an authority, not ${JSON.stringify(raw)}`,\n );\n }\n if (parsed.hasQuery && !policy.allowQuery) {\n refuse(operation, field, 'must carry no query — §28.3 derives the metadata path from it');\n }\n if (parsed.hasFragment && !policy.allowFragment) {\n refuse(operation, field, 'must carry no fragment');\n }\n const scheme = parsed.scheme.toLowerCase();\n if (scheme === 'https') return parsed;\n if (scheme === 'http' && LOOPBACK_HOSTS.has(hostOf(parsed.authority).toLowerCase())) {\n return parsed;\n }\n refuse(\n operation,\n field,\n `must use https — http is accepted only on 127.0.0.1, [::1] or localhost, and ${JSON.stringify(raw)} is neither`,\n );\n}\n\nfunction requireList(operation: string, field: string, value: unknown): readonly unknown[] {\n if (!Array.isArray(value)) refuse(operation, field, 'must be a list');\n return value;\n}\n\n// ---------------------------------------------------------------------------\n// §28.1 / §28.2 — `protectedResourceMetadata`\n// ---------------------------------------------------------------------------\n\n/**\n * The RFC 9728 §2 document, carrying **at most** the five members §28.2\n * permits, in that order, and no others.\n *\n * Member names are the wire names, because this object serializes to the\n * document byte for byte. RFC 9728 defines further members; §28.2 forbids\n * emitting them in this contract version — a member one SDK emits and ten do\n * not is a divergence the cross-SDK review would have to reconcile.\n *\n * Two members are **omitted rather than emitted empty or `null`**:\n * `scopes_supported` when the caller passed no scopes, and\n * `resource_documentation` when the caller passed none.\n */\nexport interface ProtectedResourceMetadataDocument {\n /** The resource identifier this server publishes for itself — the string an RFC 8707 `resource` parameter carries and the `aud` the guard checks. */\n readonly resource: string;\n /** The issuer identifiers of the authorization servers that guard this resource. At least one, each verbatim. */\n readonly authorization_servers: readonly string[];\n /** The scope tokens this resource server understands, in the caller's order. Omitted when the caller passed none. */\n readonly scopes_supported?: readonly string[];\n /** Always `[\"header\"]` in this contract version — §10's guard reads a bearer credential from the `Authorization` header alone. */\n readonly bearer_methods_supported: readonly string[];\n /** A human-readable documentation page. Omitted when the caller passed none; never `null`. */\n readonly resource_documentation?: string;\n}\n\n/**\n * The arguments of §28.1's `protected_resource_metadata`, as one options\n * object — this SDK's idiom for a constructor with five inputs, and the shape\n * `RequireAccessOptions` and `OidcLoginOptions` already use. The canonical\n * order is preserved in the declaration so a port author can read the two\n * side by side.\n */\nexport interface ProtectedResourceMetadataOptions {\n /** The resource identifier. Absolute, `https` (or `http` on a loopback host), with no query and no fragment. A trailing slash is significant. */\n resource: string;\n /** The issuer identifiers of the authorization servers guarding it — at least one, no duplicates, no query, no fragment. */\n authorizationServers: readonly string[];\n /** The scope tokens this resource server understands. Order is preserved, duplicates are refused, and an empty list omits the member. */\n scopesSupported: readonly string[];\n /** Defaults to `[\"header\"]`, and `[\"header\"]` is the only accepted value in this contract version. */\n bearerMethodsSupported?: readonly string[];\n /** Optional documentation page for a human. May carry a query and a fragment; omitted from the document when absent. */\n resourceDocumentation?: string;\n}\n\n/**\n * What {@link protectedResourceMetadata} returns: the document, the path it is\n * served at, and the URL that path resolves to.\n *\n * {@link ProtectedResourceMetadata.metadataUrl} exists so that the guard's\n * `resourceMetadataUrl` option is fed from the helper that derived it rather\n * than retyped — retyping is how the two come to disagree, and a challenge\n * pointing at a document that is not this resource server's is worse than no\n * challenge at all.\n */\nexport interface ProtectedResourceMetadata {\n /** The RFC 9728 §2 document, ready to serialize. */\n readonly document: ProtectedResourceMetadataDocument;\n /** The absolute path the document is served at, derived from the resource per §28.3 — never chosen. */\n readonly metadataPath: string;\n /** {@link ProtectedResourceMetadata.metadataPath} resolved against the resource's scheme and authority. Feed this to the guard's `resourceMetadataUrl`. */\n readonly metadataUrl: string;\n}\n\n/**\n * `protectedResourceMetadata(options)` (CONTRACT.md §28.1) — build and\n * validate the RFC 9728 protected-resource metadata document this server\n * publishes about itself, and derive the path and URL it is served at.\n *\n * @remarks\n * **Validation happens here and it refuses; it never repairs.** Every §28.2\n * rule is checked before any route exists and before any request is served,\n * and a violation throws `ValidationError`. Nothing is normalised, trimmed,\n * lowercased or re-encoded to make it pass: a value that needs adjusting is a\n * configuration mistake an operator fixes in one line, and a helper that\n * quietly fixed it would publish a document describing a resource server that\n * does not exist.\n *\n * **Nothing in the document may come from a request** (§28.2 rule 8). Both\n * `resource` and `authorizationServers` are configuration; this SDK offers no\n * option to build either from the `Host` header, the `Forwarded`/`X-Forwarded-*`\n * family or the request URL, because a document assembled from the request is\n * a document an attacker can point at an authorization server of their\n * choosing — the whole handshake redirected with one header.\n *\n * @example\n * ```ts\n * const metadata = protectedResourceMetadata({\n * resource: 'https://mcp.example.com/mcp',\n * authorizationServers: ['https://axiam.example.com'],\n * scopesSupported: ['mcp:read', 'mcp:tools'],\n * });\n * metadata.metadataPath; // '/.well-known/oauth-protected-resource/mcp'\n * metadata.metadataUrl; // 'https://mcp.example.com/.well-known/oauth-protected-resource/mcp'\n * ```\n *\n * @throws ValidationError when any §28.2 rule is violated.\n */\nexport function protectedResourceMetadata(\n options: ProtectedResourceMetadataOptions,\n): ProtectedResourceMetadata {\n const op = 'protectedResourceMetadata';\n\n // Rule 1 + rule 2.\n const resource = options.resource;\n const parsed = requireAbsoluteUri(op, 'resource', resource, IDENTIFIER);\n\n // Rule 3 + rule 4: at least one entry, each an issuer verbatim, no duplicates.\n const servers = requireList(op, 'authorization_servers', options.authorizationServers);\n if (servers.length === 0) {\n refuse(\n op,\n 'authorization_servers',\n 'must name at least one authorization server — a document that names none answers none of the question the client asked',\n );\n }\n const seenServers = new Set<string>();\n const authorizationServers: string[] = [];\n for (const entry of servers) {\n requireAbsoluteUri(op, 'authorization_servers', entry, IDENTIFIER);\n const issuer = entry as string;\n if (seenServers.has(issuer)) {\n refuse(op, 'authorization_servers', `duplicate entry ${JSON.stringify(issuer)}`);\n }\n seenServers.add(issuer);\n authorizationServers.push(issuer);\n }\n\n // Rule 5: NQCHAR tokens, order preserved, duplicates refused, empty omits.\n const scopes = requireList(op, 'scopes_supported', options.scopesSupported);\n const seenScopes = new Set<string>();\n const scopesSupported: string[] = [];\n for (const scope of scopes) {\n if (typeof scope !== 'string' || scope === '' || !isAll(scope, isNqchar)) {\n refuse(\n op,\n 'scopes_supported',\n `${JSON.stringify(scope)} is not a scope token — one or more NQCHAR (no space, no '\"', no '\\\\', no control character, no non-ASCII)`,\n );\n }\n if (seenScopes.has(scope)) refuse(op, 'scopes_supported', `duplicate scope ${JSON.stringify(scope)}`);\n seenScopes.add(scope);\n scopesSupported.push(scope);\n }\n\n // Rule 6: exactly [\"header\"].\n const methods = requireList(\n op,\n 'bearer_methods_supported',\n options.bearerMethodsSupported ?? ['header'],\n );\n if (methods.length !== 1 || methods[0] !== 'header') {\n refuse(\n op,\n 'bearer_methods_supported',\n `must be exactly [\"header\"] in this contract version — §10's guard reads a bearer credential from the Authorization header alone, so ${JSON.stringify(methods)} would describe behaviour this SDK does not have`,\n );\n }\n\n // Rule 7: absolute URL, query and fragment permitted, omitted when absent.\n const documentation = options.resourceDocumentation;\n if (documentation !== undefined) {\n requireAbsoluteUri(op, 'resource_documentation', documentation, LOCATOR);\n }\n\n // §28.2 fixes the member order. Insertion order is what `JSON.stringify`\n // emits, so the conditional spreads sit where the omitted members belong.\n const document: ProtectedResourceMetadataDocument = Object.freeze({\n resource,\n authorization_servers: Object.freeze(authorizationServers) as readonly string[],\n ...(scopesSupported.length > 0\n ? { scopes_supported: Object.freeze(scopesSupported) as readonly string[] }\n : {}),\n bearer_methods_supported: Object.freeze(['header']) as readonly string[],\n ...(documentation !== undefined ? { resource_documentation: documentation } : {}),\n });\n\n const metadataPath = deriveMetadataPath(parsed.path);\n return Object.freeze({\n document,\n metadataPath,\n metadataUrl: `${parsed.scheme}://${parsed.authority}${metadataPath}`,\n });\n}\n\n/**\n * §28.3's derivation: RFC 9728 §3.1 inserts the well-known segment between the\n * authority and the path. An empty path and a bare `/` both reach the root\n * form; anything else is appended, **trailing slash included** — it is part of\n * the identifier a client compares, and two resources that differ only by it\n * are two resources.\n */\nfunction deriveMetadataPath(resourcePath: string): string {\n if (resourcePath === '' || resourcePath === '/') return PROTECTED_RESOURCE_METADATA_PREFIX;\n return PROTECTED_RESOURCE_METADATA_PREFIX + resourcePath;\n}\n\n// ---------------------------------------------------------------------------\n// §28.4 — `bearerChallenge`\n// ---------------------------------------------------------------------------\n\n/** The arguments of §28.1's `bearer_challenge`, in canonical order. */\nexport interface BearerChallengeOptions {\n /** The document's URL — the one parameter that is always present. May carry a query and a fragment. */\n resourceMetadataUrl: string;\n /** One of RFC 6750 §3.1's three codes, or absent when the request carried no authentication information at all. */\n error?: BearerChallengeError;\n /**\n * A human-readable description, for an application building **its own**\n * challenge for its own 400.\n *\n * The SDK's guards never set it: expired, not yet valid, wrong tenant, wrong\n * audience, bad signature, `alg` confusion, an unsatisfiable `cnf`, a revoked\n * `sid` — §28.4 makes all of them `invalid_token`, indistinguishably. Every\n * distinction a 401 draws for an unauthenticated stranger is an oracle.\n */\n errorDescription?: string;\n /** The scope the route asked for, verbatim — one or more tokens joined by a single space. */\n scope?: string;\n}\n\n/**\n * `bearerChallenge(options)` (CONTRACT.md §28.4) — build the **value** of a\n * `WWW-Authenticate` header, never the whole header line and never a map. The\n * caller sets the header.\n *\n * @remarks\n * Parameters appear in a fixed order — `error`, `error_description`, `scope`,\n * `resource_metadata` — separated by exactly `, `. `resource_metadata` is\n * always present; the other three are omitted when not given.\n *\n * **Every value is quoted and no value is ever escaped.** RFC 6750 §3 restricts\n * each parameter to a character set that cannot contain `\"` or `\\`, so a value\n * needing an escape is a value that does not belong in a challenge: this\n * function refuses it rather than escaping, truncating or stripping it. A\n * challenge is built from the code's own constants and a route's own\n * configuration, so an invalid one is a programming error, not a runtime\n * condition to degrade around.\n *\n * @example\n * ```ts\n * bearerChallenge({ resourceMetadataUrl: metadata.metadataUrl });\n * // Bearer resource_metadata=\"https://mcp.example.com/.well-known/oauth-protected-resource/mcp\"\n *\n * bearerChallenge({ resourceMetadataUrl: metadata.metadataUrl, error: 'insufficient_scope', scope: 'mcp:tools' });\n * // Bearer error=\"insufficient_scope\", scope=\"mcp:tools\", resource_metadata=\"https://…/mcp\"\n * ```\n *\n * @throws ValidationError when any parameter is outside RFC 6750's syntax.\n */\nexport function bearerChallenge(options: BearerChallengeOptions): string {\n const op = 'bearerChallenge';\n const params: string[] = [];\n\n if (options.error !== undefined) {\n if (!BEARER_CHALLENGE_ERRORS.has(options.error)) {\n refuse(\n op,\n 'error',\n `must be one of invalid_request, invalid_token, insufficient_scope — RFC 6750 §3.1 defines no others, and ${JSON.stringify(options.error)} is not among them`,\n );\n }\n params.push(`error=\"${options.error}\"`);\n }\n\n if (options.errorDescription !== undefined) {\n const description = options.errorDescription;\n if (typeof description !== 'string' || description === '' || !isAll(description, isNqschar)) {\n refuse(\n op,\n 'error_description',\n 'must be one or more NQSCHAR (no \\'\"\\', no \\'\\\\\\', no control character, no non-ASCII) — a value needing an escape does not belong in a challenge',\n );\n }\n params.push(`error_description=\"${description}\"`);\n }\n\n if (options.scope !== undefined) {\n const scope = options.scope;\n if (typeof scope !== 'string' || scope === '') {\n refuse(op, 'scope', 'must be one or more scope tokens joined by a single space');\n }\n for (const token of scope.split(' ')) {\n if (token === '' || !isAll(token, isNqchar)) {\n refuse(\n op,\n 'scope',\n `${JSON.stringify(scope)} is not a space-joined list of scope tokens — no leading, trailing or doubled space, and no empty token`,\n );\n }\n }\n params.push(`scope=\"${scope}\"`);\n }\n\n const url = options.resourceMetadataUrl;\n requireAbsoluteUri(op, 'resource_metadata', url, LOCATOR);\n if (!isAll(url, isNqchar)) {\n refuse(\n op,\n 'resource_metadata',\n 'must carry no \\'\"\\', no \\'\\\\\\', no space and no control character — a correctly encoded URL cannot, so one that does has not been encoded',\n );\n }\n params.push(`resource_metadata=\"${url}\"`);\n\n return `Bearer ${params.join(', ')}`;\n}\n\n// ---------------------------------------------------------------------------\n// §28.5 — the `resourceMetadataUrl` guard option\n// ---------------------------------------------------------------------------\n\n/**\n * The two guard settings §28.5 reads. Satisfied structurally by\n * `VerifiableSession`, which is where an integrator actually sets them; taken\n * as its own shape so `serveProtectedResourceMetadata` can cross-check a guard\n * without depending on the verification core.\n */\nexport interface McpGuardConfig {\n /** §10.1 row 6's expected audience, under the name this SDK already gives it. §28 adds no second audience option. */\n expectedAudience?: string;\n /** §28.5's option: the URL of this resource server's metadata document. Setting it is what turns §28 on. */\n resourceMetadataUrl?: string;\n}\n\n/**\n * The §28 challenge values a guard emits, all built once at guard-construction\n * time so that an invalid one is a startup failure rather than a surprise on\n * the 401 path.\n *\n * `undefined` where {@link McpGuardConfig.resourceMetadataUrl} is unset, which\n * is how \"§28 is off\" stays byte-for-byte indistinguishable from \"§28 is\n * absent\" (§28.5 rule 1).\n */\nexport interface McpGuardChallenges {\n /** §28.4 vector 1 — the request carried **no** authentication information, so RFC 6750 §3 says not to name an error. */\n readonly noCredential: string;\n /** §28.4 vector 2 — a credential was presented and rejected. The only thing the 401 ever says about why. */\n readonly invalidToken: string;\n /** §28.4 vector 3 — present only where the route named a scope; emitted on a `no_grant` denial and nowhere else. */\n readonly insufficientScope?: string;\n /** The document's path, exempted from authentication by the §10 guard (§28.3 rule 2). */\n readonly metadataPath: string;\n}\n\n/**\n * Validate a guard's §28 configuration and precompute the challenges it will\n * emit. Called by every guard factory at construction time — route-setup time,\n * never per-request.\n *\n * @remarks\n * Returns `undefined` when `resourceMetadataUrl` is unset: §28 is opt-in, and\n * with the option absent the guard behaves exactly as it did before §28\n * existed — no header on any response, no status changed, no body changed.\n *\n * **`expectedAudience` is mandatory once `resourceMetadataUrl` is set**, and\n * the refusal names both options. A resource server that publishes \"tokens for\n * me carry this `aud`\" and then does not check `aud` has published a claim it\n * does not honour, and a token minted for a *different* resource server opens\n * it. That is the confusion RFC 8707 exists to prevent, so this is a refusal\n * rather than a warning.\n *\n * @param guard - the session the guard was built from.\n * @param operation - the guard factory's name, so the refusal says which guard refused.\n * @param scope - the route's `scope` argument, where it has one (§28.5 rule 5).\n * @throws ValidationError when `resourceMetadataUrl` is set without an expected audience, or when either it or `scope` is outside §28.4's syntax.\n */\nexport function mcpGuardChallenges(\n guard: McpGuardConfig,\n operation: string,\n scope?: string,\n): McpGuardChallenges | undefined {\n const resourceMetadataUrl = guard.resourceMetadataUrl;\n if (resourceMetadataUrl === undefined) return undefined;\n\n if (guard.expectedAudience === undefined || guard.expectedAudience === '') {\n refuse(\n operation,\n 'resourceMetadataUrl',\n 'requires expectedAudience to be set on the same session (CONTRACT.md §28.5 rule 2) — announcing a resource identifier obliges this server to check that an inbound token\\'s `aud` is that identifier, and a resource server that announces itself without checking is opened by a token minted for somebody else',\n );\n }\n\n const parsed = requireAbsoluteUri(operation, 'resourceMetadataUrl', resourceMetadataUrl, LOCATOR);\n return Object.freeze({\n noCredential: bearerChallenge({ resourceMetadataUrl }),\n invalidToken: bearerChallenge({ resourceMetadataUrl, error: 'invalid_token' }),\n ...(scope !== undefined\n ? {\n insufficientScope: bearerChallenge({\n resourceMetadataUrl,\n error: 'insufficient_scope',\n scope,\n }),\n }\n : {}),\n metadataPath: parsed.path === '' ? '/' : parsed.path,\n });\n}\n\n/**\n * Pick between §28.4's first two vectors for a 401: `invalid_token` when the\n * request carried a credential, no `error` at all when it carried none.\n *\n * §28.4 is explicit that the absent `error` is not an oversight — RFC 6750 §3\n * says a resource server SHOULD NOT name an error code when the request\n * carried no authentication information, because no credential is not a bad\n * credential, and a client has to be able to tell the two apart.\n *\n * @internal\n */\nexport function challengeFor401(\n challenges: McpGuardChallenges,\n cookieHeader: string | undefined,\n authorizationHeader: string | undefined,\n): string {\n return extractCredential(cookieHeader, authorizationHeader)\n ? challenges.invalidToken\n : challenges.noCredential;\n}\n\n/**\n * §28.5 rule 5: the one class of 403 that carries a challenge, and only it.\n *\n * A `no_grant` denial on a route that named a scope means *ask for more*,\n * which is exactly what a challenge invites a client to do. A `denied_by_rule`\n * denial means *an administrator has already decided*, and challenging on it\n * sends an MCP client all the way around the authorization loop to arrive at\n * the identical 403. An absent or unrecognised `reason_code` — an older server,\n * a value this SDK predates — is not eligible either: §11 rule 9 requires an\n * unknown code to leave the outcome alone, and the outcome here is a\n * header-free 403.\n *\n * @internal\n */\nexport function challengeFor403(\n challenges: McpGuardChallenges | undefined,\n reasonCode: string | undefined,\n): string | undefined {\n if (!challenges?.insufficientScope) return undefined;\n return reasonCode === ReasonCode.NO_GRANT ? challenges.insufficientScope : undefined;\n}\n\n/**\n * Is this request the unauthenticated `GET` of the metadata document?\n *\n * §28.3 rule 2 requires the document to be reachable with no credential of any\n * kind, and requires the SDK to exempt the path explicitly where the §10 guard\n * is applied globally — which is the normal Express `app.use(...)` and Fastify\n * `preHandler` arrangement. A document that 401s cannot start the handshake it\n * exists to start: the client would be holding a 401 and being told to go read\n * a page that answers 401.\n *\n * The exemption is derived from `resourceMetadataUrl`, so it exists only where\n * §28 is configured and covers exactly the one path that option names.\n *\n * @internal\n */\nexport function isMetadataDocumentRequest(\n challenges: McpGuardChallenges | undefined,\n method: string | undefined,\n url: string | undefined,\n): boolean {\n if (!challenges || typeof url !== 'string') return false;\n const verb = (method ?? '').toUpperCase();\n if (verb !== 'GET' && verb !== 'HEAD') return false;\n const end = url.search(/[?#]/);\n return (end < 0 ? url : url.slice(0, end)) === challenges.metadataPath;\n}\n\n// ---------------------------------------------------------------------------\n// §28.3 — `serveProtectedResourceMetadata`\n// ---------------------------------------------------------------------------\n\n/**\n * The framework object `serveProtectedResourceMetadata` registers on — §10's\n * table, unchanged: an Express application or router, or a Fastify instance.\n */\nexport type McpMetadataApp = Router | FastifyInstance;\n\n/**\n * `serveProtectedResourceMetadata(app, metadata, guard?)` (CONTRACT.md §28.3) —\n * register the one `GET` route that serves the document, on the framework's\n * own router, and return the same metadata value so the guard's\n * `resourceMetadataUrl` can be fed from it.\n *\n * @remarks\n * **The path is derived, not chosen**, and **exactly one route is registered.**\n * The root form is not also registered for a resource that has a path: a\n * deployment fronting two resources would then have two helpers competing for\n * the same root path and registration order would decide the loser. A\n * deployment fronting several resources calls this once per resource, and the\n * derived paths cannot collide because each comes from its own resource.\n *\n * The response is `200` with `Content-Type: application/json`, the document as\n * its body, `Cache-Control: public, max-age=3600` and\n * `Access-Control-Allow-Origin: *` — the last because an MCP client running in\n * a browser cannot read the document without it, and it is safe precisely\n * because the response is identical for every caller. It carries no\n * `Access-Control-Allow-Credentials`, which would be asking a browser to attach\n * the user's cookies to a request that has no use for them. Nothing is read\n * from the request, so there is no `Set-Cookie` and no per-caller content, and\n * §3a does not apply: it is a `GET`, and §3a is scoped to state-changing\n * methods and cookie-sourced credentials.\n *\n * **Serving it needs no route ordering.** Where the §10 guard is mounted\n * globally it exempts this exact path itself, from the `resourceMetadataUrl`\n * it was configured with — so the route works whether it is registered before\n * or after the guard, and on Fastify, where a `preHandler` hook applies\n * regardless of registration order.\n *\n * @param app - an Express application/router, or a Fastify instance. Register on the application root: a router mounted under a prefix would serve the document at a path the derived URL does not name.\n * @param metadata - the value {@link protectedResourceMetadata} returned.\n * @param guard - optionally, the session the §10 guard is built from. Passing it is what lets this SDK apply §28.5 rule 3 — see below.\n *\n * @throws ValidationError when `guard` is given and its `resourceMetadataUrl`\n * is not exactly the document's `metadataUrl`, or its `expectedAudience` is not\n * exactly the document's `resource`.\n *\n * Both comparisons are simple string equality (RFC 3986 §6.2.1): no\n * normalisation, no case folding of the host, no trailing-slash tolerance. A\n * trailing slash that differs between the document and the guard is a real\n * misconfiguration that will make a real client's `aud` check fail, and\n * startup is a better place to hear about it than a support ticket. Note that\n * the two strings compared are *different* strings — the resource is\n * `https://mcp.example.com/mcp` and the metadata URL is\n * `https://mcp.example.com/.well-known/oauth-protected-resource/mcp` — so each\n * is compared against its own counterpart.\n *\n * Where the guard is configured in another process this SDK can see only one\n * side and checks nothing; omit the argument there and configure both from one\n * constant, which is what `metadataUrl` is for.\n *\n * @example\n * ```ts\n * const metadata = protectedResourceMetadata({\n * resource: 'https://mcp.example.com/mcp',\n * authorizationServers: ['https://axiam.example.com'],\n * scopesSupported: ['mcp:read', 'mcp:tools'],\n * });\n * const session = {\n * ...baseSession,\n * expectedAudience: metadata.document.resource,\n * resourceMetadataUrl: metadata.metadataUrl,\n * };\n *\n * app.use(axiamMiddleware(session));\n * serveProtectedResourceMetadata(app, metadata, session);\n * ```\n */\nexport function serveProtectedResourceMetadata(\n app: McpMetadataApp,\n metadata: ProtectedResourceMetadata,\n guard?: McpGuardConfig,\n): ProtectedResourceMetadata {\n const op = 'serveProtectedResourceMetadata';\n\n if (guard) {\n if (guard.resourceMetadataUrl !== metadata.metadataUrl) {\n refuse(\n op,\n 'resourceMetadataUrl',\n `is ${JSON.stringify(guard.resourceMetadataUrl)} but this document is published at ${JSON.stringify(metadata.metadataUrl)} — the challenge would point at a document that is not this resource server's`,\n );\n }\n if (guard.expectedAudience !== metadata.document.resource) {\n refuse(\n op,\n 'expectedAudience',\n `is ${JSON.stringify(guard.expectedAudience)} but this document announces ${JSON.stringify(metadata.document.resource)} — the document would announce one identifier while the guard checked \\`aud\\` against another, so every token the flow produced would be refused`,\n );\n }\n }\n\n // Serialized once: the response is identical for every caller (§28.3 rule 4),\n // so there is nothing per-request to build.\n const body = JSON.stringify(metadata.document);\n\n if (isFastify(app)) {\n // Fastify appends `; charset=utf-8` to any `*json*` content type that\n // carries no charset parameter, and offers no supported way to suppress\n // it short of writing to `reply.raw` and losing every `onSend` hook. The\n // media type is still `application/json`, which is what §28.3 rule 1 pins\n // and what a client parses; the Express surface emits the bare form.\n app.get(metadata.metadataPath, async (_request: FastifyRequest, reply: FastifyReply) =>\n reply\n .code(200)\n .header('content-type', 'application/json')\n .header('cache-control', 'public, max-age=3600')\n .header('access-control-allow-origin', '*')\n .send(body),\n );\n return metadata;\n }\n\n app.get(metadata.metadataPath, (_req: ExpressRequest, res: ExpressResponse) => {\n // `res.setHeader`/`res.end` rather than `res.type`/`res.json`: Express\n // appends `; charset=utf-8` to a content type set through its own helper,\n // and §28.3 rule 1 pins the header to `application/json`.\n res.statusCode = 200;\n res.setHeader('Content-Type', 'application/json');\n res.setHeader('Cache-Control', 'public, max-age=3600');\n res.setHeader('Access-Control-Allow-Origin', '*');\n res.end(body);\n });\n return metadata;\n}\n\n/**\n * Tell a Fastify instance from an Express application/router.\n *\n * `addHook` is the discriminator: Fastify has it and Express has nothing of\n * the kind, so this never depends on how either library spells `get`.\n */\nfunction isFastify(app: McpMetadataApp): app is FastifyInstance {\n return typeof (app as Partial<FastifyInstance>).addHook === 'function';\n}\n","// Shared \"Login with AXIAM\" core (CONTRACT.md §12) — the ONE\n// begin/complete + state-store + error-mapping path both the Express\n// `oidcLoginHandlers` and the Fastify `oidcLoginPlugin` call, mirroring how\n// `authzCore.ts` is the one §11 path and `verifyCore.ts` the one §10 path.\n//\n// This module is framework-agnostic on purpose: it takes plain values in and\n// returns a discriminated `OidcLoginOutcome` out, so each adapter only has to\n// translate an outcome into that framework's redirect/JSON response. It\n// performs no token extraction, sets no cookie, and touches no `req`/`reply`\n// object.\n//\n// The state store is what makes the two HTTP requests of a redirect flow into\n// one login: `oidcBegin` produces `state`/`nonce`/`code_verifier` in the\n// login request, and only `state` survives the round trip through the IdP, so\n// the other two must be parked somewhere the callback request can reach\n// (§12.3 rule 1 — the SDK itself stores nothing).\n\nimport { AuthError, NetworkError } from '../core/index.js';\nimport type { OidcClient } from '../node/oidc.js';\nimport type { OidcStateEntry, OidcStateStore } from '../node/oidcState.js';\nimport type { OidcTokenSet } from '../node/oidcTypes.js';\nimport type { AuthzLogger, ErrorBody } from './authzCore.js';\n\n/** Configuration shared by the login and callback handlers (CONTRACT.md §12). */\nexport interface OidcLoginOptions {\n /** The relying-party client driving the flow (built with `createOidcClient`). */\n client: OidcClient;\n /**\n * Where in-flight login state is parked between the login redirect and the\n * callback. {@link MemoryOidcStateStore} is a ready single-process\n * implementation; a multi-instance deployment needs a shared one.\n */\n store: OidcStateStore;\n /**\n * The relying party's redirect URI — must be the public URL of the callback\n * route, and is replayed verbatim on the token exchange (the server compares\n * the two).\n */\n redirectUri: string;\n /** Requested scope. `openid` is added automatically when absent (§12.1 rule 4). */\n scope?: string | string[];\n /** Where to send the browser after a successful login. Falls back to the `returnTo` captured at login time, then to a JSON summary. */\n successRedirect?: string;\n /**\n * Called with the validated token set once the exchange succeeds — the hook\n * where an application establishes its OWN session (sign a cookie, write a\n * session row, …). The SDK deliberately does not do this for you: what a\n * session means is the application's decision.\n *\n * Receives the consumed state entry too, so `returnTo` and any other\n * application data captured at login time is available.\n */\n onSuccess?: (tokens: OidcTokenSet, entry: OidcStateEntry) => void | Promise<void>;\n /** Debug-only logger. Receives failure reasons, never token material, `state`, `nonce` or the verifier. */\n logger?: AuthzLogger;\n}\n\n/**\n * What a login/callback handler should do next — one arm per response shape.\n * Adapters translate this into their framework's API and add nothing of their\n * own, so Express and Fastify cannot drift.\n */\nexport type OidcLoginOutcome =\n | {\n /** Send a 302 to {@link url}. */\n kind: 'redirect';\n /** Target of the redirect: the IdP authorization URL, or the post-login destination. */\n url: string;\n }\n | {\n /** Reply `200` with {@link body} — the fallback when no post-login redirect is configured. */\n kind: 'json';\n /** A token-free summary of the established login. */\n body: OidcLoginSuccessBody;\n }\n | {\n /** Reply {@link status} with the standardized `{ error, message }` body. */\n kind: 'error';\n /** HTTP status: 400 malformed callback, 401 authentication failure, 503 AXIAM unreachable. */\n status: number;\n /** Standardized error body (§10/§11 shape). */\n body: ErrorBody;\n };\n\n/** The token-free success summary returned when no post-login redirect is configured. */\nexport interface OidcLoginSuccessBody {\n /** Always `true` — the ID token validated and the login completed. */\n authenticated: true;\n /** The authenticated subject from the validated ID token, when the server issued one. */\n sub?: string;\n /** Access-token lifetime in seconds, for a caller sizing its own session. */\n expiresIn: number;\n}\n\n/** The callback query parameters the flow reads (RFC 6749 §4.1.2 / §4.1.2.1). */\nexport interface OidcCallbackQuery {\n /** The `state` the IdP echoed back — matched against the stored entry. */\n state?: string;\n /** The authorization code, on success. */\n code?: string;\n /** An RFC 6749 error code, when the IdP refused instead of issuing a code. */\n error?: string;\n /** The IdP's description of {@link error}. */\n error_description?: string;\n}\n\nfunction authenticationFailedBody(message: string): ErrorBody {\n return { error: 'authentication_failed', message };\n}\n\nfunction invalidRequestBody(message: string): ErrorBody {\n return { error: 'invalid_request', message };\n}\n\nfunction unavailableBody(message: string): ErrorBody {\n return { error: 'oidc_unavailable', message };\n}\n\n/**\n * Step 1 — build the authorization request, park its state, and hand back the\n * redirect (CONTRACT.md §12.1 `oidc_begin`).\n *\n * Discovery is fetched through `oidcDiscover`, so its per-origin cache and\n * single-flight de-duplication apply and a busy login route does not hammer\n * the discovery endpoint (§12.3 rule 6).\n *\n * @param options the shared login configuration.\n * @param returnTo optional application destination to restore after login;\n * stored with the state entry and used as the post-login redirect when\n * `successRedirect` is unset.\n */\nexport async function beginOidcLogin(\n options: OidcLoginOptions,\n returnTo?: string,\n): Promise<OidcLoginOutcome> {\n try {\n const configuration = await options.client.oidcDiscover();\n const request = options.client.oidcBegin({\n configuration,\n redirectUri: options.redirectUri,\n ...(options.scope !== undefined ? { scope: options.scope } : {}),\n });\n await options.store.save({\n state: request.state,\n nonce: request.nonce,\n codeVerifier: request.codeVerifier,\n redirectUri: options.redirectUri,\n ...(returnTo !== undefined ? { returnTo } : {}),\n });\n return { kind: 'redirect', url: request.url };\n } catch (err) {\n // A login route that cannot reach AXIAM must fail closed with 503 rather\n // than redirect the browser somewhere half-built.\n options.logger?.debug('axiam_sdk.oidc', 'oidc login could not be started', {\n reason: err instanceof Error ? err.message : 'unknown',\n });\n return { kind: 'error', status: 503, body: unavailableBody('could not start the OIDC login flow') };\n }\n}\n\n/**\n * Step 2 — validate the callback, consume the stored state, exchange the code,\n * and hand back the post-login response (CONTRACT.md §12.1 `oidc_exchange`).\n *\n * Failure mapping:\n * - IdP returned `error=…` instead of a code → `401 authentication_failed`;\n * - `state` or `code` missing → `400 invalid_request`;\n * - `state` unknown, already consumed, or expired → `401 authentication_failed`\n * (all three are deliberately indistinguishable to the client);\n * - any §12.4 ID-token failure or `OAuthProtocolError` (an `AuthError`\n * sub-type) → `401 authentication_failed`;\n * - `NetworkError` → `503 oidc_unavailable`, never a silent success.\n */\nexport async function completeOidcLogin(\n options: OidcLoginOptions,\n query: OidcCallbackQuery,\n): Promise<OidcLoginOutcome> {\n if (query.error) {\n options.logger?.debug('axiam_sdk.oidc', 'idp returned an authorization error', { error: query.error });\n return {\n kind: 'error',\n status: 401,\n body: authenticationFailedBody(\n query.error_description ? `${query.error}: ${query.error_description}` : query.error,\n ),\n };\n }\n if (!query.state || !query.code) {\n return {\n kind: 'error',\n status: 400,\n body: invalidRequestBody('callback is missing the state or code query parameter'),\n };\n }\n\n // Single-use consume (§12.3 rule 1): a replayed callback finds nothing.\n const entry = await options.store.consume(query.state);\n if (!entry) {\n options.logger?.debug('axiam_sdk.oidc', 'no stored login state for the callback state');\n return {\n kind: 'error',\n status: 401,\n body: authenticationFailedBody('unknown, expired, or already-used login state'),\n };\n }\n\n let tokens: OidcTokenSet;\n try {\n tokens = await options.client.oidcExchange({\n code: query.code,\n codeVerifier: entry.codeVerifier,\n nonce: entry.nonce,\n redirectUri: entry.redirectUri,\n });\n } catch (err) {\n if (err instanceof NetworkError) {\n options.logger?.debug('axiam_sdk.oidc', 'token exchange transport failure');\n return { kind: 'error', status: 503, body: unavailableBody('the AXIAM token endpoint is unreachable') };\n }\n // AuthError (including OAuthProtocolError and every §12.4 reason code) and\n // anything unexpected: a login that cannot be proven is a failed login.\n const reason = err instanceof AuthError ? err.message : 'token exchange failed';\n options.logger?.debug('axiam_sdk.oidc', 'token exchange failed', { reason });\n return { kind: 'error', status: 401, body: authenticationFailedBody(reason) };\n }\n\n await options.onSuccess?.(tokens, entry);\n\n const destination = options.successRedirect ?? entry.returnTo;\n if (destination) {\n return { kind: 'redirect', url: destination };\n }\n return {\n kind: 'json',\n body: {\n authenticated: true,\n ...(typeof tokens.idClaims?.sub === 'string' ? { sub: tokens.idClaims.sub } : {}),\n expiresIn: tokens.expiresIn,\n },\n };\n}\n","// ID-token claim validation — CONTRACT.md §12.4, OIDC Core §3.1.3.7.\n//\n// PURE logic only: no network, no jose, no crypto beyond a constant-time\n// compare. The signature half of §12.4 (rules 1–2: `alg` allowlist, `kid`\n// lookup, Ed25519 verification, single JWKS re-fetch) lives in node/jwks.ts,\n// on the SAME verifier the §10 middleware already uses — §12 forbids forking\n// it. This module holds rules 3–6 (issuer, audience, time, nonce) plus the\n// reason-code vocabulary, so both halves can be unit-tested independently and\n// ported as one pair.\n//\n// Every failure raises `AuthError` carrying one of the seven stable reason\n// codes from §12.3 rule 3. Rule 7 (all-or-nothing discard) is enforced by the\n// caller — `OidcClient.oidcExchange` never returns a token set whose ID token\n// failed here, so `access_token`/`refresh_token` from the same response are\n// dropped with it.\n\nimport { timingSafeEqual } from 'node:crypto';\nimport { AuthError, type IdTokenFailureReason } from '../core/index.js';\n\n/**\n * The decoded, **already-validated** ID-token claim set carried by\n * {@link OidcTokenSet.idClaims} (CONTRACT.md §12.1).\n *\n * @remarks\n * Claim names are kept verbatim in their JWT/OIDC spelling (`iss`, `sub`,\n * `aud`, …) rather than camelCased: they are protocol identifiers a caller\n * cross-references against OIDC Core, exactly as {@link AxiamClaims} already\n * does for access-token claims. The open index signature is mandated by\n * §12.1 — the ID token's full claim set is not enumerated by `openapi.json`,\n * so unknown claims MUST be preserved and MUST NOT be rejected.\n */\nexport interface IdTokenClaims {\n /** Issuer — matched for exact string equality against the discovery document's `issuer` (§12.4 rule 3). */\n iss: string;\n /** Subject — the authenticated end user's stable identifier at AXIAM. */\n sub: string;\n /** Audience — contains the relying party's `client_id` (§12.4 rule 4). */\n aud: string | string[];\n /** Expiry time (epoch seconds). */\n exp: number;\n /** Issued-at time (epoch seconds). */\n iat: number;\n /** Not-before time (epoch seconds), when the server sends one. */\n nbf?: number;\n /** The `nonce` echoed back from the authorization request (§12.4 rule 6). */\n nonce?: string;\n /** Authorized party — required to equal `client_id` when `aud` holds multiple audiences (§12.4 rule 4). */\n azp?: string;\n /** Any further claim the server sends (e.g. `email`, `preferred_username`) — preserved, never rejected (§12.1). */\n [claim: string]: unknown;\n}\n\n/**\n * What an ID token is checked against by {@link IdTokenVerifier.verifyIdToken}\n * (CONTRACT.md §12.4 rules 3–6).\n */\nexport interface IdTokenExpectations {\n /**\n * The authoritative issuer — always the `issuer` value of the discovery\n * document the token endpoint was read from, never the client base URL\n * (§12.3 rule 6: behind a proxy the two legitimately differ).\n */\n issuer: string;\n /** The relying party's own `client_id`, matched against `aud`/`azp` (rule 4). */\n clientId: string;\n /**\n * The `nonce` returned by `oidcBegin` and passed back into `oidcExchange`.\n *\n * Mandatory for `oidcExchange`. Left `undefined` by `oidcRefresh` and\n * `loginClientCredentials`, which skip rule 6 entirely — OIDC Core §12.2\n * does not require a `nonce` in a refresh-issued ID token.\n */\n nonce?: string;\n /**\n * Permitted clock skew in seconds for `exp`/`iat`/`nbf` (rule 5). Defaults\n * to {@link MAX_CLOCK_SKEW_SEC} and is clamped to it — the contract forbids\n * configuring it *above* 60 s, so a larger value is silently reduced rather\n * than honoured.\n */\n clockSkewSec?: number;\n}\n\n/**\n * Maximum (and default) permitted clock skew in seconds for ID-token time\n * claims. CONTRACT.md §12.4 rule 5 caps this at 60 s and forbids any\n * configuration above the bound.\n */\nexport const MAX_CLOCK_SKEW_SEC = 60;\n\n/**\n * Build the `AuthError` for a §12.4 failure: a stable machine-readable\n * `reason` code plus a human-readable message that — per §12.3 rule 3 and §2's\n * construction rules — never embeds the token, a claim value that could carry\n * secret material, or the expected nonce.\n */\nexport function idTokenAuthError(reason: IdTokenFailureReason, message: string): AuthError {\n return new AuthError(`id_token validation failed (${reason}): ${message}`, reason);\n}\n\n/**\n * Resolve the effective clock skew: the caller's value clamped into\n * `[0, MAX_CLOCK_SKEW_SEC]`, or the maximum when unset.\n */\nexport function resolveClockSkewSec(clockSkewSec?: number): number {\n if (clockSkewSec === undefined) {\n return MAX_CLOCK_SKEW_SEC;\n }\n return Math.min(Math.max(clockSkewSec, 0), MAX_CLOCK_SKEW_SEC);\n}\n\n/**\n * Constant-time string equality, used for the `nonce` comparison §12.4 rule 6\n * requires. A length mismatch short-circuits to `false` (`timingSafeEqual`\n * throws on unequal-length buffers) — the same idiom\n * `middleware/cookieHeader.ts` and `amqp/hmac.ts` already use.\n */\nexport function constantTimeEquals(a: string, b: string): boolean {\n const left = Buffer.from(a, 'utf8');\n const right = Buffer.from(b, 'utf8');\n if (left.length !== right.length) {\n return false;\n }\n return timingSafeEqual(left, right);\n}\n\n/** Reject the JOSE header `alg` unless it is exactly `EdDSA` (§12.4 rule 1). */\nexport const ID_TOKEN_ALG = 'EdDSA';\n\n/**\n * §12.4 rule 1 — algorithm check, run against the JOSE **header** and BEFORE\n * any signature work, so the token can never select its own verification\n * algorithm. `none` is rejected by the same equality test as every other\n * non-`EdDSA` value; it gets no special case and no separate code path.\n */\nexport function assertIdTokenAlg(alg: unknown): void {\n if (alg !== ID_TOKEN_ALG) {\n throw idTokenAuthError(\n 'invalid_alg',\n `expected alg \"${ID_TOKEN_ALG}\", got ${typeof alg === 'string' ? `\"${alg}\"` : 'no alg header'}`,\n );\n }\n}\n\n/**\n * §12.4 rules 3–6 — issuer, audience, time and nonce checks over an\n * already-signature-verified claim set. Returns the claims unchanged on\n * success; throws the matching `AuthError` reason code on the first failure.\n *\n * @param claims the verified JWT payload.\n * @param expectations issuer/client_id/nonce to check against.\n * @param nowSec current time in epoch seconds — injectable so tests can pin it.\n */\nexport function checkIdTokenClaims(\n claims: IdTokenClaims,\n expectations: IdTokenExpectations,\n nowSec: number = Math.floor(Date.now() / 1000),\n): IdTokenClaims {\n const skew = resolveClockSkewSec(expectations.clockSkewSec);\n\n // Rule 3 — exact string comparison. No normalization, no trailing-slash\n // tolerance, no prefix matching.\n if (claims.iss !== expectations.issuer) {\n throw idTokenAuthError('invalid_issuer', 'iss does not equal the discovery document issuer');\n }\n\n // Rule 4 — aud must contain our client_id; with multiple audiences an azp\n // claim must be present and equal to it.\n const audiences = Array.isArray(claims.aud) ? claims.aud : [claims.aud];\n if (!audiences.includes(expectations.clientId)) {\n throw idTokenAuthError('invalid_audience', 'aud does not contain this client_id');\n }\n if (audiences.length > 1 && claims.azp !== expectations.clientId) {\n throw idTokenAuthError(\n 'invalid_audience',\n 'aud holds multiple audiences and azp is absent or does not equal this client_id',\n );\n }\n\n // Rule 5 — exp must be in the future, iat must not be in the future, nbf is\n // honored when present; all within `skew` seconds. `exp` is treated as\n // REQUIRED: a token with no expiry could never satisfy \"exp must be in the\n // future\", so its absence is an expiry failure rather than a free pass.\n if (typeof claims.exp !== 'number') {\n throw idTokenAuthError('token_expired', 'exp claim is missing or not a number');\n }\n if (claims.exp + skew <= nowSec) {\n throw idTokenAuthError('token_expired', 'exp is in the past');\n }\n if (typeof claims.iat !== 'number') {\n throw idTokenAuthError('token_expired', 'iat claim is missing or not a number');\n }\n if (claims.iat - skew > nowSec) {\n throw idTokenAuthError('token_expired', 'iat is in the future');\n }\n if (typeof claims.nbf === 'number' && claims.nbf - skew > nowSec) {\n throw idTokenAuthError('token_expired', 'nbf is in the future');\n }\n\n // Rule 6 — mandatory for oidcExchange, skipped when the caller supplied no\n // expected nonce (oidcRefresh / loginClientCredentials).\n if (expectations.nonce !== undefined) {\n if (typeof claims.nonce !== 'string' || !constantTimeEquals(claims.nonce, expectations.nonce)) {\n throw idTokenAuthError('nonce_mismatch', 'nonce claim is absent or does not match the request nonce');\n }\n }\n\n return claims;\n}\n","// Local JWKS verification (D-11, CONTRACT.md §7 defense-in-depth via\n// explicit algorithm allowlist) — for BOTH inbound access tokens (§10\n// middleware) and relying-party ID tokens (§12.4). One verifier, one cached\n// remote key set, two entry points: `verifyAccessToken` and `verifyIdToken`.\n// §12 explicitly forbids forking this module for the OIDC flow.\n//\n// Endpoint: `{baseUrl}/oauth2/jwks` — organization-wide, NOT tenant-scoped,\n// serving exactly one EdDSA (Ed25519) key in the common case\n// (RESEARCH.md Area 3, mirrors the Rust SDK's src/token/jwks.rs). `jose`'s\n// `createRemoteJWKSet` handles fetch + cache + refetch-on-unknown-kid\n// natively; we use its single-cooldown model rather than porting the Rust\n// SDK's two-timer (TTL + forced-refetch) design (RESEARCH.md Area 3 explicit\n// recommendation).\n//\n// Pitfall 1 (jose is ESM-only): `jose` 5+/6.x ships no CJS entry condition,\n// so a tsup CJS build's transpiled `require('jose')` would throw\n// `ERR_REQUIRE_ESM`. `createVerifier` obtains jose via a dynamic\n// `await import('jose')`, deferring resolution to first call rather than\n// module-load time — this keeps `require('axiam-sdk/grpc')` (or any other\n// CJS entry that reaches this module) from throwing at import time.\n\nimport { AuthError } from '../core/index.js';\nimport {\n assertIdTokenAlg,\n checkIdTokenClaims,\n ID_TOKEN_ALG,\n idTokenAuthError,\n resolveClockSkewSec,\n type IdTokenClaims,\n type IdTokenExpectations,\n} from './oidcIdToken.js';\n\n/** Verified claims carried by an AXIAM access token (the JWT payload {@link Verifier.verifyAccessToken} returns). */\nexport interface AxiamClaims {\n /** Subject — user ID (UUID). */\n sub: string;\n /** Tenant ID (UUID). */\n tenant_id: string;\n /** Organization ID (UUID), if present. */\n org_id?: string;\n /** Issuer — the AXIAM authorization server that minted the token. */\n iss: string;\n /** Issued-at time (epoch seconds), if present. */\n iat?: number;\n /** Expiry time (epoch seconds); the verifier rejects the token once it has passed. */\n exp: number;\n /** Unique token ID / session id — needed for logout(). */\n jti?: string;\n /** Token audience — \"axiam:user\" | \"axiam:m2m\". */\n aud?: string;\n /** OAuth2 scopes (space-separated). */\n scope?: string;\n /**\n * RFC 7800 / RFC 8705 §3.1 confirmation claim — present **only** on a\n * sender-constrained token (CONTRACT.md §10.1 rule 9, contract 1.15).\n *\n * Its presence changes what the token *is*. Without it, the token is a\n * bearer credential: whoever holds it may use it. With it, the token names\n * a key, and accepting it without proving the caller holds that key\n * converts it straight back into a bearer token.\n *\n * {@link Verifier.verifyAccessToken} checks this against the `proofs` you\n * pass it (contract 1.51 fix) — omit `proofs` (or pass `{}`) and a token\n * carrying `cnf` is refused, never silently accepted as a bearer token.\n * Supply the evidence your transport holds (a certificate thumbprint, a\n * verified DPoP key thumbprint, or both) to accept a bound token. See\n * {@link verifyCertificateBinding} / {@link verifyTokenBinding} for the\n * shared implementation `verifyAccessToken` reuses.\n */\n cnf?: CnfClaim;\n}\n\n/**\n * RFC 7800 confirmation claim.\n *\n * Deliberately an object with one optional field rather than a union: RFC 7800\n * permits confirmation methods this SDK does not implement, and such a token\n * must still *parse*. What it must not do is validate — see\n * {@link verifyCertificateBinding}.\n */\nexport interface CnfClaim {\n /**\n * RFC 8705 §3.1 — base64url (unpadded) SHA-256 of the DER client\n * certificate the token was issued to.\n */\n 'x5t#S256'?: string;\n /**\n * RFC 9449 §6.1 — base64url (unpadded) RFC 7638 thumbprint of the DPoP\n * public key the token was issued to (contract 1.16).\n */\n jkt?: string;\n}\n\n/**\n * The proofs a caller can present for a sender-constrained token\n * (contract 1.16, CONTRACT.md §10.1 rule 9).\n *\n * Both fields are optional because a caller may hold one, both or neither —\n * and \"neither\" is legitimate for an ordinary bearer token, which is why\n * {@link verifyTokenBinding} accepts `{}` and returns when the token names no\n * confirmation.\n *\n * @remarks\n * **Every thumbprint must come from the transport.** Take the certificate\n * thumbprint from the TLS peer certificate\n * (`TLSSocket.getPeerCertificate().raw` under Node), or from a *trusted*\n * terminating proxy over a channel your application controls. Never from a\n * caller-settable header: a forgeable input makes the mechanism decorative.\n */\nexport interface PresentedProofs {\n /** RFC 8705 §3.1 `x5t#S256` of the peer certificate on this connection. */\n certificateThumbprint?: string;\n /**\n * RFC 9449 §6.1 `jkt` of the key that signed a DPoP proof this SDK has\n * **already verified** for this request's `htm`/`htu`.\n *\n * Supplying a value here asserts the proof checked out. A thumbprint lifted\n * off an unverified proof would let a proof captured from any other\n * endpoint authorize this request.\n */\n dpopThumbprint?: string;\n}\n\n/**\n * CONTRACT.md §10.1 **rule 9** — enforce a token's sender constraint against\n * the certificate the caller presented on **this** connection\n * (RFC 8705 §3, contract 1.15).\n *\n * `presentedThumbprint` is the RFC 8705 §3.1 `x5t#S256` of the peer\n * certificate: base64url, **unpadded**, SHA-256 over the **DER** encoding.\n * {@link certificateThumbprintS256} computes it from DER bytes.\n *\n * | token's `cnf` | `presentedThumbprint` | result |\n * |---|---|---|\n * | absent | anything | returns — an ordinary bearer token |\n * | `x5t#S256` | equal | returns |\n * | `x5t#S256` | different, or `undefined` | **throws** |\n * | present, no `x5t#S256` | anything | **throws** |\n *\n * The first row is why adopting this rule breaks nothing: an unbound token is\n * still accepted whether or not a certificate is present. The last row is the\n * one that is easy to get wrong — a `cnf` naming a method this SDK cannot\n * check is an *unverifiable constraint*, never *no constraint*. Read the\n * other way, a sender-constrained token silently degrades to a bearer token\n * the day a newer AXIAM issues a confirmation this SDK predates.\n *\n * @remarks\n * **The thumbprint must come from the transport.** Take it from the TLS peer\n * certificate (`TLSSocket.getPeerCertificate().raw` under Node) or from a\n * value a *trusted* terminating proxy forwarded over a channel your\n * application controls. Never from a caller-settable request header: a\n * forgeable input makes the whole mechanism decorative.\n *\n * @throws {Error} on any of the three rejecting rows. The §10 middleware\n * wraps this into an `AuthError`.\n */\nexport function verifyCertificateBinding(\n claims: Pick<AxiamClaims, 'cnf'>,\n presentedThumbprint: string | undefined,\n): void {\n const cnf = claims.cnf;\n if (cnf === undefined || cnf === null) return;\n\n const expected = cnf['x5t#S256'];\n if (typeof expected !== 'string' || expected.length === 0) {\n // Includes the DPoP case: this entry point has no proof to check, so a\n // `jkt`-bound token is refused rather than silently downgraded.\n throw new Error(\n 'token carries a cnf confirmation naming a method this entry point cannot verify ' +\n '(CONTRACT.md §10.1 rule 9 — an unverifiable constraint is not an absent one; ' +\n 'use verifyTokenBinding for DPoP)',\n );\n }\n // A token naming BOTH methods is a conjunction (contract 1.16): this\n // function can establish one half and must not answer for the whole.\n // Refusing here is what stops \"check whichever we can\".\n if (typeof cnf.jkt === 'string' && cnf.jkt.length > 0) {\n throw new Error(\n 'token names both a certificate and a DPoP key; both must hold ' +\n '(CONTRACT.md §10.1 rule 9) — use verifyTokenBinding',\n );\n }\n if (presentedThumbprint === undefined) {\n throw new Error('token is certificate-bound but no client certificate was presented');\n }\n if (!constantTimeEqual(expected, presentedThumbprint)) {\n throw new Error('token is bound to a different client certificate than the one presented');\n }\n}\n\n/**\n * CONTRACT.md §10.1 **rule 9** — enforce a token's sender constraint against\n * **every** proof the caller presented (contract 1.16).\n *\n * This is the full rule, and the one to use unless your transport genuinely\n * cannot produce a DPoP thumbprint.\n *\n * | token's `cnf` | certificate | DPoP | result |\n * |---|---|---|---|\n * | absent | anything | anything | returns — an ordinary bearer token |\n * | `x5t#S256` | equal | ignored | returns |\n * | `x5t#S256` | different or absent | ignored | **throws** |\n * | `jkt` | ignored | equal | returns |\n * | `jkt` | ignored | different or absent | **throws** |\n * | both | equal | equal | returns — **conjunction** |\n * | both | either wrong or missing | — | **throws** |\n * | present, names neither | anything | anything | **throws** |\n *\n * Two rows carry the weight. **Both present is a conjunction**: an operator\n * who turned on two constraints asked for two, and satisfying the more\n * convenient one is not compliance. **Names neither is a refusal**: a\n * confirmation this SDK cannot interpret is an unverifiable constraint, and\n * reading it as \"unconstrained\" is the exact downgrade rule 9 exists to\n * prevent. That includes an *empty* `cnf` — which is also how proto3 delivers\n * an empty `CnfClaim` over gRPC (§10.3 rule 3).\n *\n * @remarks\n * This function compares thumbprints; it does **not** verify proofs. Supply\n * `dpopThumbprint` only after checking the proof's signature, `htm`, `htu`,\n * `iat` and `jti` for *this* request.\n *\n * @throws {Error} on any rejecting row. The §10 middleware wraps this into an\n * `AuthError`.\n */\nexport function verifyTokenBinding(\n claims: Pick<AxiamClaims, 'cnf'>,\n proofs: PresentedProofs = {},\n): void {\n const cnf = claims.cnf;\n // The fast path, and the common one. First on purpose: an unbound token is\n // accepted with no proofs at all, which is what keeps existing deployments\n // working when a guard adopts this rule.\n if (cnf === undefined || cnf === null) return;\n\n const expectedCert = typeof cnf['x5t#S256'] === 'string' && cnf['x5t#S256'].length > 0\n ? cnf['x5t#S256']\n : undefined;\n const expectedJkt = typeof cnf.jkt === 'string' && cnf.jkt.length > 0 ? cnf.jkt : undefined;\n\n if (expectedCert === undefined && expectedJkt === undefined) {\n throw new Error(\n 'token carries a cnf confirmation naming no method this SDK can verify ' +\n '(CONTRACT.md §10.1 rule 9 — an unverifiable constraint is not an absent one)',\n );\n }\n\n // Each arm that applies must pass. Written as two independent checks rather\n // than a switch on the pair precisely so \"both named\" needs no branch of its\n // own — it is simply the case where both run.\n if (expectedCert !== undefined) {\n if (proofs.certificateThumbprint === undefined) {\n throw new Error('token is certificate-bound but no client certificate was presented');\n }\n if (!constantTimeEqual(expectedCert, proofs.certificateThumbprint)) {\n throw new Error('token is bound to a different client certificate than the one presented');\n }\n }\n\n if (expectedJkt !== undefined) {\n if (proofs.dpopThumbprint === undefined) {\n throw new Error('token is DPoP-bound but no verified DPoP proof was presented');\n }\n if (!constantTimeEqual(expectedJkt, proofs.dpopThumbprint)) {\n throw new Error('token is bound to a different DPoP key than the one presented');\n }\n }\n}\n\n/**\n * Constant-time string comparison for {@link verifyCertificateBinding}.\n *\n * The thumbprint is usually public — it derives from a certificate sent in the\n * clear during the handshake — so this is defence in depth. It matters most\n * for a self-signed client, where the registered thumbprint is the whole\n * credential. Hand-rolled rather than `crypto.timingSafeEqual` so that this\n * function stays usable in the browser build, where `node:crypto` is absent.\n */\nfunction constantTimeEqual(a: string, b: string): boolean {\n // Length inequality short-circuits, leaking only the length. Both operands\n // are fixed-length base64url SHA-256 digests whenever either is well-formed.\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i += 1) {\n diff |= a.charCodeAt(i) ^ b.charCodeAt(i);\n }\n return diff === 0;\n}\n\n/**\n * Compute the RFC 8705 §3.1 `x5t#S256` thumbprint of a DER client\n * certificate: base64url-encoded SHA-256, **without** padding.\n *\n * Unpadded is not a style choice — RFC 7515 §2 defines base64url in JOSE as\n * omitting `=`, and a padded value will not compare equal to what AXIAM put in\n * the token.\n *\n * Node only (it needs `node:crypto`). A browser-side guard has no peer\n * certificate to fingerprint in the first place.\n */\nexport async function certificateThumbprintS256(der: Uint8Array): Promise<string> {\n const { createHash } = await import('node:crypto');\n return createHash('sha256').update(der).digest('base64url');\n}\n\n/** Path (relative to the client base URL) of the org-wide JWKS endpoint. */\nexport const JWKS_PATH = '/oauth2/jwks';\n\nconst COOLDOWN_DURATION_MS = 60_000;\nconst TIMEOUT_DURATION_MS = 5_000;\n\n/**\n * Clock-skew leeway applied to the `exp` and `nbf` checks (CONTRACT.md §10.1\n * rule 7).\n *\n * A **named, bounded, non-configurable** constant, fixed at the contract's\n * RECOMMENDED 60 seconds. Rule 7 forbids both an inline literal and an\n * operator-settable value that could be widened without bound, so there is\n * deliberately no option to override it — widening the window is a source\n * change, reviewable as such.\n */\nexport const CLOCK_SKEW_LEEWAY_SEC = 60;\n\n/**\n * The verification policy {@link Verifier.verifyAccessToken} enforces, per\n * CONTRACT.md §10.1.\n *\n * `expectedTenantId` is **required** (rule 4): the `/oauth2/jwks` trust\n * anchor is organization-wide, so a valid signature proves only \"some tenant\n * in this organization\". `expectedIssuer` and `expectedAudience` are\n * **conditional** (rules 5 and 6) — omitted means the check is not performed,\n * and the SDK never assumes a default issuer.\n */\nexport interface AccessTokenExpectations {\n /**\n * §10.1 rule 4 — the tenant this resource server is configured for. The\n * token's `tenant_id` claim MUST equal it; an absent claim, an empty\n * expectation, or a mismatch all reject (fail closed).\n */\n expectedTenantId: string;\n /** §10.1 rule 5 — expected `iss`. Omit for no issuer check. */\n expectedIssuer?: string;\n /**\n * §10.1 rule 6 — expected `aud`. Omit for no audience check. A resource\n * server guarding user-facing routes SHOULD pass `\"axiam:user\"`.\n */\n expectedAudience?: string;\n}\n\n/** Verifies an AXIAM access token's EdDSA signature against the org-wide remote JWKS. */\nexport interface Verifier {\n /**\n * Verify `token` against the **complete** CONTRACT.md §10.1 minimum\n * local-verification set and return its claims.\n *\n * | § | rule | how it is enforced |\n * |---|---|---|\n * | 1 | signature | `algorithms: ['EdDSA']` is checked by `jose` against the JWS header *before* the remote key set function is invoked, so `alg: none` and an HS-signed token bearing an EdDSA `kid` are rejected without a key lookup. |\n * | 2 | `exp` | `requiredClaims: ['exp']` — `jose` only checks `exp` *if present* by default, so an absent `exp` (a permanent credential) would otherwise sail through. A non-numeric `exp` is rejected by `jose`'s own type check. |\n * | 3 | `nbf` | honoured by `jose` when present, bounded by {@link CLOCK_SKEW_LEEWAY_SEC}. |\n * | 4 | `tenant_id` | asserted against {@link AccessTokenExpectations.expectedTenantId}; absent claim, absent expectation, or mismatch all reject. |\n * | 5 | `iss` | checked only when `expectedIssuer` is supplied. |\n * | 6 | `aud` | checked only when `expectedAudience` is supplied. |\n * | 7 | clock skew | {@link CLOCK_SKEW_LEEWAY_SEC}, passed as `clockTolerance`. |\n * | 9 | `cnf` | (contract 1.51 fix) `proofs` defaults to `{}` — no evidence — so a token carrying `cnf` is refused unless the caller supplies matching evidence. Enforced by handing the verified claims and `proofs` to {@link verifyTokenBinding}, the same function {@link verifyCertificateBinding}, `authenticateRequest` and a hand-rolled guard share, so local verification never disagrees with itself about whether a token is a bearer token. An unbound token is unaffected whether or not `proofs` is supplied. |\n *\n * **`proofs` and which entry point to call.** This method is the SDK's\n * documented §10 guard entry point (see {@link verifySignatureOnlyUnchecked}),\n * and until the contract 1.51 fix it applied rules 1–8 only: it had no\n * transport to ask for a certificate, so it silently treated every\n * `cnf`-bound token as an ordinary bearer credential — precisely the\n * SEC-071/SEC-080 downgrade §10.1 rule 9 exists to close, and exactly what\n * every device token `authenticateDevice()` (§6.1) mints. `proofs` is now\n * how a caller supplies that evidence: a certificate thumbprint the\n * transport verified for this connection, a DPoP key thumbprint from a\n * proof the caller has **itself** verified per §21.7, or both. Omitting it\n * (or passing `{}`) is exactly {@link verifySignatureOnlyUnchecked}'s\n * opposite number for rule 9 — refuse rather than guess — and is the\n * correct default for a caller with no transport evidence to offer; an\n * unbound token is accepted either way, which is what keeps every existing\n * bearer-only deployment working unchanged.\n *\n * Rejects with the underlying error on any failed rule; the §10 middleware\n * wraps that into an `AuthError`.\n */\n verifyAccessToken(\n token: string,\n expectations: AccessTokenExpectations,\n proofs?: PresentedProofs,\n ): 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 * `aud` or `cnf` (rule 9) check whatsoever: an expired token, a\n * not-yet-valid token, a token minted for a *different tenant* in the same\n * organization, and a certificate- or DPoP-bound token presented with no\n * evidence at all, all pass. It exists only for integrators deliberately\n * implementing their own policy on top of the signature — the `Unchecked`\n * suffix is there to make that omission obvious at the call site. Anything\n * guarding a route MUST use {@link Verifier.verifyAccessToken}, passing\n * `proofs` when it may see a certificate- or DPoP-bound token (or, better,\n * the §10 middleware built on it, which does this automatically).\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 proofs: PresentedProofs = {},\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 const claims = payload as unknown as AxiamClaims;\n\n // §10.1 rule 9 (contract 1.51 fix). This entry point is the SDK's\n // documented guard — its own `verifySignatureOnlyUnchecked` doc says so\n // — so it must not accept a `cnf`-bound token as an ordinary bearer\n // credential just because it was handed no evidence. `proofs` defaults\n // to `{}` (no evidence), which is exactly the \"reject\" row of rule 9's\n // table for a bound token; an unbound token is unaffected. Reuses\n // `verifyTokenBinding` rather than duplicating it, so this entry point\n // and `authenticateRequest`/a hand-rolled guard can never disagree\n // about whether a token is a bearer token.\n verifyTokenBinding(claims, proofs);\n\n return claims;\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","// CONTRACT.md §10.1 rule 9 (contract 1.15/1.16/1.51) — deriving the ONE piece\n// of transport evidence `authenticateRequest` can gather on its own: the\n// client certificate the TLS layer verified for THIS connection, when Node\n// itself terminated TLS.\n//\n// This is deliberately the only automatic evidence source. §10.1 detail 2 is\n// explicit that the comparison input \"MUST come from the transport\" and\n// \"MUST NOT\" come from a caller-settable header — a raw `net.Socket`'s own\n// `getPeerCertificate()` is exactly the transport, nothing forwarded. DPoP\n// evidence is NOT derived here: proof verification (§21.7) is a materially\n// larger obligation the middleware does not undertake automatically, and\n// `verifyTokenBinding`'s own contract is to refuse a jkt-bound token when no\n// verified proof is supplied — which is correct, not a gap this file needs\n// to fill.\n\nimport type { PresentedProofs } from '../node/jwks.js';\nimport { certificateThumbprintS256 } from '../node/jwks.js';\n\n/**\n * The minimal shape a Node `net.Socket`/`tls.TLSSocket` needs for this\n * module to read a peer certificate off it. `encrypted` is TLSSocket's own\n * \"always true\" marker (Node's documented way to tell a TLS socket from a\n * plain one); `getPeerCertificate` is TLSSocket's method.\n */\nexport interface PeerCertificateSocket {\n /** `tls.TLSSocket`'s own \"this is a TLS socket\" marker — always `true` there, absent on a plain `net.Socket`. */\n encrypted?: boolean;\n /** `tls.TLSSocket.getPeerCertificate`. Returns the DER-encoded peer certificate, when `detailed` is `true` and one was presented. */\n getPeerCertificate?: (detailed?: boolean) => PeerCertificateLike | undefined;\n}\n\n/** The one field this module reads off `tls.TLSSocket.getPeerCertificate()`'s return value. */\nexport interface PeerCertificateLike {\n /** The DER-encoded certificate bytes, when a certificate was presented. */\n raw?: Uint8Array;\n}\n\n/**\n * Derive {@link PresentedProofs} from a request's raw socket.\n *\n * Returns `{}` (no evidence) whenever there is nothing to read: `socket` is\n * absent or not TLS-shaped, `encrypted` is not `true` (a plain `net.Socket`\n * — no TLS at all, or TLS terminated by a proxy that forwards nothing to\n * this process), or `getPeerCertificate()` returned no certificate (the\n * common case: nothing requested one, or the handshake carried none). `{}`\n * is the same shape `verifyTokenBinding`'s default parameter already means\n * \"no proofs\" — an unbound token is accepted either way, and a bound one is\n * refused, exactly CONTRACT.md §10.1 rule 9 detail 3's \"the SDK cannot see\n * any client certificate at all\" case: fail closed, never silently accept.\n *\n * Does **not** check whether the certificate chains to any particular CA —\n * possession is what a completed TLS handshake already proves (the peer\n * demonstrated the matching private key to get this far), and comparing the\n * resulting thumbprint against the token's `cnf` is `verifyTokenBinding`'s\n * job, not this function's.\n */\nexport async function certificateProofFromSocket(\n rawSocket: unknown,\n): Promise<PresentedProofs> {\n // `unknown` rather than `PeerCertificateSocket | null | undefined`: the\n // real callers (Express's `net.Socket`, Fastify's raw Node request socket)\n // are typed by @types/node with no `encrypted`/`getPeerCertificate`\n // members at all outside a `tls.TLSSocket` narrowing this module has no\n // reason to import — an all-optional interface with zero structural\n // overlap is exactly what TS's \"weak type\" check (TS2559) rejects at the\n // call site. The shape check below is the real guard either way.\n if (!rawSocket || typeof rawSocket !== 'object') {\n return {};\n }\n const socket = rawSocket as PeerCertificateSocket;\n if (socket.encrypted !== true || typeof socket.getPeerCertificate !== 'function') {\n return {};\n }\n let cert: PeerCertificateLike | undefined;\n try {\n cert = socket.getPeerCertificate(true);\n } catch {\n return {};\n }\n if (!cert?.raw || cert.raw.length === 0) {\n return {};\n }\n return { certificateThumbprint: await certificateThumbprintS256(cert.raw) };\n}\n","// Shared verify core (D-27, CONTRACT.md §10) — the ONE verification path\n// both Express and Fastify middleware call. Reuses the 17-03 local-JWKS\n// verifier (jose against the cached remote JWKS, EdDSA-only) — no\n// per-request round-trip to the AXIAM server on a cache hit, and no\n// additional TTL bookkeeping beyond jose's own `exp` check (§10 \"MUST NOT\n// cache session verification results longer than the token's remaining\n// TTL\").\n\nimport { AuthError } from '../core/index.js';\nimport { assertTenantClaim, type PresentedProofs, type Verifier } from '../node/jwks.js';\nimport type { RevocationFeed } from '../node/revocationFeed.js';\n\n/**\n * Minimal session shape the middleware needs: a JWKS verifier (D-11) and the\n * tenant this resource server is configured for (CR-03). JWKS is org-wide,\n * not tenant-scoped (node/jwks.ts) — `tenantHeaderValue` is what lets\n * `authenticateRequest` reject a validly-signed token minted for a\n * DIFFERENT tenant in the same org (CONTRACT.md §10.1 rule 4).\n */\nexport interface VerifiableSession {\n /** Local JWKS verifier (D-11) — validates the token's EdDSA signature against the org-wide cached JWKS, offline on a cache hit. */\n jwksVerifier: Verifier;\n /**\n * The tenant this resource server is configured for (CR-03, §10.1 rule 4);\n * a validly-signed token minted for a different tenant in the same org is\n * rejected.\n *\n * @remarks\n * The claim it is compared against is the token's `tenant_id`, which is\n * always a UUID — so a resource server guarding routes MUST be configured\n * with `tenantId` (the UUID form), not `tenantSlug`. A slug-configured\n * session can never match and therefore rejects every request; that is\n * fail-closed by design, not a silent pass.\n */\n tenantHeaderValue: string;\n /**\n * CONTRACT.md §10.1 rule 5 — expected token issuer. Optional and unset by\n * default: the rule is conditional on configuration, and the SDK never\n * hardcodes an issuer. When set, a token whose `iss` differs is rejected.\n * Populated from `AxiamClientOptions.expectedIssuer`.\n */\n expectedIssuer?: string;\n /**\n * CONTRACT.md §10.1 rule 6 — expected token audience. Optional and unset by\n * default. A resource server guarding user-facing routes SHOULD set\n * `\"axiam:user\"`. Populated from `AxiamClientOptions.expectedAudience`.\n */\n expectedAudience?: string;\n /**\n * CONTRACT.md §28.5 (contract 1.48) — the URL of this resource server's RFC\n * 9728 protected-resource metadata document.\n *\n * Unset by default, and **setting it is what turns §28 on**. With it unset\n * every guard built from this session behaves byte-for-byte as it did before\n * §28 existed: no `WWW-Authenticate` header on any response, no status\n * changed, no body changed.\n *\n * With it set, the guard's 401s carry §28.4's challenge, a\n * `require_access`/`requireAccessHook` denial that named a scope and came\n * back `no_grant` carries `insufficient_scope`, and the path this URL names\n * is served without authentication so the document can start the handshake\n * it exists to start.\n *\n * **{@link VerifiableSession.expectedAudience} becomes mandatory.** Every\n * guard factory refuses the configuration at construction — before the first\n * request — when this is set and that is not, and the refusal names both. A\n * resource server that publishes \"tokens for me carry this `aud`\" and then\n * does not check `aud` is opened by a token minted for a different resource\n * server, which is the confusion RFC 8707 exists to prevent.\n *\n * Feed it from `protectedResourceMetadata(...).metadataUrl` rather than by\n * retyping the string — retyping is how the guard and the document come to\n * disagree.\n */\n resourceMetadataUrl?: string;\n /**\n * CONTRACT.md §10.4 (contract 1.44) — the optional session-revocation feed.\n *\n * Unset by default, and with it unset this guard behaves exactly as it did\n * before 1.44: a revoked session's access token verifies locally until it\n * expires, which is the §10.2 posture this narrows rather than replaces.\n *\n * It is never a control. A feed that cannot be read denies nothing, every\n * §10.1 rule runs first and still decides, and a token with no `sid` is\n * never matched against it.\n */\n revocationFeed?: RevocationFeed;\n}\n\n/** Authenticated identity injected as req.axiamUser / request.axiamUser (§10). */\nexport interface AxiamIdentity {\n /** The authenticated end user's id (the token's `sub` claim). */\n userId: string;\n /** The tenant the verified token was minted for (the token's `tenant_id` claim). */\n tenantId: string;\n /** Roles derived from the token's space-separated `scope` claim (§10). */\n roles: string[];\n}\n\n/**\n * Verify `token` locally against `session`'s cached JWKS and map the\n * verified claims to the identity shape injected by both middleware\n * modules. Roles are derived from the `scope` claim (space-separated) —\n * AXIAM's access token carries no dedicated `roles` claim server-side\n * (mirrors the Rust SDK's src/middleware/actix.rs).\n *\n * This is the SDK's **documented §10 guard entry point** for TypeScript, and\n * it applies the complete CONTRACT.md §10.1 minimum local-verification set:\n * rules 1/2/3/5/6/7 inside `verifyAccessToken` (EdDSA `alg` pinned before key\n * lookup, REQUIRED numeric `exp`, `nbf` when present, conditional `iss`/`aud`,\n * a named bounded clock skew), rule 4 — the `tenant_id` assertion — both\n * there and again here, so a caller-supplied `Verifier` implementation that\n * ignores its expectations still cannot get a cross-tenant token past the\n * middleware, and rule 9 — see `proofs` below.\n *\n * **`proofs` and rule 9.** A token carrying `cnf` is not a bearer token\n * (§10.1 rule 9): it may be used only by a presenter that proves possession\n * of the key it names. `proofs` is this function's transport evidence — a\n * certificate thumbprint the caller's TLS layer verified for this\n * connection, a DPoP key thumbprint from a proof the caller has **itself**\n * verified, or both — and it is passed straight into `verifyAccessToken`,\n * which is where rule 9 is now enforced (contract 1.51 fix; see\n * `verifyAccessToken`'s own doc in `node/jwks.ts`). There is deliberately no\n * *second* rule-9 check here: `verifyAccessToken` already reuses\n * `verifyTokenBinding` internally, and re-running that same check against\n * the same `proofs` a moment later would only be able to agree with itself —\n * the risk worth guarding against is a check run against *different* inputs\n * (for example the transport's real evidence at one call site and `{}` at\n * another), not the same evidence read twice.\n *\n * `proofs` defaults to `{}` — **no evidence** — so a `cnf`-bound token is\n * refused by default, which is the fail-closed, spec-correct behaviour for a\n * caller that has not supplied any: rule 9's table has no row where absent\n * evidence accepts a bound token. `axiamMiddleware`/`axiamPlugin` pass\n * `certificateProofFromSocket(req.socket)` automatically, so a resource\n * server whose Node process terminates TLS itself accepts a\n * certificate-bound token with no extra wiring; a deployment behind a proxy\n * that forwards nothing still refuses one, exactly as §10.1 rule 9 detail 3\n * requires. An unbound token is unaffected either way — this is the\n * positive regression rule 9 exists to protect, and its own test asserts it\n * explicitly.\n *\n * Throws `AuthError` on any verification failure (missing/invalid/expired\n * token, a token with no `exp`, a not-yet-valid `nbf`, a malformed/mismatched\n * sub/tenant_id claim, or an unsatisfiable `cnf`).\n */\nexport async function authenticateRequest(\n session: VerifiableSession,\n token: string,\n proofs: PresentedProofs = {},\n): Promise<AxiamIdentity> {\n let claims;\n try {\n // proofs flows straight into verifyAccessToken, which now applies rule 9\n // itself (contract 1.51 fix) — see the doc comment above for why this\n // stays a single check rather than a second one against the same\n // evidence.\n claims = await session.jwksVerifier.verifyAccessToken(\n token,\n {\n expectedTenantId: session.tenantHeaderValue,\n expectedIssuer: session.expectedIssuer,\n expectedAudience: session.expectedAudience,\n },\n proofs,\n );\n } catch (err) {\n throw new AuthError(err instanceof Error ? err.message : 'invalid or expired token');\n }\n\n if (!claims.sub) {\n throw new AuthError('invalid sub claim');\n }\n // CR-03 / §10.1 rule 4: JWKS is org-wide (node/jwks.ts), so signature\n // validity alone does NOT imply the token was minted for THIS resource\n // server's tenant. Re-asserted on the guard side (the verifier already did\n // it) because `VerifiableSession.jwksVerifier` is an interface a consumer\n // may implement themselves — the middleware must not delegate a\n // fail-closed control to a type it does not own.\n assertTenantClaim(claims.tenant_id, session.tenantHeaderValue);\n\n // §10.4 rules 4 and 6. Runs LAST: every §10.1 rule has already decided, and\n // the feed can only turn an accept into a reject. A token with no `sid`\n // names no session and is never matched — there is no fallback to `jti`,\n // which would match nothing while looking like it worked.\n const sid = (claims as { sid?: unknown }).sid;\n if (session.revocationFeed && typeof sid === 'string' && sid.length > 0) {\n if (await session.revocationFeed.isRevoked(sid)) {\n throw new AuthError(\n 'the session behind this access token has been revoked (CONTRACT.md §10.4)',\n );\n }\n }\n\n const roles = (claims.scope ?? '').split(' ').filter(Boolean);\n\n return {\n userId: claims.sub,\n tenantId: claims.tenant_id,\n roles,\n };\n}\n","// Express middleware (D-27, CONTRACT.md §10). Express 5 handlers may be\n// async — an async middleware that rejects is automatically forwarded to\n// Express's error handling, but this middleware always resolves (never\n// rejects) since every failure path is caught and turned into a 401/403\n// JSON response itself.\n\nimport type { NextFunction, Request, RequestHandler, Response } from 'express';\nimport { AuthError, AuthzError } from '../core/index.js';\nimport {\n assertAuthzClient,\n authzDeniedBody as authzDeniedBodyShared,\n authzUnavailableBody,\n evaluateAccess,\n hasAnyRole,\n invalidRequestBody,\n missingAuthBody,\n resolveResourceId,\n ResourceResolutionError,\n type AuthzVerifiableSession,\n type RequireAccessOptions,\n type ResourceSpec,\n} from './authzCore.js';\nimport { CSRF_HEADER_NAME, extractCredential, isCsrfValid, isSafeMethod } from './cookieHeader.js';\nimport {\n challengeFor401,\n challengeFor403,\n isMetadataDocumentRequest,\n mcpGuardChallenges,\n} from './mcpCore.js';\nimport {\n beginOidcLogin,\n completeOidcLogin,\n type OidcLoginOptions,\n type OidcLoginOutcome,\n} from './oidcLoginCore.js';\nimport { certificateProofFromSocket } from './peerCertificate.js';\nimport { authenticateRequest, type AxiamIdentity, type VerifiableSession } from './verifyCore.js';\n\n/** An Express `Request` augmented with the AXIAM identity that `axiamMiddleware` injects after §10 verification. */\nexport interface AxiamRequest extends Request {\n /** The authenticated identity, present once `axiamMiddleware` (or `requireAuth`) has run; absent on an unauthenticated request. */\n axiamUser?: AxiamIdentity;\n}\n\ninterface ErrorBody {\n error: string;\n message: string;\n}\n\nfunction missingCredentialsBody(): ErrorBody {\n return { error: 'authentication_failed', message: 'missing authentication credentials' };\n}\n\nfunction invalidTokenBody(message: string): ErrorBody {\n return { error: 'authentication_failed', message };\n}\n\nfunction authzDeniedBody(message: string): ErrorBody {\n return { error: 'authorization_denied', message };\n}\n\nfunction csrfDeniedBody(): ErrorBody {\n return { error: 'authorization_denied', message: 'csrf validation failed' };\n}\n\n/**\n * `axiamMiddleware(session)` — extracts the session (cookie-first, then\n * `Authorization: Bearer` fallback), verifies it locally against the\n * cached JWKS (D-11, no per-request server round-trip on a cache hit),\n * and injects `req.axiamUser` on success. Returns 401 (AuthError) or 403\n * (AuthzError) with a standardized JSON error body on failure.\n *\n * **CSRF (cookie double-submit, CONTRACT.md §3):** when the credential was\n * sourced from the `axiam_access` COOKIE (not the `Authorization` header)\n * and the request method is state-changing (anything other than\n * GET/HEAD/OPTIONS), this middleware additionally requires the\n * `X-CSRF-Token` request header to be present and equal (constant time) to\n * the `axiam_csrf` cookie value, rejecting with 403 on mismatch/absence.\n * Bearer-header requests are CSRF-immune by construction — a cross-site\n * attacker cannot set arbitrary request headers — but a cookie\n * automatically attached by the browser is not, and in any same-site\n * deployment where `axiam_access` reaches this app, the non-`httpOnly`\n * `axiam_csrf` cookie does too. This mirrors, locally, the same\n * double-submit check the AXIAM server performs on its own endpoints (§3).\n */\nexport function axiamMiddleware(session: VerifiableSession): RequestHandler {\n // §28.5: validated and precomputed at construction, `undefined` when\n // `resourceMetadataUrl` is unset — which is what keeps a guard without §28\n // byte-for-byte identical to one from before §28 existed.\n const challenges = mcpGuardChallenges(session, 'axiamMiddleware');\n\n return async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n // §28.3 rule 2: the metadata document MUST answer without a credential,\n // and this guard is normally mounted globally — so the exemption is here,\n // explicit, and derived from the one path `resourceMetadataUrl` names.\n if (isMetadataDocumentRequest(challenges, req.method, req.originalUrl ?? req.url)) {\n next();\n return;\n }\n\n const credential = extractCredential(req.headers.cookie, req.headers.authorization);\n if (!credential) {\n // §28.4: no credential is not a bad credential, so the challenge names\n // no error code (RFC 6750 §3).\n if (challenges) res.setHeader('WWW-Authenticate', challenges.noCredential);\n res.status(401).json(missingCredentialsBody());\n return;\n }\n\n if (credential.source === 'cookie' && !isSafeMethod(req.method)) {\n const csrfHeader = req.headers[CSRF_HEADER_NAME];\n const csrfValue = Array.isArray(csrfHeader) ? csrfHeader[0] : csrfHeader;\n if (!isCsrfValid(req.headers.cookie, csrfValue)) {\n res.status(403).json(csrfDeniedBody());\n return;\n }\n }\n\n try {\n // §10.1 rule 9: the one piece of transport evidence this middleware can\n // gather on its own — the peer certificate the TLS layer verified for\n // THIS connection, when Node itself terminated TLS. `req.socket` is\n // `express`'s (Node's) raw socket; `{}` when it is not TLS-shaped or\n // carries no certificate, which is exactly \"no evidence\" and refuses a\n // cnf-bound token rather than accepting one (see verifyCore.ts).\n const proofs = await certificateProofFromSocket(req.socket);\n const identity = await authenticateRequest(session, credential.token, proofs);\n (req as AxiamRequest).axiamUser = identity;\n next();\n } catch (err) {\n if (err instanceof AuthzError) {\n // §28.5 rule 5: this 403 is not a `no_grant` scope denial, so it gains\n // no header.\n res.status(403).json(authzDeniedBody(err.message));\n return;\n }\n // §28.4: a credential was presented and rejected. Expired, not yet\n // valid, wrong tenant, wrong audience, bad signature, an unsatisfiable\n // `cnf`, a revoked `sid` — all of them are `invalid_token`,\n // indistinguishably. Every distinction a 401 draws for an\n // unauthenticated stranger is an oracle.\n if (challenges) res.setHeader('WWW-Authenticate', challenges.invalidToken);\n if (err instanceof AuthError) {\n res.status(401).json(invalidTokenBody(err.message));\n return;\n }\n res.status(401).json(invalidTokenBody('invalid or expired token'));\n }\n };\n}\n\n/**\n * `requireAuth(session)` (CONTRACT.md §11.1) — the canonical §11 name for\n * the same §10 guard `axiamMiddleware` already provides, for mounting\n * per-route (`router.get('/x', requireAuth(session), handler)`) rather than\n * globally via `app.use(axiamMiddleware(session))`. Pure sugar: it performs\n * no verification of its own beyond what `axiamMiddleware` already does.\n */\nexport function requireAuth(session: VerifiableSession): RequestHandler {\n return axiamMiddleware(session);\n}\n\n/**\n * `requireAccess(session, action, resource, opts?)` (CONTRACT.md §11) — a\n * per-route authorization guard layered strictly on top of the §10 guard.\n *\n * Throws synchronously (at route-setup time, not per-request) if\n * `session.authzClient` is not configured. Requires `req.axiamUser` to\n * already be set (by `axiamMiddleware`/`requireAuth` mounted earlier in the\n * chain) — this helper never extracts or verifies a token itself (§11.2.1),\n * so responds 401 immediately when it is absent.\n *\n * `resource` is resolved per §11.2.3's precedence: a literal string, a\n * {@link fromParam} route-parameter reference, or a `(req) => string`\n * resolver. `subjectId` on the wire is always the *authenticated request's*\n * user id (§11.2.2), never the SDK client's own service-account identity.\n * Error mapping (§11.2.5): 401 unauthenticated, 403 denied, 400 unresolvable\n * resource, 503 `authz_unavailable` on any transport/unexpected failure\n * (fail closed — never a silent allow).\n */\nexport function requireAccess(\n session: AuthzVerifiableSession,\n action: string,\n resource: ResourceSpec<Request>,\n opts?: RequireAccessOptions,\n): RequestHandler {\n const checker = assertAuthzClient(session);\n // §28.5 rule 5's challenge is built here, from this route's own `scope`\n // argument, so a scope outside RFC 6750's syntax fails at route setup rather\n // than on the first denial.\n const challenges = mcpGuardChallenges(session, 'requireAccess', opts?.scope);\n\n return async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n const axiamUser = (req as AxiamRequest).axiamUser;\n if (!axiamUser) {\n if (challenges) {\n res.setHeader(\n 'WWW-Authenticate',\n challengeFor401(challenges, req.headers.cookie, req.headers.authorization),\n );\n }\n res.status(401).json(missingAuthBody());\n return;\n }\n\n let resourceId: string;\n try {\n resourceId = resolveResourceId(req, resource, (r) => r.params as Record<string, string | undefined>);\n } catch (err) {\n const message = err instanceof ResourceResolutionError ? err.message : 'invalid resource';\n res.status(400).json(invalidRequestBody(message));\n return;\n }\n\n const outcome = await evaluateAccess(\n checker,\n action,\n resourceId,\n axiamUser.userId,\n opts?.scope,\n opts?.umaChallenge,\n );\n if (outcome.kind === 'denied') {\n opts?.logger?.debug('axiam_sdk.authz', 'access denied', { action, resourceId });\n // §20.3's UMA challenge wins where both apply: it is per-route opt-in and\n // carries a live ticket for the exact authority just refused, where\n // §28.5 rule 5's is the generic \"ask for this scope\" hint. Only one\n // `WWW-Authenticate` value is emitted either way.\n const challenge = outcome.challenge ?? challengeFor403(challenges, outcome.reasonCode);\n if (challenge) {\n // §20.3 / §28.5 rule 5: tell the caller where to obtain authority.\n // Additive — the body is the unchanged §11.2.5 shape, so a client that\n // speaks neither sees exactly the 403 it saw before. In particular\n // `insufficient_scope` appears only in the header: the body is still\n // `authorization_denied`.\n res.setHeader('WWW-Authenticate', challenge);\n }\n res.status(403).json(authzDeniedBodyShared(outcome.message));\n return;\n }\n if (outcome.kind === 'unavailable') {\n opts?.logger?.debug('axiam_sdk.authz', 'authz check unavailable', { action, resourceId });\n res.status(503).json(authzUnavailableBody(outcome.message));\n return;\n }\n next();\n };\n}\n\n/**\n * `requireRole(session, ...roles)` (CONTRACT.md §11.1, MAY) — a local\n * (no server round-trip) check that the authenticated identity's `roles`\n * (from `req.axiamUser`, itself derived from the verified token's `scope`\n * claim) contain at least one of `roles`. Cheaper but coarser than\n * `requireAccess`; NOT a substitute for a resource-level check.\n *\n * `session` is taken first for signature parity with\n * `requireAuth`/`requireAccess` (every §11 helper does). The role check itself\n * reads nothing from it; §28.5 is the only thing that does, so that this\n * guard's own 401 carries the same challenge every other 401 does.\n */\nexport function requireRole(session: VerifiableSession, ...roles: string[]): RequestHandler {\n // The one thing this guard does read off the session: §28.5 rule 4 puts the\n // challenge on every 401 the guard emits, and this guard emits one.\n const challenges = mcpGuardChallenges(session, 'requireRole');\n\n return (req: Request, res: Response, next: NextFunction): void => {\n const axiamUser = (req as AxiamRequest).axiamUser;\n if (!axiamUser) {\n if (challenges) {\n res.setHeader(\n 'WWW-Authenticate',\n challengeFor401(challenges, req.headers.cookie, req.headers.authorization),\n );\n }\n res.status(401).json(missingAuthBody());\n return;\n }\n if (!hasAnyRole(axiamUser.roles, roles)) {\n // §28.5 rule 5: a role failure is not a scope failure — no header.\n res.status(403).json(authzDeniedBodyShared('missing required role'));\n return;\n }\n next();\n };\n}\n\n// ---------------------------------------------------------------------------\n// \"Login with AXIAM\" route handlers (CONTRACT.md §12)\n// ---------------------------------------------------------------------------\n\n/** Apply an {@link OidcLoginOutcome} to an Express response. */\nfunction sendOidcOutcome(res: Response, outcome: OidcLoginOutcome): void {\n if (outcome.kind === 'redirect') {\n res.redirect(outcome.url);\n return;\n }\n if (outcome.kind === 'json') {\n res.status(200).json(outcome.body);\n return;\n }\n res.status(outcome.status).json(outcome.body);\n}\n\n/**\n * `oidcLoginHandlers(options)` (CONTRACT.md §12) — the two Express route\n * handlers an application needs for \"Login with AXIAM\": a `login` handler that\n * redirects the browser to AXIAM's authorization endpoint, and a `callback`\n * handler that consumes the returned `state`, exchanges the code, and\n * validates the ID token.\n *\n * @remarks\n * Both handlers are thin adapters over {@link beginOidcLogin} /\n * {@link completeOidcLogin}, which the Fastify variant\n * (`oidcLoginPlugin`) also uses — so the two frameworks cannot drift on flow\n * semantics or error mapping.\n *\n * The `login` handler reads an optional `?returnTo=` query parameter and\n * stores it with the login state, so the callback can send the user back where\n * they started. **Validate or allowlist that value in your own application if\n * you accept it from user input** — an unchecked `returnTo` is an open-redirect\n * vector, and the SDK cannot know which destinations your app considers safe.\n *\n * Establishing your application's own session is the `onSuccess` hook's job:\n * the SDK validates the login and hands you the token set, but what a session\n * means (a signed cookie, a database row, a JWT of your own) is your decision.\n *\n * @example\n * ```ts\n * const store = new MemoryOidcStateStore();\n * const oidc = createOidcClient(session, { clientId, clientSecret });\n * const { login, callback } = oidcLoginHandlers({\n * client: oidc,\n * store,\n * redirectUri: 'https://app.example.com/auth/callback',\n * scope: 'openid profile email',\n * onSuccess: (tokens) => { myAppSession.establish(tokens.idClaims!.sub); },\n * });\n *\n * app.get('/auth/login', login);\n * app.get('/auth/callback', callback);\n * ```\n */\nexport function oidcLoginHandlers(options: OidcLoginOptions): {\n /** `GET` handler that redirects the browser to the AXIAM authorization endpoint. */\n login: RequestHandler;\n /** `GET` handler for the redirect URI: consumes `state`, exchanges `code`, validates the ID token. */\n callback: RequestHandler;\n} {\n const login: RequestHandler = async (req: Request, res: Response): Promise<void> => {\n const returnTo = typeof req.query.returnTo === 'string' ? req.query.returnTo : undefined;\n sendOidcOutcome(res, await beginOidcLogin(options, returnTo));\n };\n\n const callback: RequestHandler = async (req: Request, res: Response): Promise<void> => {\n const query = req.query as Record<string, unknown>;\n sendOidcOutcome(\n res,\n await completeOidcLogin(options, {\n ...(typeof query.state === 'string' ? { state: query.state } : {}),\n ...(typeof query.code === 'string' ? { code: query.code } : {}),\n ...(typeof query.error === 'string' ? { error: query.error } : {}),\n ...(typeof query.error_description === 'string'\n ? { error_description: query.error_description }\n : {}),\n }),\n );\n };\n\n return { login, callback };\n}\n","// Fastify middleware (D-27, CONTRACT.md §10) — registered as a\n// `preHandler` hook via a FastifyPluginAsync, mirroring express.ts's\n// verification flow through the same shared verifyCore.\n\nimport type { FastifyPluginAsync, FastifyReply, FastifyRequest } from 'fastify';\nimport { AuthError, AuthzError } from '../core/index.js';\nimport {\n assertAuthzClient,\n authzDeniedBody as authzDeniedBodyShared,\n authzUnavailableBody,\n evaluateAccess,\n hasAnyRole,\n invalidRequestBody,\n missingAuthBody,\n resolveResourceId,\n ResourceResolutionError,\n type AuthzVerifiableSession,\n type RequireAccessOptions,\n type ResourceSpec,\n} from './authzCore.js';\nimport { CSRF_HEADER_NAME, extractCredential, isCsrfValid, isSafeMethod } from './cookieHeader.js';\nimport {\n challengeFor401,\n challengeFor403,\n isMetadataDocumentRequest,\n mcpGuardChallenges,\n} from './mcpCore.js';\nimport {\n beginOidcLogin,\n completeOidcLogin,\n type OidcLoginOptions,\n type OidcLoginOutcome,\n} from './oidcLoginCore.js';\nimport { certificateProofFromSocket } from './peerCertificate.js';\nimport { authenticateRequest, type AxiamIdentity, type VerifiableSession } from './verifyCore.js';\n\n/** A Fastify `FastifyRequest` augmented with the AXIAM identity that `axiamPlugin` injects after §10 verification. */\nexport interface AxiamFastifyRequest extends FastifyRequest {\n /** The authenticated identity, present once `axiamPlugin` (or `requireAuthHook`) has run; absent on an unauthenticated request. */\n axiamUser?: AxiamIdentity;\n}\n\n/** A Fastify `preHandler`-compatible hook function (CONTRACT.md §11) — usable both via `fastify.addHook('preHandler', ...)` and per-route as `{ preHandler: hook }`. */\nexport type PreHandlerHook = (request: FastifyRequest, reply: FastifyReply) => Promise<void>;\n\ninterface ErrorBody {\n error: string;\n message: string;\n}\n\nfunction missingCredentialsBody(): ErrorBody {\n return { error: 'authentication_failed', message: 'missing authentication credentials' };\n}\n\nfunction invalidTokenBody(message: string): ErrorBody {\n return { error: 'authentication_failed', message };\n}\n\nfunction authzDeniedBody(message: string): ErrorBody {\n return { error: 'authorization_denied', message };\n}\n\nfunction csrfDeniedBody(): ErrorBody {\n return { error: 'authorization_denied', message: 'csrf validation failed' };\n}\n\n/**\n * The `preHandler` body shared by `axiamPlugin` (registered globally as a\n * hook) and `requireAuthHook` (mounted per-route) — extracts the session\n * (cookie-first, then `Authorization: Bearer` fallback), verifies it\n * locally against the cached JWKS (D-11), and injects `request.axiamUser`\n * on success. Replies 401 (AuthError) or 403 (AuthzError/CSRF) with a\n * standardized JSON error body on failure.\n *\n * **CSRF (cookie double-submit, CONTRACT.md §3):** when the credential was\n * sourced from the `axiam_access` COOKIE (not the `Authorization` header)\n * and the request method is state-changing (anything other than\n * GET/HEAD/OPTIONS), this hook additionally requires the `X-CSRF-Token`\n * request header to be present and equal (constant time) to the\n * `axiam_csrf` cookie value, replying 403 on mismatch/absence. Bearer-header\n * requests are CSRF-immune by construction — a cross-site attacker cannot\n * set arbitrary request headers — but a cookie automatically attached by\n * the browser is not, and in any same-site deployment where `axiam_access`\n * reaches this app, the non-`httpOnly` `axiam_csrf` cookie does too. This\n * mirrors, locally, the same double-submit check the AXIAM server performs\n * on its own endpoints (§3).\n */\nfunction buildAuthHook(session: VerifiableSession, operation: string): PreHandlerHook {\n // §28.5: validated and precomputed at construction, `undefined` when\n // `resourceMetadataUrl` is unset — which is what keeps a guard without §28\n // byte-for-byte identical to one from before §28 existed.\n const challenges = mcpGuardChallenges(session, operation);\n\n return async (request: FastifyRequest, reply: FastifyReply) => {\n // §28.3 rule 2: the metadata document MUST answer without a credential.\n // A Fastify `preHandler` hook applies to every route in its context\n // regardless of registration order, so there is no ordering trick that\n // would exempt the path — the exemption has to be here, and explicit.\n if (isMetadataDocumentRequest(challenges, request.method, request.url)) return;\n\n const credential = extractCredential(request.headers.cookie, request.headers.authorization);\n if (!credential) {\n // §28.4: no credential is not a bad credential, so the challenge names\n // no error code (RFC 6750 §3).\n if (challenges) void reply.header('WWW-Authenticate', challenges.noCredential);\n await reply.code(401).send(missingCredentialsBody());\n return;\n }\n\n if (credential.source === 'cookie' && !isSafeMethod(request.method)) {\n const csrfHeader = request.headers[CSRF_HEADER_NAME];\n const csrfValue = Array.isArray(csrfHeader) ? csrfHeader[0] : csrfHeader;\n if (!isCsrfValid(request.headers.cookie, csrfValue)) {\n await reply.code(403).send(csrfDeniedBody());\n return;\n }\n }\n\n try {\n // §10.1 rule 9: same evidence as the Express guard — the peer\n // certificate the TLS layer verified for THIS connection, from\n // Fastify's raw Node request. `{}` (no evidence) when it is not\n // TLS-shaped or carries no certificate.\n const proofs = await certificateProofFromSocket(request.raw.socket);\n const identity = await authenticateRequest(session, credential.token, proofs);\n (request as AxiamFastifyRequest).axiamUser = identity;\n } catch (err) {\n if (err instanceof AuthzError) {\n // §28.5 rule 5: this 403 is not a `no_grant` scope denial, so it gains\n // no header.\n await reply.code(403).send(authzDeniedBody(err.message));\n return;\n }\n // §28.4: a credential was presented and rejected. Expired, not yet\n // valid, wrong tenant, wrong audience, bad signature, an unsatisfiable\n // `cnf`, a revoked `sid` — all of them are `invalid_token`,\n // indistinguishably. Every distinction a 401 draws for an\n // unauthenticated stranger is an oracle.\n if (challenges) void reply.header('WWW-Authenticate', challenges.invalidToken);\n if (err instanceof AuthError) {\n await reply.code(401).send(invalidTokenBody(err.message));\n return;\n }\n await reply.code(401).send(invalidTokenBody('invalid or expired token'));\n }\n };\n}\n\n/**\n * `axiamPlugin(session)` — a `FastifyPluginAsync` registering the shared\n * auth `preHandler` hook globally (D-27, CONTRACT.md\n * §10). Marked with fastify's own `skip-override` plugin symbol (the same\n * mechanism the `fastify-plugin` package wraps) so the `preHandler` hook\n * applies to routes registered as siblings of this plugin rather than\n * being scoped only to its own encapsulation context — avoids adding\n * `fastify-plugin` as a dependency for a one-line escape hatch.\n */\nexport const axiamPlugin: (session: VerifiableSession) => FastifyPluginAsync = (session) => {\n // Built here rather than inside the plugin body so §28.5's configuration\n // refusal happens when `axiamPlugin(session)` is called — construction time,\n // before `register` and before the server is listening.\n const hook = buildAuthHook(session, 'axiamPlugin');\n const plugin: FastifyPluginAsync = async (fastify) => {\n fastify.addHook('preHandler', hook);\n };\n (plugin as unknown as Record<symbol, unknown>)[Symbol.for('skip-override')] = true;\n (plugin as unknown as Record<symbol, unknown>)[Symbol.for('fastify.display-name')] =\n 'axiam-plugin';\n return plugin;\n};\n\n/**\n * `requireAuthHook(session)` (CONTRACT.md §11.1) — the canonical §11 name\n * for the same §10 guard `axiamPlugin` already provides, as a plain\n * `preHandler` function usable per-route:\n * `fastify.get('/x', { preHandler: requireAuthHook(session) }, handler)`,\n * rather than registered globally via `fastify.register(axiamPlugin(session))`.\n * Pure sugar: it performs no verification of its own beyond what the shared\n * auth `preHandler` hook (also used by `axiamPlugin`) already does.\n */\nexport function requireAuthHook(session: VerifiableSession): PreHandlerHook {\n return buildAuthHook(session, 'requireAuthHook');\n}\n\n/**\n * `requireAccessHook(session, action, resource, opts?)` (CONTRACT.md §11) —\n * the Fastify `preHandler` counterpart to `requireAccess` (see that\n * function's doc for the full §11 semantics). Throws synchronously (at\n * route-setup time) if `session.authzClient` is not configured. Requires\n * `request.axiamUser` to already be set (by `axiamPlugin`/`requireAuthHook`\n * mounted earlier in the chain) — replies 401 immediately when absent.\n */\nexport function requireAccessHook(\n session: AuthzVerifiableSession,\n action: string,\n resource: ResourceSpec<FastifyRequest>,\n opts?: RequireAccessOptions,\n): PreHandlerHook {\n const checker = assertAuthzClient(session);\n // §28.5 rule 5's challenge is built here, from this route's own `scope`\n // argument, so a scope outside RFC 6750's syntax fails at route setup rather\n // than on the first denial.\n const challenges = mcpGuardChallenges(session, 'requireAccessHook', opts?.scope);\n\n return async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n const axiamUser = (request as AxiamFastifyRequest).axiamUser;\n if (!axiamUser) {\n if (challenges) {\n void reply.header(\n 'WWW-Authenticate',\n challengeFor401(challenges, request.headers.cookie, request.headers.authorization),\n );\n }\n await reply.code(401).send(missingAuthBody());\n return;\n }\n\n let resourceId: string;\n try {\n resourceId = resolveResourceId(\n request,\n resource,\n (r) => r.params as Record<string, string | undefined>,\n );\n } catch (err) {\n const message = err instanceof ResourceResolutionError ? err.message : 'invalid resource';\n await reply.code(400).send(invalidRequestBody(message));\n return;\n }\n\n const outcome = await evaluateAccess(\n checker,\n action,\n resourceId,\n axiamUser.userId,\n opts?.scope,\n opts?.umaChallenge,\n );\n if (outcome.kind === 'denied') {\n opts?.logger?.debug('axiam_sdk.authz', 'access denied', { action, resourceId });\n // §20.3's UMA challenge wins where both apply — see `requireAccess` for\n // why. Only one `WWW-Authenticate` value is emitted either way.\n const challenge = outcome.challenge ?? challengeFor403(challenges, outcome.reasonCode);\n if (challenge) {\n // §20.3 / §28.5 rule 5, additive: the body keeps the unchanged §11.2.5\n // shape, so `insufficient_scope` appears only in the header and the\n // body is still `authorization_denied`.\n void reply.header('WWW-Authenticate', challenge);\n }\n await reply.code(403).send(authzDeniedBodyShared(outcome.message));\n return;\n }\n if (outcome.kind === 'unavailable') {\n opts?.logger?.debug('axiam_sdk.authz', 'authz check unavailable', { action, resourceId });\n await reply.code(503).send(authzUnavailableBody(outcome.message));\n return;\n }\n };\n}\n\n/**\n * `requireRoleHook(session, ...roles)` (CONTRACT.md §11.1, MAY) — the\n * Fastify `preHandler` counterpart to `requireRole`; see that function's\n * doc for the full semantics (local-only check, no server round-trip).\n * `session` is taken first for signature parity with\n * `requireAuthHook`/`requireAccessHook`; the role check reads nothing from it,\n * and §28.5 is the only thing that does.\n */\nexport function requireRoleHook(session: VerifiableSession, ...roles: string[]): PreHandlerHook {\n // The one thing this guard does read off the session: §28.5 rule 4 puts the\n // challenge on every 401 the guard emits, and this guard emits one.\n const challenges = mcpGuardChallenges(session, 'requireRoleHook');\n\n return async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n const axiamUser = (request as AxiamFastifyRequest).axiamUser;\n if (!axiamUser) {\n if (challenges) {\n void reply.header(\n 'WWW-Authenticate',\n challengeFor401(challenges, request.headers.cookie, request.headers.authorization),\n );\n }\n await reply.code(401).send(missingAuthBody());\n return;\n }\n if (!hasAnyRole(axiamUser.roles, roles)) {\n // §28.5 rule 5: a role failure is not a scope failure — no header.\n await reply.code(403).send(authzDeniedBodyShared('missing required role'));\n return;\n }\n };\n}\n\n// ---------------------------------------------------------------------------\n// \"Login with AXIAM\" routes (CONTRACT.md §12)\n// ---------------------------------------------------------------------------\n\n/** Apply an {@link OidcLoginOutcome} to a Fastify reply. */\nasync function sendOidcOutcome(reply: FastifyReply, outcome: OidcLoginOutcome): Promise<void> {\n if (outcome.kind === 'redirect') {\n // 302 + Location, written directly rather than via @fastify/redirect — the\n // SDK adds no new dependency for a two-line response.\n await reply.code(302).header('location', outcome.url).send();\n return;\n }\n if (outcome.kind === 'json') {\n await reply.code(200).send(outcome.body);\n return;\n }\n await reply.code(outcome.status).send(outcome.body);\n}\n\n/** Route paths the {@link oidcLoginPlugin} registers, relative to where it is registered. */\nexport interface OidcLoginRoutePaths {\n /** Path of the login-redirect route. Defaults to `/auth/login`. */\n loginPath?: string;\n /** Path of the callback route — must match the public URL in `redirectUri`. Defaults to `/auth/callback`. */\n callbackPath?: string;\n}\n\n/**\n * `oidcLoginPlugin(options)` (CONTRACT.md §12) — a `FastifyPluginAsync`\n * registering the two \"Login with AXIAM\" routes: a login-redirect route and\n * the callback route that consumes `state`, exchanges the code, and validates\n * the ID token.\n *\n * @remarks\n * The Fastify counterpart of Express's `oidcLoginHandlers`, built on the same\n * {@link beginOidcLogin} / {@link completeOidcLogin} core, so the two\n * frameworks cannot drift on flow semantics or error mapping. See\n * `oidcLoginHandlers` for the `returnTo` open-redirect caveat and the\n * `onSuccess` session-establishment contract, which apply identically here.\n *\n * Unlike `axiamPlugin` this plugin is deliberately **encapsulated** (no\n * `skip-override` marker): it registers routes rather than a hook, so there is\n * nothing that needs to escape its own context.\n *\n * @example\n * ```ts\n * await fastify.register(oidcLoginPlugin({\n * client: oidc,\n * store: new MemoryOidcStateStore(),\n * redirectUri: 'https://app.example.com/auth/callback',\n * onSuccess: (tokens) => { myAppSession.establish(tokens.idClaims!.sub); },\n * }));\n * ```\n */\nexport const oidcLoginPlugin: (\n options: OidcLoginOptions & OidcLoginRoutePaths,\n) => FastifyPluginAsync = (options) => {\n const loginPath = options.loginPath ?? '/auth/login';\n const callbackPath = options.callbackPath ?? '/auth/callback';\n\n const plugin: FastifyPluginAsync = async (fastify) => {\n fastify.get(loginPath, async (request: FastifyRequest, reply: FastifyReply) => {\n const query = request.query as Record<string, unknown>;\n const returnTo = typeof query.returnTo === 'string' ? query.returnTo : undefined;\n await sendOidcOutcome(reply, await beginOidcLogin(options, returnTo));\n });\n\n fastify.get(callbackPath, async (request: FastifyRequest, reply: FastifyReply) => {\n const query = request.query as Record<string, unknown>;\n await sendOidcOutcome(\n reply,\n await completeOidcLogin(options, {\n ...(typeof query.state === 'string' ? { state: query.state } : {}),\n ...(typeof query.code === 'string' ? { code: query.code } : {}),\n ...(typeof query.error === 'string' ? { error: query.error } : {}),\n ...(typeof query.error_description === 'string'\n ? { error_description: query.error_description }\n : {}),\n }),\n );\n });\n };\n\n (plugin as unknown as Record<symbol, unknown>)[Symbol.for('fastify.display-name')] =\n 'axiam-oidc-login';\n return plugin;\n};\n","// A session-free transport for calls that carry a credential of their own.\n//\n// CONTRACT.md §28.12.2 rule 3 (RFC 7592 client configuration) and §32.7\n// (`SsfReceiver.poll`) both send a bearer that is NOT this SDK's session — a\n// registration access token, a receiver's client-credentials token — and both\n// say the SDK's own session must not ride along: no session cookie, no access\n// token, no CSRF header, and no §9 refresh on a `401`. The session's axios\n// instance cannot give that guarantee, because its request interceptors add\n// those things and its response interceptor refreshes, so these calls go out\n// on a fresh axios instance instead:\n//\n// * no interceptors at all (no `X-Tenant-ID`, no `X-CSRF-Token`, no\n// `Authorization` the session adopted, no refresh-on-401);\n// * no cookie jar — under Node the session's TLS material is reused through\n// `noCredentialsConfig()`'s plain (jar-free) agents, so §6's custom CA and\n// §6.1's client certificate still apply; in a browser `withCredentials` is\n// off;\n// * no redirect following (`maxRedirects: 0`) — a redirect would hand the\n// bearer to whichever host the `Location` names. **Node only:** a browser's\n// XHR/fetch follows same-origin redirects itself and offers no way to stop\n// it, which is one reason these helpers are documented as server-side;\n// * every status resolved rather than thrown (`validateStatus`), so the\n// caller maps it with the tolerant `/oauth2` decoder and decides retries\n// itself.\n\nimport axios, { type AxiosRequestConfig, type AxiosResponse } from 'axios';\nimport { NetworkError } from '../core/index.js';\nimport type { SharedSession } from './session.js';\n\n/**\n * Issue one request on a fresh, interceptor-free, jar-free, redirect-free\n * axios instance carrying this session's TLS configuration only.\n *\n * A transport failure (no response at all) becomes a {@link NetworkError}\n * whose message names the operation and the low-level error code only. The\n * axios error itself is **not** attached as `cause`: its `config` holds the\n * request headers — the bearer this call exists to protect — and the request\n * body.\n *\n * @internal\n */\nexport async function bareRequest<T>(\n session: SharedSession,\n operation: string,\n config: AxiosRequestConfig,\n): Promise<AxiosResponse<T>> {\n const defaults = session.axios.defaults;\n const instance = axios.create({\n timeout: defaults.timeout,\n // The base session's own TLS agent (custom CA / client certificate, no\n // jar). Under the Node persona this is the jar-wrapped cookie agent, which\n // `noCredentialsConfig()` below replaces with a plain one.\n ...(defaults.httpsAgent !== undefined ? { httpsAgent: defaults.httpsAgent } : {}),\n // The bare transport carries the RFC 7592 registration calls on `/oauth2/register/*`,\n // so it gets an `/oauth2/*` request's config: in the browser persona the fetch adapter\n // that omits credentials (C164-06; identical to `noCredentialsConfig()` under Node).\n ...session.oauth2RequestConfig(),\n withCredentials: false,\n maxRedirects: 0,\n validateStatus: () => true,\n });\n let response: AxiosResponse<T>;\n try {\n response = await instance.request<T>(config);\n } catch (err) {\n const code =\n err && typeof err === 'object' && 'code' in err && typeof (err as { code?: unknown }).code === 'string'\n ? ` (${(err as { code: string }).code})`\n : '';\n throw new NetworkError(`${operation}: the request failed before any response arrived${code}`);\n }\n // CONTRACT.md §12.1 rule 3: no redirect is followed and a 3xx is a NetworkError. A browser\n // `fetch` with `redirect: 'error'` rejects above; this catches an adapter that hands the\n // redirect (or an opaque-redirect, status 0) back as a response. Neither the `Location`\n // nor the request is put in the message.\n if (response.status === 0 || (response.status >= 300 && response.status < 400)) {\n throw new NetworkError(`${operation}: the server answered with a redirect, which is not followed`);\n }\n return response;\n}\n\n/**\n * Parse a `Retry-After` header (delta-seconds form only) into milliseconds, for\n * the §16 runner's floor. An HTTP-date or anything unparseable is ignored.\n *\n * @internal\n */\nexport function retryAfterMs(response: AxiosResponse): number | undefined {\n const raw = response.headers?.['retry-after'];\n const value = typeof raw === 'string' ? raw.trim() : undefined;\n if (value === undefined || !/^\\d+$/.test(value)) return undefined;\n return Number(value) * 1000;\n}\n\n/**\n * Whether §16 may retry a response with this status: `408`, `429` and every\n * `5xx`. Every other `4xx` is a decisive answer — including a bodiless `400`,\n * which §2 maps to `NetworkError` and which the shared runner would otherwise\n * retry because it retries every `NetworkError`.\n *\n * @internal\n */\nexport function statusIsRetryable(status: number): boolean {\n return status === 408 || status === 429 || status >= 500;\n}\n\n/**\n * A `NetworkError` the §16 runner may retry, carrying the server's\n * `Retry-After` as the floor it reads.\n *\n * @internal\n */\nexport function retryableNetworkError(message: string, response?: AxiosResponse): NetworkError {\n const error = new NetworkError(message);\n const floor = response ? retryAfterMs(response) : undefined;\n if (floor !== undefined) {\n Object.defineProperty(error, 'retryAfterMs', { value: floor, enumerable: false });\n }\n return error;\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 // CONTRACT.md §6.1 rule 11 / CONTRACT 1.52 N4.5 (C-12): \"A `401` on the\n // device POST itself ... is `AuthError`, with no refresh call ... even\n // when the client holds an earlier session.\" Without this entry, a client\n // that already completed a password login (`session.authenticated ===\n // true`) and then called `authenticateDevice()` into a refusal had that\n // 401 misread as an ordinary authenticated-session 401 — this IS the\n // login, so it must never itself trigger a refresh-then-retry cycle,\n // regardless of what session state came before it.\n '/api/v1/auth/device',\n '/oauth2/token',\n // CONTRACT.md §14.2 rule 5 (contract 1.62): a client that fails to\n // authenticate at the device endpoints is `401 invalid_client`, which is not\n // an expired session and which refreshing cannot fix. `/oauth2/token` (the\n // poll) was already here; the authorization endpoint now authenticates the\n // client too, so its 401 must not enter the §9 guard either.\n '/oauth2/device_authorization',\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 // CONTRACT.md §6.1 rule 11, §12.1 rule 3, §14.6 (contract 1.63): no\n // `X-CSRF-Token` on an `/oauth2/*` request — it authenticates the client\n // through the form body (or the TLS certificate), never the session.\n if (isOAuth2Endpoint(config.url, session.baseUrl)) {\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 // §6.1 rule 6 (contract 1.51): a device token has no refresh token\n // behind it. A later 401 on it is AuthError, never a refresh attempt —\n // there is nothing the §9 guard could spend, and the recovery path is\n // calling authenticateDevice() again (one TLS handshake), not this.\n const isDeviceSession = session.deviceAccessToken !== undefined;\n\n if (status === 401 && !originalRequest._retry && !isSkipRefresh && session.authenticated && !isDeviceSession) {\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 || isDeviceSession)) {\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/**\n * True for a request to an `/oauth2/*` endpoint: the request path, relative to the base\n * URL's own path, begins with `/oauth2/` (absolute or relative `url`; query ignored). A prefix\n * match, not a substring one — `/api/v1/auth/federation/oauth2/callback` is an ordinary\n * session endpoint whose `Set-Cookie` the jar must keep.\n */\nexport function isOAuth2Endpoint(url: string | undefined, baseUrl: string): boolean {\n if (!url) {\n return false;\n }\n try {\n const base = new URL(baseUrl);\n let path = new URL(url, base).pathname;\n const prefix = base.pathname.replace(/\\/+$/, '');\n if (prefix !== '' && path.startsWith(`${prefix}/`)) {\n path = path.slice(prefix.length);\n }\n return path.startsWith('/oauth2/');\n } catch {\n return false;\n }\n}\n\n/**\n * Request interceptor: once `authenticateDevice()` has adopted a token\n * (`session.deviceAccessToken`), every same-origin request carries it as\n * `Authorization: Bearer` — except to `/oauth2/*`, which gets no `Authorization`\n * header at all (§6.1 rule 11, §14.6, C162-05) — and rides the jar-free agent pair\n * `noCredentialsConfig()` builds — TLS-configured (the client certificate\n * stays on the connection), but with no cookie jar attached (CONTRACT.md\n * §6.1 rules 6-10, contract 1.51).\n *\n * The server reads the `axiam_access` cookie BEFORE the `Authorization`\n * header, so leaving the jar attached would let a cookie from an earlier\n * session on this same client silently outrank this token and the request\n * would run as that earlier session's principal — the exact hazard the\n * reference Rust SDK's own re-vendor flagged (\"what the plan did not\n * anticipate\", note 3). A session that never calls `authenticateDevice()`\n * is byte-for-byte unaffected: `deviceAccessToken` stays `undefined` and\n * this branch never runs.\n *\n * Installed by `installInterceptors` (bound to whichever `session`\n * `AxiamClient`'s constructor was actually given — the Node persona's real\n * `NodeSession`, not the transient `SharedSession` `createSession()`\n * discards after lifting its `.axios`/`.tenantHeaderValue` into it) rather\n * than inside `session.ts`'s `createSession`, so it always observes the\n * `deviceAccessToken` `authenticateDevice()` actually sets.\n */\nexport function installDeviceTokenInterceptor(axiosInstance: AxiosInstance, session: SharedSession): void {\n axiosInstance.interceptors.request.use((config) => {\n const deviceToken = session.deviceAccessToken;\n const oauth2 = isOAuth2Endpoint(config.url, session.baseUrl);\n if (session.isForeignHost(config.url) || (deviceToken === undefined && !oauth2)) {\n return config;\n }\n // An `/oauth2/*` request also gets the browser persona's fetch adapter with\n // `credentials: 'omit'` (C163-12); the other credential-free calls do not.\n const noCred = oauth2 ? session.oauth2RequestConfig() : session.noCredentialsConfig();\n Object.assign(config, noCred);\n config.headers = config.headers ?? {};\n if (oauth2) {\n // CONTRACT.md §6.1 rule 11, §12.1 rule 3 and §14.6 (contract 1.62, C162-05;\n // contract 1.63 extends it to the session cookies and `X-CSRF-Token`):\n // an `/oauth2/*` endpoint authenticates the client through the form body\n // (or the TLS certificate), so neither the adopted device credential nor\n // an `axiam_*` session cookie rides on it — the cookie stays out through\n // the jar-free agent pair above, and the CSRF interceptor adds no\n // `X-CSRF-Token` there. A credential the caller passes explicitly to\n // one call (RFC 7591/7592 registration tokens) travels on the bare\n // transport, which never reaches this interceptor.\n // An `Authorization` the caller set on this one call is left as given.\n return config;\n }\n config.headers['Authorization'] = `Bearer ${deviceToken!.expose()}`;\n // Belt and braces alongside the agent swap above: an explicit empty\n // Cookie header is what the reference Rust SDK relies on to make sure a\n // stale session cookie cannot ride beside this token even if something\n // downstream of noCredentialsConfig() still had one to offer.\n config.headers['Cookie'] = '';\n return config;\n });\n}\n\n/** Install the CSRF, reactive single-flight refresh, and §6.1 device-token interceptors. */\nexport function installInterceptors(axiosInstance: AxiosInstance, session: SharedSession): void {\n installCsrfInterceptor(axiosInstance, session);\n installRefreshInterceptor(axiosInstance, session);\n installDeviceTokenInterceptor(axiosInstance, session);\n}\n","// Bounded read-only retry policy — CONTRACT.md §16.\n//\n// This file previously held a policy of its own invention: 1000 ms base, 8 s\n// cap, partial jitter (`base + 0–20%`), and `Retry-After` *replacing* the\n// computed backoff rather than flooring it. Two problems with that, both now\n// fixed:\n//\n// * `retryAfterMs ?? backoffDelayMs(attempt)` meant a `Retry-After: 0`\n// retried immediately, defeating the backoff entirely — exactly what\n// §16.1's \"floor, never a ceiling\" forbids.\n// * It was exported and unit-tested but **never called by any production\n// path**. `checkAccess` did not route through it, so this SDK performed no\n// read-only retries at all while appearing to. A tested helper nobody calls\n// is worse than an absent one: the green tests are what stop anyone from\n// looking.\n//\n// §16 is the normative table all eleven SDKs now share. `withRetry` is wired\n// into the authz surface in `authz.ts`; the §16.7 tests assert the policy\n// through the public `checkAccess` API, not just against this helper.\n\nimport { NetworkError } from '../core/index.js';\nimport type { TelemetryDispatcher } from '../core/telemetry.js';\n\n/** Attempt cap: 1 initial + 2 retries (§16.1). */\nexport const MAX_ATTEMPTS = 3;\n/** First backoff step, in milliseconds (§16.1). */\nexport const BASE_DELAY_MS = 200;\n/** Ceiling on any single computed backoff, in milliseconds (§16.1). */\nexport const MAX_DELAY_MS = 5_000;\n\n/** Options controlling {@link withRetry}. */\nexport interface RetryOptions {\n /**\n * Only operations that change **no server state** may be retried (§16.2).\n *\n * Note this means side-effect-free, **not** \"is an HTTP GET\": AXIAM's\n * authorization check is a `POST` with a request body and is the single most\n * important operation covered by this policy.\n */\n idempotent: boolean;\n /** Canonical operation name, for the §19 `retry` event. */\n operation?: string;\n /** Set `false` to disable retrying entirely (§16.1 disable switch). */\n enabled?: boolean;\n /** §19 sink, notified before each retry wait. */\n telemetry?: TelemetryDispatcher;\n /** Injected for tests — see §16.7 (\"a test that really waits 200 ms is a test nobody runs\"). */\n sleepFn?: (ms: number) => Promise<void>;\n /** Injected for tests: returns the jitter fraction in [0, 1]. */\n randomFn?: () => number;\n /**\n * Called with the wait before a retry is announced or served; throwing refuses the retry, so\n * nothing is emitted for it and nothing more is sent. A poll inside a deadline uses it to refuse\n * a wait that would reach the deadline (CONTRACT.md §14.2 rule 4, §34.2 P10).\n */\n admit?: (delayMs: number) => void;\n}\n\ninterface RetryAfterCarrier {\n retryAfterMs?: number;\n}\n\nfunction isRetryAfterCarrier(err: unknown): err is RetryAfterCarrier {\n return typeof err === 'object' && err !== null && 'retryAfterMs' in err;\n}\n\nfunction defaultSleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * The un-jittered backoff for a 1-based attempt: `min(cap, base * 2^(n-1))`.\n * Attempt 1 → 200 ms, attempt 2 → 400 ms.\n */\nexport function backoffMs(attempt: number): number {\n return Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** (attempt - 1));\n}\n\n/**\n * The actual wait: **full jitter** over `[0, backoff]`, then raised to any\n * server-supplied `Retry-After` (§16.1).\n *\n * Full jitter, not `backoff ± 10%`. Partial jitter keeps every client's retries\n * clustered around the same instant, which is the thundering herd retries are\n * supposed to prevent rather than cause.\n *\n * `Retry-After` is a **floor, never a ceiling**: the server is saying when it\n * will be ready, so retrying sooner is not permitted — and a `Retry-After: 0`\n * cannot shorten the wait below what jitter chose.\n */\nexport function delayMs(attempt: number, retryAfterMs: number | undefined, fraction: number): number {\n const jittered = backoffMs(attempt) * Math.min(Math.max(fraction, 0), 1);\n return retryAfterMs === undefined ? jittered : Math.max(jittered, retryAfterMs);\n}\n\n/**\n * Runs `fn` under the §16 policy.\n *\n * `fn` receives the 1-based attempt number so it can label its §19\n * `requestStart`/`requestEnd` pair. That is not cosmetic: §19.2 rule 5 requires\n * one pair **per attempt** with the attempt distinguishing them, so a caller\n * can count real wire calls. Emitting every pair as attempt 1 would make a\n * retried call indistinguishable from a single slow one — the exact blindness\n * §16.5 exists to remove.\n *\n * `fn` MUST be side-effect-free. This helper — like every retry helper — cannot\n * tell the difference, so routing a mutation through it would silently\n * duplicate a side effect, or replay a single-use credential (an authorization\n * code, a device code at redemption, a rotating refresh token) into a hard\n * `invalid_grant`.\n *\n * Only `NetworkError` is retried. The §2 taxonomy folds `408`/`429`/`5xx`/\n * transport into that one type, so this implements the whole §16.3 table:\n * `AuthError` and `AuthzError` are decisive answers, not transport failures.\n */\nexport async function withRetry<T>(\n fn: (attempt: number) => Promise<T>,\n options: RetryOptions,\n): Promise<T> {\n const retryable = options.idempotent && options.enabled !== false;\n const maxAttempts = retryable ? MAX_ATTEMPTS : 1;\n const sleep = options.sleepFn ?? defaultSleep;\n const random = options.randomFn ?? Math.random;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n try {\n return await fn(attempt);\n } catch (err) {\n const isLastAttempt = attempt === maxAttempts;\n if (!retryable || !(err instanceof NetworkError) || isLastAttempt) {\n throw err;\n }\n const retryAfterMs = isRetryAfterCarrier(err) ? err.retryAfterMs : undefined;\n const delay = delayMs(attempt, retryAfterMs, random());\n options.admit?.(delay);\n // §16.5 — without this event a retried-then-succeeded call is invisible:\n // a slow success with no signal that the server is failing.\n options.telemetry?.emit({\n type: 'retry',\n operation: options.operation ?? 'unknown',\n attempt,\n delayMs: delay,\n reason: err instanceof Error ? err.message : String(err),\n });\n await sleep(delay);\n }\n }\n\n // Unreachable: the loop above always returns or throws.\n throw new NetworkError('retry loop exhausted without a result');\n}\n","// 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';\nimport type { ProviderNonce } from './oidcTypes.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\n/**\n * A fresh nonce pair for native sign-in with a provider ID token\n * (CONTRACT.md §37.4) — **pure local computation, no network I/O**.\n *\n * `raw` is 32 CSPRNG bytes, base64url without padding, wrapped in\n * {@link Sensitive}; `hashed` is the lower-case hexadecimal SHA-256 of the\n * bytes of `raw` as sent. Give `hashed` to the provider's SDK as *its* nonce\n * and `raw` to `loginWithProviderIdToken`. Nothing is stored.\n */\nexport function nativeNonce(): ProviderNonce {\n const raw = randomUrlSafeToken(CSPRNG_BYTES);\n return { raw: new Sensitive(raw), hashed: createHash('sha256').update(raw, 'utf8').digest('hex') };\n}\n","// OIDC / SSO relying-party helpers — CONTRACT.md §12 (contract 1.38).\n//\n// The thirteen canonical §12 operations, under the exact §12.2 TypeScript\n// names: oidcDiscover, oidcBegin, oidcExchange, oidcRefresh,\n// loginClientCredentials, introspect, revoke, ssoStart, ssoComplete, and — as\n// of contract 1.38 — ssoProviders, ssoStartOauth2, ssoCompleteOauth2,\n// ssoCompleteHandoff.\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 { randomBytes, timingSafeEqual, type KeyObject } from 'node:crypto';\nimport type { AxiosRequestConfig, AxiosResponse } from 'axios';\nimport {\n AuthError,\n AxiamError,\n isOAuth2ErrorBody,\n mapHttpStatusToError,\n NetworkError,\n OAuthProtocolError,\n oauth2ErrorFromBody,\n sanitizeAxiosError,\n Sensitive,\n} from '../core/index.js';\nimport { ValidationError } from '../management/errors.js';\nimport { retryAfterMs, retryableNetworkError, statusIsRetryable } from '../rest/bareTransport.js';\nimport { isOAuth2Endpoint } from '../rest/interceptors.js';\nimport { withRetry } from '../rest/retry.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 LoginWithProviderIdTokenOptions,\n OidcBeginParams,\n OidcConfiguration,\n OidcExchangeParams,\n MtlsEndpointAliases,\n OidcRefreshParams,\n OidcStartResponseWire,\n OidcTokenSet,\n RevokeParams,\n SsoCompleteParams,\n SsoCompleteResult,\n SsoLoginSuccessResponseWire,\n SsoStartParams,\n SsoStartResult,\n FederationProvider,\n FederationProviderList,\n OAuth2StartResponseWire,\n PublicFederationProvidersResponseWire,\n SsoCompleteHandoffParams,\n SsoCompleteOauth2Params,\n SsoProvidersParams,\n SsoStartOauth2Params,\n TokenResponseWire,\n DeviceAuthorization,\n DeviceAuthorizationResponseWire,\n DeviceAuthorizeParams,\n DeviceLoginParams,\n DevicePollParams,\n ExchangedToken,\n LogoutUrlParams,\n TokenExchangeParams,\n TokenExchangeResponseWire,\n VerifiedLogoutToken,\n RequestedPermission,\n RequestingPartyToken,\n ResourceSet,\n ResourceSetWire,\n RptResponseWire,\n UmaChallenge,\n UmaExchangeTicketParams,\n OidcParParams,\n PushedAuthorizationRequest,\n PushedAuthorizationResponseWire,\n CibaAwaitParams,\n CibaClock,\n CibaInitiateParams,\n CibaInitiateResponse,\n CibaPingHeaders,\n CibaPollParams,\n CibaSigningAlg,\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/** Path of the public provider-listing endpoint (contract 1.38). */\nexport const SSO_PROVIDERS_PATH = '/api/v1/auth/federation/providers';\n\n/** Path of the plain-OAuth2 federation step-1 endpoint (contract 1.38). */\nexport const SSO_OAUTH2_START_PATH = '/api/v1/auth/federation/oauth2/start';\n\n/** Path of the plain-OAuth2 federation step-2 (callback) endpoint (contract 1.38). */\nexport const SSO_OAUTH2_CALLBACK_PATH = '/api/v1/auth/federation/oauth2/callback';\n\n/** Path of the handoff-code redemption endpoint (contract 1.38). */\nexport const SSO_HANDOFF_PATH = '/api/v1/auth/federation/handoff';\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/** `grant_type` of the device access-token request (RFC 8628 §3.4). */\nexport const DEVICE_CODE_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:device_code';\n\n/**\n * Polling interval used when the authorization response omits `interval`\n * (RFC 8628 §3.2, §14.2 rule 2). An SDK MUST NOT hard-code a faster floor.\n */\nexport const DEFAULT_POLL_INTERVAL_SECS = 5;\n\n/**\n * Seconds added to the polling interval on each `slow_down` (§14.2 rule 1).\n * The increase is permanent and cumulative.\n */\nexport const SLOW_DOWN_INCREMENT_SECS = 5;\n\n/** `grant_type` of an RFC 8693 exchange. */\nexport const TOKEN_EXCHANGE_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange';\n\n/**\n * The `actor_token_type` this SDK sends, and the `subject_token_type` a caller\n * names for the same-domain exchange of §15.1. There is no default: the type is\n * a required member of {@link TokenExchangeParams}.\n */\nexport const ACCESS_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token';\n\n/**\n * A JWT from a trusted external issuer — the cross-domain exchange of §15.7.\n *\n * @remarks\n * Pass it as {@link TokenExchangeParams.subjectTokenType} to exchange a partner\n * IdP's token. AXIAM also accepts {@link ACCESS_TOKEN_TYPE} for an external\n * issuer, and refuses refresh and ID token types **by name**.\n */\nexport const JWT_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:jwt';\n\n/** `grant_type` of the UMA ticket grant (UMA 2.0 §3.3.1, CONTRACT.md §20.1). */\nexport const UMA_TICKET_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:uma-ticket';\n\n/** The scope that makes an access token a Protection API Token (§20.2 rule 1). */\nexport const UMA_PROTECTION_SCOPE = 'uma_protection';\n\n/** The only `claim_token_format` AXIAM v1 accepts (§20.2 rule 2). */\nexport const UMA_CLAIM_TOKEN_FORMAT = 'urn:ietf:params:oauth:token-type:access_token';\n\n/**\n * Parse a `WWW-Authenticate: UMA …` header value (CONTRACT.md §20.3).\n *\n * @remarks\n * **This deliberately does not exchange the ticket.** Parsing a challenge and\n * acting on it are separate decisions: the `as_uri` names an authorization\n * server this client has not necessarily chosen to trust, and auto-exchanging\n * would send the requesting party's `claimToken` to whatever host answered the\n * 403. The caller decides.\n *\n * @returns the parsed challenge, or `undefined` when the header is not a UMA\n * challenge.\n */\nexport function umaParseChallenge(header: string): UmaChallenge | undefined {\n const trimmed = header.trim();\n if (!trimmed.startsWith('UMA')) return undefined;\n const rest = trimmed.slice(3);\n // \"UMA\" alone is a valid, if useless, challenge; anything else must be\n // separated by whitespace so `UMAX realm=\"…\"` is not read as UMA.\n if (rest.length > 0 && !/^\\s/.test(rest)) return undefined;\n\n const challenge: UmaChallenge = {};\n for (const part of rest.split(',')) {\n const eq = part.indexOf('=');\n if (eq === -1) continue;\n const key = part.slice(0, eq).trim();\n const value = part.slice(eq + 1).trim().replace(/^\"|\"$/g, '');\n if (key === 'realm') challenge.realm = value;\n else if (key === 'as_uri') challenge.asUri = value;\n else if (key === 'ticket') challenge.ticket = new Sensitive(value);\n }\n return challenge;\n}\n\n/**\n * Format a `WWW-Authenticate: UMA` header value (§20.3, emit half).\n *\n * The resource-server side: having obtained a ticket from `umaRequestTicket`,\n * tell the caller where to redeem it.\n */\nexport function umaChallengeHeader(\n realm: string,\n asUri: string,\n ticket: Sensitive<string> | string,\n): string {\n return `UMA realm=\"${realm}\", as_uri=\"${asUri}\", ticket=\"${exposeSecret(ticket)}\"`;\n}\n\n/** Map the camelCase {@link ResourceSet} onto the snake_case wire shape. */\nfunction toResourceSetWire(resource: ResourceSet): ResourceSetWire {\n return {\n name: resource.name,\n ...(resource.type !== undefined ? { type: resource.type } : {}),\n // Always sent, even when empty: an update replaces the scope list, and\n // omitting the key would leave the server's copy untouched (§20.2 rule 8).\n resource_scopes: resource.resourceScopes ?? [],\n };\n}\n\n/** Map the wire shape back onto {@link ResourceSet}. */\nfunction fromResourceSetWire(wire: ResourceSetWire): ResourceSet {\n return {\n ...(wire._id != null ? { id: wire._id } : {}),\n name: wire.name,\n ...(wire.type != null ? { type: wire.type } : {}),\n resourceScopes: wire.resource_scopes ?? [],\n };\n}\n\n/**\n * The `events` member that distinguishes a logout token from an ID token\n * (OIDC Back-Channel Logout 1.0 §2.4).\n */\nexport const BACKCHANNEL_LOGOUT_EVENT = 'http://schemas.openid.net/event/backchannel-logout';\n\n/**\n * Maximum age accepted for a logout token's `iat`, in seconds. AXIAM issues\n * them with a 120 s lifetime; this bound is the same order and stops a token\n * captured from a mis-configured RP being replayed days later.\n */\nexport const MAX_LOGOUT_TOKEN_AGE_SECS = 300;\n\n/** The claim shape of a back-channel logout token (§12.7.3). */\ninterface LogoutTokenClaims {\n iss?: string;\n aud?: string;\n iat?: number;\n exp?: number;\n jti?: string;\n sid?: string;\n sub?: string;\n events?: Record<string, unknown>;\n /** Never legitimately present — see `verifyLogoutToken`. */\n nonce?: string;\n}\n\n/**\n * The §14.2 polling schedule: the interval, and the deadline it stops at.\n *\n * @remarks\n * Exported so the arithmetic §14.2 rules 1, 2 and 4 describe can be tested\n * exhaustively and instantly. Driving it through a mock HTTP server would\n * test the transport rather than the rule, and would take a real half-minute\n * to assert one `slow_down`.\n *\n * @internal\n */\nexport class PollSchedule {\n #intervalSecs: number;\n #remainingSecs: number;\n /** A `Retry-After` still to be served by the next wait (§14.2 rule 9, contract 1.64). */\n #retryAfterSecs = 0;\n\n constructor(intervalSecs: number, expiresInSecs: number) {\n this.#intervalSecs = intervalSecs > 0 ? intervalSecs : DEFAULT_POLL_INTERVAL_SECS;\n this.#remainingSecs = expiresInSecs;\n }\n\n /** The current inter-poll delay, in seconds. */\n get intervalSecs(): number {\n return this.#intervalSecs;\n }\n\n /**\n * The delay before the next poll, in seconds: the interval, or the pending\n * `Retry-After` when that is longer (a minimum, §14.2 rule 9).\n */\n get waitSecs(): number {\n return Math.max(this.#intervalSecs, this.#retryAfterSecs);\n }\n\n /**\n * Record a `429 rate_limit_exceeded` (§14.2 rule 9, contract 1.64): the next\n * wait lasts at least `retryAfterSecs` and stands in for one interval. The\n * interval itself is **not** raised — only the `400 slow_down` does that.\n */\n rateLimited(retryAfterSecs: number | undefined): void {\n this.#retryAfterSecs = retryAfterSecs !== undefined && retryAfterSecs > 0 ? retryAfterSecs : 0;\n }\n\n /** Apply one `slow_down` (§14.2 rule 1): **cumulative, never reset.** */\n slowDown(): void {\n this.#intervalSecs += SLOW_DOWN_INCREMENT_SECS;\n }\n\n /**\n * Consume one interval's worth of the grant's remaining life.\n *\n * @returns `false` when the deadline has been reached, at which point the\n * caller MUST stop (§14.2 rule 4) — the deadline is authoritative even if\n * the server is still answering `authorization_pending`.\n */\n tick(): boolean {\n // A pending `Retry-After` is served once, in place of the interval; past\n // the deadline it is capped there (§14.2 rule 9), which ends the loop.\n const waitSecs = this.waitSecs;\n this.#retryAfterSecs = 0;\n if (waitSecs >= this.#remainingSecs) {\n this.#remainingSecs = 0;\n return false;\n }\n this.#remainingSecs -= waitSecs;\n return true;\n }\n}\n\n/**\n * The `Retry-After` of a `429 rate_limit_exceeded` poll, in milliseconds, kept\n * beside the error rather than on it so the public error type is unchanged.\n */\nconst POLL_RETRY_AFTER_MS = new WeakMap<OAuthProtocolError, number>();\n\n/**\n * The §14.2 rule 9 reading of a device poll's `429` (contract 1.64, amended:\n * the status decides, not the body): an `OAuthProtocolError` with\n * `error == \"rate_limit_exceeded\"` whatever the body names — a bodiless `429`\n * from a proxy, or one saying `slow_down` as a server before 1.1.2 sent it,\n * included — with its `Retry-After` recorded in {@link POLL_RETRY_AFTER_MS}.\n * `undefined` for any other status, which keeps §2's mapping.\n */\nfunction pollRateLimit(err: unknown): OAuthProtocolError | undefined {\n if (axiosStatus(err) !== 429) return undefined;\n const body = axiosBody(err);\n const description =\n body !== null && typeof body === 'object' && typeof (body as { error_description?: unknown }).error_description === 'string'\n ? (body as { error_description: string }).error_description\n : '';\n const response = (err as { response?: AxiosResponse }).response;\n const retryAfter = response ? retryAfterMs(response) : undefined;\n const limited = new OAuthProtocolError('rate_limit_exceeded', description, retryAfter);\n if (retryAfter !== undefined) POLL_RETRY_AFTER_MS.set(limited, retryAfter);\n return limited;\n}\n\n/** Await `ms` milliseconds. Extracted so tests can stub the timer. */\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\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/** The query parameter / pushed field that names the sign-in provider (§12.1 \"`idp_hint`\", contract 1.65). */\nconst IDP_HINT_PARAM = 'axiam_idp_hint';\n\n/** The longest `idp_hint`, in UTF-8 bytes (§12.1 \"`idp_hint`\" rule 2). */\nconst IDP_HINT_MAX_BYTES = 256;\n\n/** The grant type of native sign-in with a provider ID token (CONTRACT.md §37). */\nexport const PROVIDER_ID_TOKEN_GRANT_TYPE = 'urn:axiam:params:oauth:grant-type:provider-id-token';\n\n/**\n * Refuse an `idp_hint` that is empty or over {@link IDP_HINT_MAX_BYTES} bytes\n * (§12.1 \"`idp_hint`\" rule 2) — and nothing else: no trimming, case-folding,\n * UUID parsing or lookup.\n */\nfunction checkIdpHint(operation: string, hint: string): void {\n if (hint === '') {\n throw new ValidationError(operation, 400, `${operation}: idpHint must not be empty (CONTRACT.md §12.1)`, [\n { field: 'idpHint', message: 'must not be empty' },\n ]);\n }\n if (Buffer.byteLength(hint, 'utf8') > IDP_HINT_MAX_BYTES) {\n throw new ValidationError(\n operation,\n 400,\n `${operation}: idpHint must be at most ${IDP_HINT_MAX_BYTES} bytes (CONTRACT.md §12.1)`,\n [{ field: 'idpHint', message: `must be at most ${IDP_HINT_MAX_BYTES} bytes` }],\n );\n }\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 */\n/** The non-empty `axiam_idp_hint` an `oidcBegin` URL carries, or `undefined` (D-N36). */\nfunction beginUrlIdpHint(url: string): string | undefined {\n try {\n const value = new URL(url).searchParams.get(IDP_HINT_PARAM);\n return value === null || value === '' ? undefined : value;\n } catch {\n return undefined;\n }\n}\n\n/**\n * §12.1 rule 3 / §37.2 rule 12 (C165-14): an `/oauth2/*` POST never follows a redirect — a 307/308\n * would re-send the form, and its credentials, to the `Location` target. The `3xx` is a\n * `NetworkError` that names the status only (no `Location`, no axios cause: its config holds the form).\n */\nfunction redirectRefused(operation: string, status: number): NetworkError {\n return new NetworkError(`${operation}: the server answered HTTP ${status}; a redirect is never followed (CONTRACT.md §12.1 rule 3)`);\n}\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 && status >= 300 && status < 400) {\n return redirectRefused(fallbackMessage, status);\n }\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 * Map an error from the **uma-ticket grant**, where `access_denied` arrives as\n * HTTP **403** (UMA 2.0 §3.3.6) rather than the 400 every other OAuth2 error\n * uses.\n *\n * @remarks\n * §20.4 requires dispatching on the `error` field rather than the status, so\n * that the code reaches the caller whichever status carries it. This is kept\n * local to the ticket grant on purpose: {@link mapHttpStatusToError}'s §2 rows\n * apply the OAuth2 mapping to 400/401 only, and widening that globally would\n * change how every OAuth2 endpoint's 403 is reported — a cross-cutting change\n * this grant does not need and did not ask for. An ordinary REST 403 keeps\n * mapping to `AuthzError`.\n */\nfunction mapUmaGrantError(err: unknown, url: string, fallbackMessage: string): AxiamError {\n if (err instanceof AxiamError) {\n return err;\n }\n const body = axiosBody(err);\n if (axiosStatus(err) === 403 && isOAuth2ErrorBody(body)) {\n return new OAuthProtocolError(body.error, body.error_description);\n }\n return mapOidcError(err, url, fallbackMessage);\n}\n\n/**\n * Refuse an `mtls_endpoint_aliases` entry that cannot carry a client\n * certificate (CONTRACT.md §21.3.1 vector C, contract 1.43).\n *\n * Falling back to the top-level endpoint looks like the safe answer and is the\n * dangerous one: the caller asked to authenticate with a certificate, the\n * operator published something unusable, and sending the certificate to the\n * front-channel host authenticates nothing while appearing to work.\n *\n * Two defects, each a refusal on its own:\n *\n * * **Not an absolute URL.** A relative alias resolves against nothing the\n * client holds, and the base that might seem obvious — the issuer's host —\n * is precisely the host the alias exists to name a different one from.\n * * **A scheme weaker than the endpoint it replaces.** An alias substitutes\n * for exactly one top-level endpoint, so that is what it is compared\n * against. `https` → `http` is a downgrade; `http` → `http` is a\n * development deployment, which AXIAM's own `build_mtls_aliases` supports\n * and this suite's harness is.\n *\n * @throws AuthError — not `NetworkError`, and the difference is not cosmetic.\n * Nothing failed in transport: the server published a document this client\n * cannot use, which is the same taxonomy as a document advertising no endpoint\n * at all (see `oidcDeviceAuthorize`). It also matters operationally, because\n * §16.3 retries `NetworkError` and only `NetworkError` — the other choice would\n * have attempted a permanent, deterministic misconfiguration three times and\n * reported it as a transient one.\n */\nexport function assertUsableMtlsAlias(alias: string, replaces: string | undefined): void {\n let parsed: URL;\n try {\n parsed = new URL(alias);\n } catch {\n throw new AuthError(\n `mtls_endpoint_aliases publishes ${JSON.stringify(alias)}, which is not an absolute URL. ` +\n 'Refusing rather than falling back to the top-level endpoint: this call presents a ' +\n 'client certificate, and sending it to the front-channel host would authenticate ' +\n 'nothing while appearing to work.',\n );\n }\n let replacedIsTls = false;\n if (replaces !== undefined) {\n try {\n replacedIsTls = new URL(replaces).protocol === 'https:';\n } catch {\n replacedIsTls = false;\n }\n }\n if (replacedIsTls && parsed.protocol !== 'https:') {\n throw new AuthError(\n `mtls_endpoint_aliases publishes ${JSON.stringify(alias)}, whose scheme is ` +\n `${JSON.stringify(parsed.protocol)}, in place of an https endpoint. That is a ` +\n 'downgrade, and mutual TLS over cleartext is a contradiction; refusing rather than ' +\n 'falling back to the top-level endpoint.',\n );\n }\n}\n\n// ---------------------------------------------------------------------------\n// §33 CIBA — module-level definitions (contract 1.58)\n// ---------------------------------------------------------------------------\n\n/** `grant_type` of the CIBA token request (CIBA Core §10.1). */\nexport const CIBA_GRANT_TYPE = 'urn:openid:params:grant-type:ciba';\n\n/** The interval used when the initiate response carries none (§33.7 rule 2). */\nexport const DEFAULT_CIBA_INTERVAL_SECS = 5;\n\n/** Seconds added to the interval per `slow_down`, permanently and cumulatively (§33.7 rule 3). */\nexport const CIBA_SLOW_DOWN_INCREMENT_SECS = 5;\n\n/** The lifetime of a signed request this SDK mints: five minutes, inside the server's sixty-minute bound on `exp − nbf` (§33.2). */\nexport const SIGNED_REQUEST_LIFETIME_SECS = 300;\n\nconst CIBA_SIGNING_ALGS: ReadonlySet<string> = new Set(['PS256', 'ES256', 'EdDSA']);\n\n/**\n * The `NetworkError`s `cibaAwait` may wait out (§33.7 rule 5): a transport\n * failure, or a `408` / `429` / `5xx` that survived §16's retries inside\n * `cibaPoll`. A bodiless `400` is a `NetworkError` too (§2), but a decisive\n * one, and is not in here.\n */\nconst TRANSIENT_POLL_FAILURES = new WeakSet<NetworkError>();\n\nfunction transient(error: NetworkError): NetworkError {\n TRANSIENT_POLL_FAILURES.add(error);\n return error;\n}\n\n/** The real clock: `Date.now` and `setTimeout`. */\nconst SYSTEM_CIBA_CLOCK: CibaClock = { now: () => Date.now(), sleep };\n\n/** The deadline a polling loop hands the poll under it: a clock instant and the clock it is read on. */\ninterface PollDeadline {\n deadline: number;\n clock: CibaClock;\n}\n\n/**\n * The §16 retry of a poll inside a loop's deadline (§14.2 rule 4, §34.2 P10; C164-36): `admit`\n * refuses a wait — the jittered backoff floored at `Retry-After`, as `withRetry` computed it —\n * that would reach the deadline, before the retry is announced to telemetry or sent, by raising\n * the typed `expired_token`; `sleepFn` serves an admitted wait on the loop's clock.\n */\nfunction deadlineBoundedRetry(\n bound: PollDeadline,\n what: string,\n): { admit: (ms: number) => void; sleepFn: (ms: number) => Promise<void> } {\n return {\n admit: (ms) => {\n if (bound.clock.now() + ms >= bound.deadline) {\n throw new OAuthProtocolError(\n 'expired_token',\n `the ${what} expired before it was decided (client-side deadline from expires_in; CONTRACT.md §14.2 rule 4, §34.2 P10)`,\n );\n }\n },\n sleepFn: (ms) => bound.clock.sleep(ms),\n };\n}\n\n/**\n * Whether `err` is the `access_denied` answer — at a CIBA (or device) poll,\n * the user refused (§33.4). Distinct from {@link isExpiredToken}.\n */\nexport function isAccessDenied(err: unknown): err is OAuthProtocolError {\n return err instanceof OAuthProtocolError && err.error === 'access_denied';\n}\n\n/**\n * Whether `err` is the `expired_token` answer — nobody decided in time. Raised\n * by the server, and locally by `cibaAwait` when it reaches the request's\n * deadline (§33.4, §33.7 rule 4).\n */\nexport function isExpiredToken(err: unknown): err is OAuthProtocolError {\n return err instanceof OAuthProtocolError && err.error === 'expired_token';\n}\n\nfunction cibaRefusal(operation: string, field: string, message: string): ValidationError {\n return new ValidationError(operation, 400, `${operation}: ${field}: ${message} (CONTRACT.md §33)`, [\n { field, message },\n ]);\n}\n\n/** What a {@link CibaRequestSigner} renders as: the algorithm and `kid`, never the key. */\nexport interface CibaSignerDescription {\n /** The algorithm the signer signs under. */\n alg: CibaSigningAlg;\n /** The `kid` it puts in the JWS header, if any. */\n kid?: string;\n}\n\n/** The signing key a {@link CibaRequestSigner} accepts: a PKCS#8 PEM, or a private `KeyObject` / `CryptoKey`. */\nexport type CibaSigningKey = Sensitive<string> | KeyObject | CryptoKey;\n\nconst NODE_INSPECT_CUSTOM = Symbol.for('nodejs.util.inspect.custom');\n\n/**\n * The key and algorithm for CIBA's signed request form (§33.2, CIBA Core\n * §7.1.1). Both are the caller's: there is no default for either, and the SDK\n * signs under exactly the algorithm given — the one the client registered as\n * `backchannel_authentication_request_signing_alg`.\n *\n * @remarks\n * Signing uses `jose` (PS256, ES256 and EdDSA). The key is held privately and\n * appears in no rendering: `String()`, `JSON.stringify` and `util.inspect` show\n * the algorithm and `kid` only.\n */\nexport class CibaRequestSigner {\n readonly #alg: CibaSigningAlg;\n readonly #key: Sensitive<KeyObject | CryptoKey>;\n readonly #kid: string | undefined;\n\n private constructor(alg: CibaSigningAlg, key: KeyObject | CryptoKey, kid: string | undefined) {\n this.#alg = alg;\n this.#key = new Sensitive(key);\n this.#kid = kid;\n }\n\n /**\n * A signer from a private key and the algorithm it signs under.\n *\n * @param alg `PS256`, `ES256` or `EdDSA` — required, never defaulted.\n * @param key a PKCS#8 PEM (wrapped in `Sensitive`), or a private `KeyObject` / `CryptoKey`.\n * @param kid the `kid` to put in the JWS header, if the client's JWKS names one.\n * @throws ValidationError (local, before any request) when `alg` is not one\n * of the three, or the key is empty, not a private key, or one that cannot\n * sign under `alg` — proved by signing a probe.\n */\n static async create(alg: CibaSigningAlg, key: CibaSigningKey, kid?: string): Promise<CibaRequestSigner> {\n const refuse = (): ValidationError =>\n cibaRefusal(\n 'ciba_initiate',\n 'signing_key',\n 'the key is not a private key that signs under the given algorithm (PS256, ES256 or EdDSA)',\n );\n if (!CIBA_SIGNING_ALGS.has(alg)) throw refuse();\n const jose = await import('jose');\n let material: KeyObject | CryptoKey;\n try {\n if (key instanceof Sensitive) {\n const pem = key.expose();\n if (typeof pem !== 'string' || pem.trim() === '') throw new Error('empty');\n material = (await jose.importPKCS8(pem, alg)) as KeyObject | CryptoKey;\n } else if (key && typeof key === 'object') {\n material = key;\n } else {\n throw new Error('no key');\n }\n // A key that parses is not yet a key for this algorithm: prove it signs.\n await new jose.SignJWT({ probe: true }).setProtectedHeader({ alg }).sign(material);\n } catch {\n throw refuse();\n }\n return new CibaRequestSigner(alg, material, kid);\n }\n\n /** The algorithm this signer uses. */\n get alg(): CibaSigningAlg {\n return this.#alg;\n }\n\n /** The `kid` it puts in the header, if any. */\n get kid(): string | undefined {\n return this.#kid;\n }\n\n /** @internal — sign `claims` as a compact JWS under this signer's algorithm. */\n async sign(claims: Record<string, unknown>): Promise<Sensitive<string>> {\n const jose = await import('jose');\n const header: { alg: string; kid?: string } = { alg: this.#alg };\n if (this.#kid !== undefined) header.kid = this.#kid;\n return new Sensitive(await new jose.SignJWT(claims).setProtectedHeader(header).sign(this.#key.expose()));\n }\n\n /** `CibaRequestSigner(<alg>)` — never the key. */\n toString(): string {\n return `CibaRequestSigner(${this.#alg})`;\n }\n\n /** `{ alg, kid }` — never the key. */\n toJSON(): CibaSignerDescription {\n return { alg: this.#alg, ...(this.#kid !== undefined ? { kid: this.#kid } : {}) };\n }\n\n /** The same as {@link toJSON}, for `console.log` / `util.inspect`. */\n [NODE_INSPECT_CUSTOM](): string {\n return `CibaRequestSigner ${JSON.stringify(this.toJSON())}`;\n }\n}\n\n/** The plain form's authentication-request members, exactly those set (§33.2). */\nfunction cibaMembers(params: CibaInitiateParams): Array<[string, string]> {\n const out: Array<[string, string]> = [['scope', params.scope]];\n if (params.loginHint !== undefined) out.push(['login_hint', params.loginHint]);\n if (params.idTokenHint !== undefined) out.push(['id_token_hint', params.idTokenHint]);\n if (params.bindingMessage !== undefined) out.push(['binding_message', params.bindingMessage]);\n if (params.requestedExpiry !== undefined) out.push(['requested_expiry', String(params.requestedExpiry)]);\n if (params.acrValues !== undefined) out.push(['acr_values', params.acrValues]);\n if (params.resource !== undefined) out.push(['resource', params.resource]);\n if (params.delivery?.mode === 'ping') {\n out.push(['client_notification_token', params.delivery.clientNotificationToken.expose()]);\n }\n return out;\n}\n\n/** Parse a response body axios left as text; `undefined` when it is not JSON. */\nfunction jsonBody(data: unknown): unknown {\n if (typeof data !== 'string') return data;\n try {\n return JSON.parse(data);\n } catch {\n return undefined;\n }\n}\n\n/** Map a non-2xx `/oauth2/*` answer: `error` at any status is an `OAuthProtocolError` (§33.4); otherwise §2. */\nfunction cibaError(operation: string, response: AxiosResponse): AxiamError {\n if (response.status >= 300 && response.status < 400) return redirectRefused(operation, response.status);\n return (\n oauth2ErrorFromBody(jsonBody(response.data), response.status === 429 ? retryAfterMs(response) : undefined) ??\n mapHttpStatusToError(response.status, `${operation}: HTTP ${response.status}`)\n );\n}\n\n/** The `Authorization` header values of a ping, in any accepted header shape. */\nfunction authorizationValues(headers: CibaPingHeaders): string[] {\n const out: string[] = [];\n const isAuth = (name: unknown): boolean => typeof name === 'string' && name.toLowerCase() === 'authorization';\n if (Array.isArray(headers) && headers.every((h) => typeof h === 'string')) {\n // Node's rawHeaders: [name, value, name, value, …].\n const flat = headers as readonly string[];\n for (let i = 0; i + 1 < flat.length; i += 2) if (isAuth(flat[i])) out.push(flat[i + 1]!);\n return out;\n }\n if (headers !== null && typeof headers === 'object' && Symbol.iterator in headers) {\n for (const entry of headers as Iterable<readonly [string, string]>) {\n if (Array.isArray(entry) && isAuth(entry[0])) out.push(String(entry[1]));\n }\n return out;\n }\n for (const [name, value] of Object.entries(headers as Record<string, string | readonly string[] | undefined>)) {\n if (!isAuth(name) || value === undefined) continue;\n if (Array.isArray(value)) out.push(...(value as readonly string[]).map(String));\n else out.push(String(value));\n }\n return out;\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 and, when\n * `idpHint` is set, the one `axiam_idp_hint` (contract 1.65).\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 * @throws ValidationError when `idpHint` is empty or over 256 UTF-8 bytes;\n * no URL is built.\n */\n oidcBegin(params: OidcBeginParams): AuthorizationRequest {\n if (params.idpHint !== undefined) checkIdpHint('oidcBegin', params.idpHint);\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 // §12.1 \"`idp_hint`\" rule 3: the input is the single source. A same-named\n // extra is dropped when it is set, and passes through (once) when it is not.\n if (key === IDP_HINT_PARAM && params.idpHint !== undefined) continue;\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 if (params.idpHint !== undefined) query.set(IDP_HINT_PARAM, params.idpHint);\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 // §37 loginWithProviderIdToken\n // -------------------------------------------------------------------------\n\n /**\n * `POST /oauth2/token` with\n * `grant_type=urn:axiam:params:oauth:grant-type:provider-id-token`\n * (CONTRACT.md §37, contract 1.65) — sign a native-app user in with the ID\n * token a Google, Apple or Facebook Limited Login SDK produced.\n *\n * @param provider - The provider's UUID or its `provider_slug`, sent verbatim:\n * never trimmed, case-folded, resolved or looked up. A provider *kind* name\n * (`google`) is not accepted here unless the operator also chose it as the\n * slug (§37.2 rule 2).\n * @param idToken - The provider's ID token (a credential; wrapped or bare).\n * @param nonce - The **raw** nonce, byte for byte: the provider's SDK was\n * given `SHA-256(raw)` as hexadecimal (`nativeNonce()` produces the\n * pair). Never hashed, replaced or generated here (§37.2 rule 3).\n * @param options - `scopes`, `resource`, `tenantId`, `configuration`.\n *\n * @remarks\n * **Never retried** — not on a status, a `429` or a transport failure: the\n * provider's token is single-use across the deployment (§37.2 rule 10). An\n * `invalid_grant` is the server's one generic answer to every refusal of the\n * token and is neither retried nor refined; the recovery is a **fresh**\n * provider token with a **fresh** nonce. A transport failure after the\n * request left is indeterminate and surfaces as `NetworkError`.\n *\n * No `openid` or other scope is added: omit `scopes` and the response carries\n * no `id_token`. This is not token exchange (§15) and never falls back to it\n * or to a browser flow. A public client sends `client_id` alone; a client\n * configured with a `clientSecret` sends it in the body.\n *\n * The result is the ordinary {@link OidcTokenSet}; an `id_token`, when\n * present, is validated under §12.4 with the raw `nonce` as the expected\n * nonce. As with `deviceLogin`, the token set is **returned and not\n * adopted** as this client's credential (§37.2 rule 9).\n *\n * Neither the ID token nor the raw nonce is logged, put in an error, or kept\n * after the call returns; hold the raw nonce only for the length of the\n * attempt.\n *\n * @throws ValidationError (local, no request) for an empty `provider`,\n * `idToken` or `nonce`.\n * @throws AuthError (local, no request) for a slug-only client (§12.3 rule 4).\n * @throws OAuthProtocolError for a body carrying `error`, at any status.\n * @throws NetworkError for a transport failure or a body-less `5xx`.\n *\n * @example\n * ```ts\n * const { raw, hashed } = nativeNonce();\n * const idToken = await providerSdk.signIn({ nonce: hashed });\n * const tokens = await oidc.loginWithProviderIdToken('corp-google', idToken, raw, {\n * scopes: ['openid', 'profile'],\n * });\n * ```\n */\n async loginWithProviderIdToken(\n provider: string,\n idToken: Sensitive<string> | string,\n nonce: Sensitive<string> | string,\n options: LoginWithProviderIdTokenOptions = {},\n ): Promise<OidcTokenSet> {\n const operation = 'loginWithProviderIdToken';\n const refuse = (field: string): ValidationError =>\n new ValidationError(operation, 400, `${operation}: ${field} must not be empty (CONTRACT.md §37.2 rule 4)`, [\n { field, message: 'must not be empty' },\n ]);\n const idTokenValue = typeof idToken === 'string' ? idToken : idToken.expose();\n const nonceValue = typeof nonce === 'string' ? nonce : nonce.expose();\n if (provider === '') throw refuse('provider');\n if (idTokenValue === '') throw refuse('idToken');\n if (nonceValue === '') throw refuse('nonce');\n // §37.1: a slug-only client is refused before any wire call — discovery included.\n this.#resolveTenantId(options.tenantId);\n\n const configuration = options.configuration ?? (await this.oidcDiscover());\n const form = new URLSearchParams();\n form.set('grant_type', PROVIDER_ID_TOKEN_GRANT_TYPE);\n form.set('client_id', this.#options.clientId);\n form.set('provider', provider);\n form.set('id_token', idTokenValue);\n form.set('nonce', nonceValue);\n // §37.2 rule 7: only what the caller named — no `openid`, never an empty `scope=`.\n if (options.scopes !== undefined && options.scopes.length > 0) {\n form.set('scope', options.scopes.join(' '));\n }\n if (options.resource !== undefined) {\n form.set('resource', options.resource);\n }\n this.#appendClientSecret(form);\n\n const url = this.#endpointUrl(this.#requiredEndpoint(configuration, 'token_endpoint'), options.tenantId);\n // One request, every status resolved so the `error` member decides (§37.3), and a\n // transport failure carrying no axios cause (its `config` holds this form).\n const response = await this.#postCibaForm(url, form, operation);\n if (response.status < 200 || response.status >= 300) {\n throw cibaError(operation, response);\n }\n // §12.4 with the RAW nonce (§37.2 rule 8): AXIAM's ID token carries it as sent.\n return this.#toTokenSet(response.data as TokenResponseWire, configuration, nonceValue);\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(this.#requiredEndpoint(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(this.#requiredEndpoint(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 this.#forgetPreviousPrincipal();\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 // 10. ssoProviders (contract 1.38)\n // -------------------------------------------------------------------------\n\n /**\n * `GET /api/v1/auth/federation/providers` (§12.1) — which \"Sign in with X\"\n * buttons to render for a workspace.\n *\n * @remarks\n * The identifiers travel as **query** parameters; this is a `GET` and sends\n * no body. The neighbouring start operations take the same four in a JSON\n * body, and the two are one copy-paste apart, which is why there is a test\n * asserting the location.\n *\n * **An empty list is a success.** An unknown organization, a known one with\n * nothing configured, and a request naming no workspace at all all answer\n * `200` with an empty `providers` array (§12.1 note 9). This method returns\n * every one of them as an ordinary result and synthesises no not-found: the\n * endpoint is deliberately shaped so it cannot be used to enumerate\n * organization or tenant slugs, and an SDK that reintroduced the\n * distinction would reintroduce the oracle. A caller learns it named the\n * workspace wrongly at the start operations, where every failure is a\n * uniform `401`.\n *\n * For the same reason this does **not** refuse client-side when no\n * organization resolves, unlike {@link ssoStart} and\n * {@link ssoStartOauth2}, which do.\n */\n async ssoProviders(params: SsoProvidersParams = {}): Promise<FederationProviderList> {\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 const query = new URLSearchParams();\n if (orgId) {\n query.set('org_id', orgId);\n } else if (orgSlug) {\n query.set('org_slug', orgSlug);\n }\n if (tenantId) {\n query.set('tenant_id', tenantId);\n } else if (tenantSlug) {\n query.set('tenant_slug', tenantSlug);\n }\n\n const search = query.toString();\n const url = search ? `${SSO_PROVIDERS_PATH}?${search}` : SSO_PROVIDERS_PATH;\n let response: AxiosResponse<PublicFederationProvidersResponseWire>;\n try {\n response = await this.#session.axios.get<PublicFederationProvidersResponseWire>(url);\n } catch (err) {\n throw mapOidcError(err, url, 'ssoProviders request failed');\n }\n\n return {\n providers: (response.data.providers ?? []).map(\n (wire): FederationProvider => ({\n id: wire.id,\n providerKind: wire.provider_kind,\n displayName: wire.display_name,\n protocol: wire.protocol,\n hasBundledMark: wire.has_bundled_mark,\n inherited: wire.inherited,\n ...(wire.button_icon ? { buttonIcon: wire.button_icon } : {}),\n }),\n ),\n };\n }\n\n // -------------------------------------------------------------------------\n // 11. ssoStartOauth2 (contract 1.38)\n // -------------------------------------------------------------------------\n\n /**\n * `POST /api/v1/auth/federation/oauth2/start` (§12.1) — step 1 of a login\n * through a **plain-OAuth2** upstream (GitHub, Facebook, `generic_oauth2`).\n *\n * @remarks\n * Call this, rather than {@link ssoStart}, exactly when the provider's\n * `protocol` is `OAuth2` (§12.1 note 10). The server refuses a mismatch\n * with `400` rather than accepting it silently, so a client that assumes\n * OIDC fails on every GitHub button.\n *\n * PKCE is mandatory on this path — it is the only replay protection left\n * once there is no `nonce` — and is generated and stored **server-side**.\n * Nothing about it appears in this request or its response (§12.1 note 11),\n * and this method computes no verifier.\n *\n * @throws AuthError client-side, without a wire call, when tenant or org\n * context cannot be resolved. On the wire, a **`400`** can mean the\n * `redirectUri` is not on an origin the deployment accepts (§12.1 rule\n * 12a) and surfaces as `NetworkError` — §2's `400` row, this taxonomy's\n * configuration/programming-error member, as distinct from the\n * `AuthError` a `401` gets. It is not retried; the same origin will be\n * refused again.\n */\n async ssoStartOauth2(params: SsoStartOauth2Params): 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 'ssoStartOauth2 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 'ssoStartOauth2 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 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<OAuth2StartResponseWire>(\n SSO_OAUTH2_START_PATH,\n body,\n 'ssoStartOauth2 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 // 12. ssoCompleteOauth2 (contract 1.38)\n // -------------------------------------------------------------------------\n\n /**\n * `POST /api/v1/auth/federation/oauth2/callback` (§12.1) — step 2 of a\n * plain-OAuth2 login.\n *\n * @remarks\n * The session arrives as **`Set-Cookie`** (§12.1 note 6), so this call must\n * go through the §4 cookie jar exactly as {@link ssoComplete} must.\n *\n * §12.4 does not apply: an `OAuth2` provider issues no ID token, so there\n * is nothing to validate. The server authenticated the user by calling a\n * configured userinfo endpoint with the access token it had just received —\n * configuration and transport trust rather than cryptographic trust (§12.1\n * note 11).\n */\n async ssoCompleteOauth2(params: SsoCompleteOauth2Params): Promise<SsoCompleteResult> {\n return this.#completeFederationSession(\n SSO_OAUTH2_CALLBACK_PATH,\n { state: params.state, code: params.code },\n 'ssoCompleteOauth2 request failed',\n );\n }\n\n // -------------------------------------------------------------------------\n // 13. ssoCompleteHandoff (contract 1.38)\n // -------------------------------------------------------------------------\n\n /**\n * `POST /api/v1/auth/federation/handoff` (§12.1) — redeem the single-use\n * code the SAML and Apple flows deliver.\n *\n * @remarks\n * Those two protocols return **cross-site**, so the server cannot set\n * `SameSite=Strict` session cookies on that response. It instead redirects\n * the browser to the SPA's callback URL with an `axiam_handoff` query\n * parameter ({@link HANDOFF_QUERY_PARAM}); this call posts that code back\n * same-origin, and *this* response is the one carrying the cookies (§12.1\n * note 12).\n *\n * **The code is gone either way.** It is valid for\n * {@link HANDOFF_CODE_TTL_SECS} seconds and redeemable **once**. Redeem it\n * from the same origin, immediately, and never retry a failed redemption: a\n * `401` is terminal, and this method makes exactly one wire call so that it\n * cannot become a retry by accident. Unknown, expired and already-redeemed\n * all answer the same `401`, deliberately — telling them apart is not\n * something a caller gets to do.\n */\n async ssoCompleteHandoff(params: SsoCompleteHandoffParams): Promise<SsoCompleteResult> {\n return this.#completeFederationSession(\n SSO_HANDOFF_PATH,\n { code: params.code },\n 'ssoCompleteHandoff request failed',\n );\n }\n\n // -------------------------------------------------------------------------\n // §14 Device Authorization Grant (RFC 8628)\n // -------------------------------------------------------------------------\n\n /**\n * `POST /oauth2/device_authorization` (CONTRACT.md §14.1) — start the grant\n * and obtain the code pair.\n *\n * @remarks\n * **The client authenticates as it does at every other token request\n * (contract 1.62, §14.1 rule 2).** A client built with a `clientSecret` sends\n * it as `client_secret` in the **form body** — never as `Authorization:\n * Basic`, whatever the client is registered for (§12.1 rule 3 stands for\n * this route, and the maintainer's 2026-10-16 \"same rules\" reading fixes the\n * form body) — and a client with a §6.1 client certificate presents it on the\n * connection, through the `mtls_endpoint_aliases` entry when discovery\n * publishes one (§21.3). **A public client sends no credential at all** and\n * is never refused client-side, so a device that cannot hold a secret still\n * works. The SDK sends a credential only when its caller configured one: it\n * never borrows one from another configuration. `private_key_jwt` client\n * authentication is not implemented by this SDK.\n *\n * A `401` with `{\"error\":\"invalid_client\"}` is an {@link OAuthProtocolError}\n * (§14.2 rule 5), is made once, and does not enter the §9 refresh guard.\n */\n async deviceAuthorize(params: DeviceAuthorizeParams = {}): Promise<DeviceAuthorization> {\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const endpoint = this.#optionalEndpoint(configuration, 'device_authorization_endpoint');\n if (!endpoint) {\n throw new AuthError(\n \"the authorization server's discovery document advertises no \" +\n 'device_authorization_endpoint: this server does not support the device grant ' +\n '(CONTRACT.md §14.1)',\n );\n }\n\n const form = new URLSearchParams();\n form.set('client_id', this.#options.clientId);\n // §14.1 rule 2: a configured secret rides in the form body; a public\n // client's form carries none.\n this.#appendClientSecret(form);\n if (params.scope !== undefined) {\n form.set('scope', Array.isArray(params.scope) ? params.scope.join(' ') : params.scope);\n }\n\n const url = this.#endpointUrl(endpoint, params.tenantId);\n const { data } = await this.#postForm<DeviceAuthorizationResponseWire>(\n url,\n form,\n 'device authorization request failed',\n );\n\n return {\n deviceCode: new Sensitive(data.device_code),\n userCode: data.user_code,\n verificationUri: data.verification_uri,\n ...(data.verification_uri_complete != null\n ? { verificationUriComplete: data.verification_uri_complete }\n : {}),\n expiresIn: data.expires_in,\n // §14.2 rule 2: the interval comes from the response; only its absence\n // falls back to the RFC default. A server-sent 0 is treated as absent —\n // polling with no delay is never what the server meant.\n interval: data.interval != null && data.interval > 0 ? data.interval : DEFAULT_POLL_INTERVAL_SECS,\n };\n }\n\n // -------------------------------------------------------------------------\n // §26 Pushed Authorization Requests (RFC 9126)\n // -------------------------------------------------------------------------\n\n /**\n * `POST /oauth2/par` (CONTRACT.md §26.1) — push the authorization request\n * over the back channel and get an opaque handle to redirect with.\n *\n * @remarks\n * PAR moves the authorization request off the browser. Instead of putting\n * `scope`, `redirect_uri`, `state` and the PKCE challenge into a URL the user\n * agent carries, the client POSTs them straight to AXIAM over an\n * authenticated channel and puts an opaque `request_uri` in the redirect.\n * What travels through the browser is then a random string that cannot be\n * edited into meaning something else.\n *\n * **Required for a FAPI 2.0 client** — `profile: \"fapi2\"` refuses a\n * registration that does not set `require_par`, so such a client cannot\n * authorize any other way (§21.1).\n *\n * This is a §12 extension, not a replacement: `oidcExchange` afterwards is\n * unchanged, and carries the same `codeVerifier` and `redirectUri`\n * ({@link PushedAuthorizationRequest.codeVerifier} is the one `oidcBegin`\n * produced — §26.2 rule 6).\n *\n * @example\n * ```ts\n * const configuration = await oidc.oidcDiscover();\n * const begun = oidc.oidcBegin({ configuration, redirectUri, scope: 'openid profile' });\n * const pushed = await oidc.oidcPar({ request: begun, redirectUri, scope: 'openid profile' });\n *\n * redirect(pushed.authorizationUrl); // client_id + request_uri, nothing else\n * // …later, on the callback:\n * const tokens = await oidc.oidcExchange({\n * code, redirectUri, nonce: pushed.nonce, codeVerifier: pushed.codeVerifier,\n * });\n * ```\n */\n async oidcPar(params: OidcParParams): Promise<PushedAuthorizationRequest> {\n if (params.idpHint !== undefined) checkIdpHint('oidcPar', params.idpHint);\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const endpoint = this.#optionalEndpoint(configuration, 'pushed_authorization_request_endpoint');\n if (!endpoint) {\n throw new AuthError(\n \"the authorization server's discovery document advertises no \" +\n 'pushed_authorization_request_endpoint: this server does not support RFC 9126 ' +\n '(CONTRACT.md §26.1)',\n );\n }\n\n // §26.2 rule 1: everything below was computed by `oidcBegin`. There is no\n // second generator here, and there must not be — two sources for `state`\n // or the PKCE pair are two things that can disagree.\n const request = params.request;\n const form = new URLSearchParams();\n form.set('client_id', this.#options.clientId);\n form.set('response_type', 'code');\n form.set('redirect_uri', params.redirectUri);\n form.set('scope', normalizeScope(params.scope));\n form.set('state', request.state);\n form.set('nonce', request.nonce);\n form.set('code_challenge', computeCodeChallenge(exposeSecret(request.codeVerifier)));\n form.set('code_challenge_method', CODE_CHALLENGE_METHOD_S256);\n // RFC 9449 §10.1 — bind the authorization code to the client's DPoP key at\n // authorization time rather than only at the token request, so a stolen\n // code cannot be redeemed with a different key. Caller-supplied: this SDK\n // verifies proofs (§21.7.2) but generates none, so it holds no key whose\n // thumbprint it could compute. Emitted only when set — §12.1 forbids\n // sending an empty value for an absent optional field.\n if (params.dpopJkt !== undefined) {\n form.set('dpop_jkt', params.dpopJkt);\n }\n // §26.2 rule 8 (contract 1.65): the provider hint rides the pushed body, once,\n // and only when set. It is never added to the redirect URL built below.\n // D-N36 (C165-11): when the argument is unset, the hint the begin URL carries is pushed;\n // the argument wins when both are set. Never twice, never a second source.\n const pushedHint = params.idpHint ?? beginUrlIdpHint(request.url);\n if (pushedHint !== undefined) {\n checkIdpHint('oidcPar', pushedHint);\n form.set(IDP_HINT_PARAM, pushedHint);\n }\n // NOT pushed, and never to be added: `request_uri`. RFC 9126 §2.1 makes it\n // the one authorization parameter a client MUST NOT push, and openapi.json\n // models it on the request schema only so the server can refuse it. A\n // client able to send it is a client able to chain one pushed request into\n // another, which is the attack the refusal exists to stop.\n this.#appendClientSecret(form);\n\n const url = this.#endpointUrl(endpoint, params.tenantId);\n // Deliberately NOT routed through the §16 retry helper: this is a POST that\n // creates server state, so it falls outside §16.2's read-only eligibility\n // exactly as `oidcExchange` does. The safe recovery from a transport\n // failure is a fresh push, which costs one round trip and cannot\n // double-consume anything (§26.2 rule 4).\n const { data } = await this.#postForm<PushedAuthorizationResponseWire>(\n url,\n form,\n 'pushed authorization request failed',\n );\n\n // §26.2 rule 2: exactly two query parameters. Not `response_type`, not\n // `redirect_uri`, not `scope`, not `state`, not the PKCE pair — the server\n // REFUSES a request carrying both a `request_uri` and any inline\n // authorization parameter rather than merging them, because merging is\n // where parameter confusion lives: an attacker supplies the inline value\n // they want and lets the pushed copy satisfy whichever check reads the\n // other one. Re-adding them \"for compatibility\" restores the attack.\n const target = new URL(configuration.authorization_endpoint);\n const query = new URLSearchParams();\n query.set('client_id', this.#options.clientId);\n query.set('request_uri', data.request_uri);\n target.search = query.toString().replace(/\\+/g, '%20');\n\n return {\n authorizationUrl: target.toString(),\n requestUri: new Sensitive(data.request_uri),\n expiresIn: data.expires_in,\n state: request.state,\n nonce: request.nonce,\n codeVerifier: request.codeVerifier,\n };\n }\n\n /**\n * `POST /oauth2/token` with the device-code grant (CONTRACT.md §14.1) —\n * **one** poll attempt.\n *\n * @remarks\n * The raw single call, so an application driving its own loop (a UI\n * rendering a countdown, say) can. The five RFC 8628 §3.5 answers surface as\n * {@link OAuthProtocolError} — `authorization_pending` and `slow_down`\n * included — so a hand-rolled loop dispatches on the same answers\n * {@link deviceLogin} does. Most callers want {@link deviceLogin}.\n *\n * Client authentication is the one {@link deviceAuthorize} describes\n * (contract 1.62, §14.1 rule 2): a configured `clientSecret` is sent as\n * `client_secret` in the form body, never as `Authorization: Basic`; a public\n * client sends none; `client_id` is sent on **every** poll (§14.1 rule 3). A\n * `401 invalid_client` surfaces as {@link OAuthProtocolError}, is not retried\n * and does not enter the §9 refresh guard (§14.2 rule 5). Any `429`\n * is an {@link OAuthProtocolError} with `error == 'rate_limit_exceeded'` too\n * (rule 9, whatever its body names) — never `slow_down`; {@link deviceLogin}\n * waits it out. Its `Retry-After` is not exposed, so a hand-rolled loop\n * should wait at least one interval on it without raising the interval, or\n * use {@link deviceLogin}. This SDK ships no\n * DPoP proof generator, so it cannot drive a client registered for DPoP; it\n * surfaces that client's refusal as the same `invalid_client`.\n */\n async devicePoll(params: DevicePollParams): Promise<OidcTokenSet> {\n return this.#devicePoll(params, undefined);\n }\n\n /** {@link devicePoll}; `bound` is the loop's deadline, which a §16 retry inside the poll must not pass. */\n async #devicePoll(params: DevicePollParams, bound: PollDeadline | undefined): Promise<OidcTokenSet> {\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const form = new URLSearchParams();\n form.set('grant_type', DEVICE_CODE_GRANT_TYPE);\n form.set('device_code', exposeSecret(params.deviceCode));\n form.set('client_id', this.#options.clientId);\n // §14.1 rule 2, as at deviceAuthorize and every other token request.\n this.#appendClientSecret(form);\n\n const url = this.#endpointUrl(this.#requiredEndpoint(configuration, 'token_endpoint'), params.tenantId);\n const wire = await this.#postDevicePoll(url, form, bound);\n // No nonce: the device grant has no authorization request to carry one,\n // and §12.4 rule 6 applies to the authorization-code flow.\n return this.#toTokenSet(wire, configuration, undefined);\n }\n\n /**\n * The composed §14.3 helper: start the grant, hand the caller the user code,\n * poll to completion.\n *\n * @remarks\n * `onUserCode` is awaited **before the first poll** — §14.3 rule 2 requires\n * the caller to have had the chance to display the code before polling\n * begins. The SDK never prints it.\n *\n * Per §14.3 rule 4 (contract 1.7 errata) this SDK **returns** the token set;\n * whether it is adopted is the same MAY as `loginClientCredentials`.\n *\n * Polling follows §14.2: the interval comes from the response; `slow_down`\n * adds 5 s **permanently**; `authorization_pending` loops; `access_denied`\n * and `expired_token` raise distinct errors; polling stops at `expires_in`\n * even if the server has not yet said `expired_token`. A 5xx or transport\n * failure mid-poll is **not** terminal (rule 6) — the loop absorbs it and\n * tries again, bounded by the same deadline, because a server restart must\n * not lose a grant the user has already approved: that bound holds for the\n * §16 retry inside a poll too, whose waits are served on the loop's clock and\n * never reach the deadline (`Retry-After` included; the typed `expired_token`\n * is raised at once, C164-36). A `429\n * rate_limit_exceeded` (rule 9, contract 1.64) is not terminal either: the\n * loop waits `Retry-After` as a minimum (capped at the `expires_in`\n * deadline), counts the wait as one interval, does **not** raise the\n * interval, and polls again.\n */\n async deviceLogin(params: DeviceLoginParams): Promise<OidcTokenSet> {\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const clock = params.clock ?? SYSTEM_CIBA_CLOCK;\n const authorization = await this.deviceAuthorize({\n ...(params.scope !== undefined ? { scope: params.scope } : {}),\n ...(params.tenantId !== undefined ? { tenantId: params.tenantId } : {}),\n configuration,\n });\n // §14.2 rule 4 (C164-05): the deadline is a point on the clock, taken when the\n // authorization arrives, so the time `onUserCode` and every poll take count\n // against it and not only the sleeps do.\n const deadline = clock.now() + authorization.expiresIn * 1000;\n\n // §14.3 rule 2 — before any polling.\n await params.onUserCode(authorization);\n\n const schedule = new PollSchedule(authorization.interval, authorization.expiresIn);\n\n for (;;) {\n // Read before `tick()`, which serves a pending `Retry-After`.\n const waitSecs = schedule.waitSecs;\n // §14.2 rule 4: the deadline is authoritative. Checking before sleeping\n // keeps the SDK from issuing a request that can only be refused, and\n // reports it under the same `expired_token` code the server would have\n // used — so a caller's branch does not care which side noticed first.\n if (!schedule.tick() || clock.now() + waitSecs * 1000 >= deadline) {\n throw new OAuthProtocolError(\n 'expired_token',\n 'the device authorization expired before the user completed it ' +\n '(client-side deadline from expires_in; CONTRACT.md §14.2 rule 4)',\n );\n }\n\n await clock.sleep(waitSecs * 1000);\n\n try {\n return await this.#devicePoll(\n {\n deviceCode: authorization.deviceCode,\n ...(params.tenantId !== undefined ? { tenantId: params.tenantId } : {}),\n configuration,\n },\n { deadline, clock },\n );\n } catch (err) {\n if (err instanceof OAuthProtocolError) {\n if (err.error === 'authorization_pending') {\n continue;\n }\n if (err.error === 'slow_down') {\n // Only the `400` gets here: a `429` is `rate_limit_exceeded` below,\n // whatever its body names (§14.2 rule 9, amended).\n schedule.slowDown(); // §14.2 rule 1: cumulative, never reset.\n continue;\n }\n if (err.error === 'rate_limit_exceeded') {\n // §14.2 rule 9 (contract 1.64): wait `Retry-After` as a minimum,\n // count it as one interval, leave the interval alone, poll again.\n const pollWaitMs = POLL_RETRY_AFTER_MS.get(err);\n schedule.rateLimited(pollWaitMs === undefined ? undefined : pollWaitMs / 1000);\n continue;\n }\n throw err; // expired_token / access_denied / invalid_grant\n }\n // §14.2 rule 6: transport and 5xx failures are not among the five\n // protocol answers and are not terminal — a 5xx whatever its body\n // (contract 1.64, amended): `500 {\"error\":\"server_error\"}` maps to\n // `NetworkError` by status, before the body is read.\n if (err instanceof NetworkError) {\n continue;\n }\n throw err;\n }\n }\n }\n\n // -------------------------------------------------------------------------\n // §15 Token Exchange (RFC 8693)\n // -------------------------------------------------------------------------\n\n /**\n * `POST /oauth2/token` with the RFC 8693 grant (CONTRACT.md §15.1) —\n * exchange a token for a **narrower** one.\n *\n * @remarks\n * The exchanging client authenticates (`client_secret_post`): unlike §14's\n * device, this is a confidential service.\n *\n * What this method deliberately does **not** do:\n *\n * - **No default `actorToken`** (§15.2 rule 1). Passing none asks for\n * *impersonation*; the SDK will not quietly reuse the client's own session\n * token as the actor and turn that into a delegation.\n * - **No substitute for an actor token that was refused** (§15.2 rule 9). The\n * actor token must have been issued to this client — the usual one is its\n * own `client_credentials` token, `loginClientCredentials()`, which the\n * caller obtains and passes. Any other is answered `400 invalid_request`\n * (`actor_token was not issued to the exchanging client`), surfaced\n * unchanged: not retried, not dropped, not replaced.\n * - **No retry or downgrade on `unauthorized_client`** (rule 2) — a\n * registration fact an operator must fix.\n * - **No auto-narrowing on `invalid_scope`** (rule 3). The server refuses\n * instead of silently narrowing precisely so the caller finds out here.\n * - **No adoption** (rule 5). The returned token is handed onward in one\n * outbound call; adopting it would silently re-privilege every subsequent\n * call this client makes.\n *\n * A cross-tenant subject token answers `invalid_grant`, identically to an\n * expired one. The SDK does not try to tell them apart (§15.3): the server\n * collapses them because distinguishing them is a tenant-enumeration signal.\n *\n * @throws AuthError when no `clientSecret` is configured — client-side, with\n * no wire call.\n */\n async tokenExchange(params: TokenExchangeParams): Promise<ExchangedToken> {\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const form = new URLSearchParams();\n form.set('grant_type', TOKEN_EXCHANGE_GRANT_TYPE);\n form.set('subject_token', exposeSecret(params.subjectToken));\n // Whatever the caller named, verbatim. The subject token is NEVER decoded\n // to pick this (§15.7): which kind of token the caller holds is the\n // caller's to know, and a guess here is the difference between a request\n // that is refused and one that is silently reinterpreted.\n form.set('subject_token_type', params.subjectTokenType);\n if (params.actorToken !== undefined) {\n form.set('actor_token', exposeSecret(params.actorToken));\n // Sent exactly when `actor_token` is: RFC 8693 §2.1 requires the pair,\n // and the type alone is a malformed request.\n form.set('actor_token_type', ACCESS_TOKEN_TYPE);\n }\n if (params.scopes !== undefined) {\n form.set('scope', params.scopes.join(' '));\n }\n if (params.audience !== undefined) {\n form.set('audience', params.audience);\n }\n if (params.resource !== undefined) {\n form.set('resource', params.resource);\n }\n form.set('client_id', this.#options.clientId);\n form.set('client_secret', this.#requireClientSecret('tokenExchange'));\n\n const url = this.#endpointUrl(this.#requiredEndpoint(configuration, 'token_endpoint'), params.tenantId);\n const { data } = await this.#postForm<TokenExchangeResponseWire>(\n url,\n form,\n 'token exchange request failed',\n );\n\n return {\n accessToken: new Sensitive(data.access_token),\n issuedTokenType: data.issued_token_type,\n tokenType: data.token_type,\n expiresIn: data.expires_in,\n ...(data.scope != null ? { scope: data.scope } : {}),\n };\n }\n\n // -------------------------------------------------------------------------\n // §20 UMA 2.0 — Protection API and ticket grant\n // -------------------------------------------------------------------------\n\n /**\n * `POST /uma2/rreg/resource_set` — register a resource set (CONTRACT.md §20.1).\n *\n * @remarks\n * The `pat` is an explicit parameter, not this client's session. A Protection\n * API Token must be a **client-credentials** token, because a ticket binds to\n * the `client_id` that minted it — and this client's session is usually a\n * *user* session, which names no client to bind to (§20.2 rule 1).\n */\n async umaRegisterResource(\n pat: Sensitive<string> | string,\n resource: ResourceSet,\n ): Promise<ResourceSet> {\n const wire = await this.#umaProtection<ResourceSetWire>(\n 'post',\n '/uma2/rreg/resource_set',\n pat,\n toResourceSetWire(resource),\n );\n return fromResourceSetWire(wire);\n }\n\n /** `GET /uma2/rreg/resource_set/{id}` — read a resource set (§20.1). */\n async umaReadResource(pat: Sensitive<string> | string, id: string): Promise<ResourceSet> {\n const wire = await this.#umaProtection<ResourceSetWire>(\n 'get',\n `/uma2/rreg/resource_set/${encodeURIComponent(id)}`,\n pat,\n );\n return fromResourceSetWire(wire);\n }\n\n /**\n * `PUT /uma2/rreg/resource_set/{id}` — replace a resource set (§20.1).\n *\n * @remarks\n * **The scope list is replaced, not merged** (§20.2 rule 8). Whatever\n * `resource.resourceScopes` holds becomes the complete declared set; omitting\n * a scope removes it, which is how a resource server drops an authority. This\n * method performs no read-before-write.\n */\n async umaUpdateResource(\n pat: Sensitive<string> | string,\n id: string,\n resource: ResourceSet,\n ): Promise<ResourceSet> {\n const wire = await this.#umaProtection<ResourceSetWire>(\n 'put',\n `/uma2/rreg/resource_set/${encodeURIComponent(id)}`,\n pat,\n toResourceSetWire(resource),\n );\n return fromResourceSetWire(wire);\n }\n\n /** `DELETE /uma2/rreg/resource_set/{id}` — deregister (§20.1). */\n async umaDeleteResource(pat: Sensitive<string> | string, id: string): Promise<void> {\n await this.#umaProtection<void>(\n 'delete',\n `/uma2/rreg/resource_set/${encodeURIComponent(id)}`,\n pat,\n );\n }\n\n /**\n * `GET /uma2/rreg/resource_set` — list the ids **this client** registered\n * (§20.1).\n *\n * @remarks\n * Not the tenant's whole resource tree: a protection scope does not entitle a\n * caller to enumerate it.\n */\n async umaListResources(pat: Sensitive<string> | string): Promise<string[]> {\n return this.#umaProtection<string[]>('get', '/uma2/rreg/resource_set', pat);\n }\n\n /**\n * `POST /uma2/perm` — mint a permission ticket (§20.1).\n *\n * @remarks\n * Scope names are validated **here**, against each resource's declared set.\n * Asking for an undeclared scope is a `400`, not a denial — the two are\n * different failures, and this SDK surfaces the distinction the server draws\n * rather than flattening it.\n */\n async umaRequestTicket(\n pat: Sensitive<string> | string,\n permissions: RequestedPermission[],\n ): Promise<Sensitive<string>> {\n const wire = await this.#umaProtection<{ ticket: string }>(\n 'post',\n '/uma2/perm',\n pat,\n permissions.map((p) => ({\n resource_id: p.resourceId,\n resource_scopes: p.resourceScopes,\n })),\n );\n return new Sensitive(wire.ticket);\n }\n\n /**\n * `POST /oauth2/token` with the uma-ticket grant (§20.1) — exchange a ticket\n * for an RPT.\n *\n * @remarks\n * **This method never retries.** It issues exactly one request and is outside\n * the §16 retry policy — not on `5xx`, not on timeout, not on any transport\n * failure (§20.2 rule 6). The ticket is consumed *before* the request is\n * evaluated, so a failed exchange has already spent it: a retry cannot\n * succeed, and under concurrency it is precisely the concurrent redemption a\n * server whose storage engine this SDK cannot attest may admit twice\n * (ilpanich/axiam#302). On failure, request a **new** ticket.\n *\n * What it deliberately does not do:\n *\n * - **No default `claimToken`** (rule 2) — it is required. Defaulting it to\n * the resource server's own PAT would mint an RPT for the resource server\n * instead of for the user.\n * - **No auto-narrowing on `access_denied`** (rule 3). A partial grant is\n * refused whole; whether two-of-three permissions is useful is the\n * application's judgement, not this SDK's.\n * - **No adoption** (rule 4). The RPT is the *requesting party's* token.\n * Adopting it would re-privilege every later call this client makes as that\n * user.\n *\n * The four ticket refusals — unknown, expired, already used, wrong client —\n * all answer `invalid_grant` with one message. This SDK does not try to tell\n * them apart (§20.4): the server collapses them so a caller cannot probe for\n * live ticket handles.\n *\n * @throws AuthError when no `clientSecret` is configured — client-side, with\n * no wire call.\n */\n async umaExchangeTicket(params: UmaExchangeTicketParams): Promise<RequestingPartyToken> {\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const form = new URLSearchParams();\n form.set('grant_type', UMA_TICKET_GRANT_TYPE);\n form.set('ticket', exposeSecret(params.ticket));\n form.set('claim_token', exposeSecret(params.claimToken));\n form.set('claim_token_format', UMA_CLAIM_TOKEN_FORMAT);\n form.set('client_id', this.#options.clientId);\n form.set('client_secret', this.#requireClientSecret('umaExchangeTicket'));\n\n const url = this.#endpointUrl(this.#requiredEndpoint(configuration, 'token_endpoint'), params.tenantId);\n // One POST, no retry wrapper. See the rule-6 note above — this is the §16\n // exception, and it is load-bearing rather than stylistic.\n let data: RptResponseWire;\n try {\n const config: AxiosRequestConfig = {\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n maxRedirects: 0,\n };\n const response = await this.#session.axios.post<RptResponseWire>(\n url,\n form.toString(),\n config,\n );\n data = response.data;\n } catch (err) {\n throw mapUmaGrantError(err, url, 'uma ticket exchange request failed');\n }\n\n return {\n accessToken: new Sensitive(data.access_token),\n tokenType: data.token_type,\n expiresIn: data.expires_in,\n };\n }\n\n /** Shared PAT-authenticated Protection API request. */\n async #umaProtection<T>(\n method: 'get' | 'post' | 'put' | 'delete',\n path: string,\n pat: Sensitive<string> | string,\n body?: unknown,\n ): Promise<T> {\n const config: AxiosRequestConfig = {\n headers: { Authorization: `Bearer ${exposeSecret(pat)}` },\n };\n try {\n const response =\n method === 'get' || method === 'delete'\n ? await this.#session.axios[method]<T>(path, config)\n : await this.#session.axios[method]<T>(path, body, config);\n return response.data;\n } catch (err) {\n throw mapOidcError(err, path, 'UMA protection API request failed');\n }\n }\n\n // -------------------------------------------------------------------------\n // §12.7 Logout helpers\n // -------------------------------------------------------------------------\n\n /**\n * Build the RP-initiated logout URL to redirect the user agent to\n * (CONTRACT.md §12.7.2).\n *\n * @remarks\n * Performs **no network I/O** beyond the discovery fetch the SDK caches\n * anyway, and does **not** clear this client's own session: whether the\n * local session ends is the application's decision — a backend holding a\n * service-account session must not lose it because a *user* logged out.\n *\n * `end_session_endpoint` is read from discovery and never synthesised from\n * the issuer (rule 1). Code that concatenates works against AXIAM and breaks\n * against every other OP the same application is pointed at.\n *\n * `postLogoutRedirectUri` is passed through **unvalidated against any local\n * list** (rule 3): the allow-list lives in the client's server-side\n * registration, and a client-side copy would drift and reject a URI an\n * operator had just registered.\n */\n async logoutUrl(params: LogoutUrlParams): Promise<string> {\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const endpoint = configuration.end_session_endpoint;\n if (!endpoint) {\n throw new AuthError(\n \"the authorization server's discovery document advertises no \" +\n 'end_session_endpoint: this server does not support RP-initiated logout ' +\n '(CONTRACT.md §12.7.2 rule 1)',\n );\n }\n\n const url = new URL(endpoint);\n url.searchParams.set('id_token_hint', exposeSecret(params.idToken));\n if (params.postLogoutRedirectUri !== undefined) {\n url.searchParams.set('post_logout_redirect_uri', params.postLogoutRedirectUri);\n }\n if (params.state !== undefined) {\n url.searchParams.set('state', params.state);\n }\n return url.toString();\n }\n\n /**\n * Verify a back-channel logout token the OP POSTed to this application's\n * `backchannel_logout_uri` (CONTRACT.md §12.7.3).\n *\n * @remarks\n * Every check exists because skipping it has a name:\n *\n * 1. **Signature**, through the same §12.4 JWKS verifier the ID-token path\n * uses — no second key-fetching path — with the same `kid`-required\n * discipline.\n * 2. **`iss`/`aud`**: a token minted for another RP is not accepted here.\n * 3. **`events` carries the back-channel-logout key.** This is what\n * distinguishes a logout token from an ID token; skipping it means\n * accepting a replayed ID token as a logout instruction.\n * 4. **`nonce` is absent.** Back-Channel Logout 1.0 §2.4 forbids it, and its\n * presence is the documented signature of an ID token being replayed.\n * Rejected, not ignored.\n * 5. **At least one of `sid`/`sub`** — a token naming neither identifies\n * nothing.\n * 6. **`exp` in the future, `iat` recent.**\n *\n * @returns `sid`, `sub` and `jti` — never a bare boolean, because the RP has\n * to know *which* session to end.\n */\n async verifyLogoutToken(\n token: string,\n configuration?: OidcConfiguration,\n ): Promise<VerifiedLogoutToken> {\n const config = configuration ?? (await this.oidcDiscover());\n const { decodeProtectedHeader } = await import('jose');\n\n // Same alg/kid discipline as §12.4 rules 1-2, applied before any key\n // lookup: a token with no `kid` gets no \"the only key\" fallback.\n let header: { alg?: string; kid?: string };\n try {\n header = decodeProtectedHeader(token);\n } catch {\n throw new AuthError('logout token is not a well-formed JWS');\n }\n if (header.alg !== 'EdDSA') {\n throw new AuthError(`logout token alg must be EdDSA, got ${String(header.alg)}`);\n }\n if (!header.kid) {\n throw new AuthError('logout token carries no kid header');\n }\n\n const claims = (await this.#verifierFor(config.jwks_uri).verifySignatureOnlyUnchecked(\n token,\n )) as unknown as LogoutTokenClaims;\n\n if (claims.iss !== config.issuer) {\n throw new AuthError('logout token issuer does not match the discovery document');\n }\n if (claims.aud !== this.#options.clientId) {\n throw new AuthError('logout token audience does not match this client_id');\n }\n\n // Without this check the whole method is an elaborate way to accept an ID\n // token.\n const event = claims.events?.[BACKCHANNEL_LOGOUT_EVENT];\n if (event === undefined || typeof event !== 'object' || event === null || Array.isArray(event)) {\n throw new AuthError(\n 'not a logout token: the events claim does not carry ' +\n 'http://schemas.openid.net/event/backchannel-logout',\n );\n }\n\n if (claims.nonce !== undefined) {\n throw new AuthError(\n 'logout token carries a nonce, which Back-Channel Logout 1.0 §2.4 forbids: ' +\n 'this is an ID token being replayed as a logout token',\n );\n }\n\n if (claims.sid === undefined && claims.sub === undefined) {\n throw new AuthError('logout token names neither sid nor sub, so it identifies no session');\n }\n\n const nowSec = Math.floor(Date.now() / 1000);\n const skew = this.#options.clockSkewSec ?? 0;\n if (typeof claims.exp !== 'number' || claims.exp + skew < nowSec) {\n throw new AuthError('logout token has expired');\n }\n if (typeof claims.iat !== 'number' || claims.iat - skew > nowSec) {\n throw new AuthError('logout token was issued in the future');\n }\n if (nowSec - claims.iat > MAX_LOGOUT_TOKEN_AGE_SECS + skew) {\n throw new AuthError('logout token is too old to be a live delivery');\n }\n\n if (typeof claims.jti !== 'string' || claims.jti === '') {\n throw new AuthError('logout token carries no jti, so the RP cannot dedup redeliveries');\n }\n\n return {\n ...(claims.sid !== undefined ? { sid: claims.sid } : {}),\n ...(claims.sub !== undefined ? { sub: claims.sub } : {}),\n jti: claims.jti,\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 // -------------------------------------------------------------------------\n // §33 CIBA — client-initiated backchannel authentication (contract 1.58)\n //\n // On this handle because §33.6 puts them beside `oidcExchange` and\n // `deviceAuthorize`. The client always authenticates — by its\n // `clientSecret` (client_secret_post) or, for a `tls_client_auth` client,\n // by the session's §6.1 client certificate (`client_id` only); a client\n // with neither is refused locally. `private_key_jwt` client authentication\n // is not implemented by this SDK (§21.8 is informative).\n // -------------------------------------------------------------------------\n\n /**\n * `POST /oauth2/bc-authorize` (CIBA Core §7, CONTRACT.md §33.1) — ask AXIAM\n * to authenticate a user **on another device**.\n *\n * @remarks\n * Form-encoded; `tenant_id` in the query, never the body; the endpoint is\n * discovery's `backchannel_authentication_endpoint`, or its\n * `mtls_endpoint_aliases` entry on an mTLS call. Exactly the members set are\n * sent — or, with `signer`, only client authentication and `request`, a JWS\n * carrying every member (`requested_expiry` as a number) plus `iss` =\n * `clientId`, `aud` = discovery `issuer`, `iat` = `nbf` = now, `exp` = now +\n * 300 s and a fresh 128-bit `jti`.\n *\n * **Never retried** — not on a transport error, a `5xx` or a `429` (§33.7\n * rule 1): every accepted call stores a request and may notify a person. On\n * a lost answer, let it expire and ask again deliberately.\n *\n * **A success proves nothing about the user** (§33.3 rule 4): AXIAM answers\n * a hint naming nobody, a locked user and a real one identically.\n *\n * @throws AuthError (local) when the client has no credential, or the\n * server advertises no CIBA endpoint.\n * @throws ValidationError (local) for both or neither hint, or a ping-mode\n * request without a non-empty `clientNotificationToken`.\n * @throws OAuthProtocolError for a body carrying `error`, at any status —\n * `invalid_binding_message` with its description, a `429`\n * `rate_limit_exceeded`; otherwise §2 (`503` is `NetworkError`).\n */\n async cibaInitiate(params: CibaInitiateParams): Promise<CibaInitiateResponse> {\n const operation = 'ciba_initiate';\n const auth = this.#cibaClientAuth(operation);\n const hasLogin = typeof params.loginHint === 'string';\n const hasIdToken = typeof params.idTokenHint === 'string';\n if (hasLogin === hasIdToken) {\n throw cibaRefusal(operation, 'login_hint', 'set exactly one of loginHint and idTokenHint');\n }\n if (params.delivery?.mode === 'ping') {\n const token = params.delivery.clientNotificationToken;\n if (!(token instanceof Sensitive) || typeof token.expose() !== 'string' || token.expose() === '') {\n throw cibaRefusal(\n operation,\n 'client_notification_token',\n 'a ping-mode request needs a non-empty clientNotificationToken: without one AXIAM has nothing to ping with',\n );\n }\n }\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const endpoint = this.#optionalEndpoint(configuration, 'backchannel_authentication_endpoint');\n if (!endpoint) {\n throw new AuthError(\n \"the authorization server's discovery document advertises no backchannel_authentication_endpoint: \" +\n 'this server does not support CIBA (CONTRACT.md §33.1)',\n );\n }\n const url = this.#endpointUrl(endpoint, params.tenantId);\n\n const form = new URLSearchParams();\n form.set('client_id', auth.clientId);\n if (auth.clientSecret !== undefined) form.set('client_secret', auth.clientSecret);\n if (params.signer) {\n const nowSec = Math.floor(Date.now() / 1000);\n const claims: Record<string, unknown> = {};\n for (const [k, v] of cibaMembers(params)) claims[k] = v;\n if (params.requestedExpiry !== undefined) claims.requested_expiry = params.requestedExpiry;\n claims.iss = auth.clientId;\n claims.aud = configuration.issuer;\n claims.iat = nowSec;\n claims.nbf = nowSec;\n claims.exp = nowSec + SIGNED_REQUEST_LIFETIME_SECS;\n claims.jti = randomBytes(16).toString('hex');\n const request = await params.signer.sign(claims);\n form.set('request', request.expose());\n } else {\n for (const [k, v] of cibaMembers(params)) form.set(k, v);\n }\n\n // One request, whatever happens to it (§33.7 rule 1).\n const response = await this.#postCibaForm(url, form, operation);\n if (response.status < 200 || response.status >= 300) throw cibaError(operation, response);\n const data = jsonBody(response.data) as { auth_req_id?: unknown; expires_in?: unknown; interval?: unknown } | undefined;\n if (!data || typeof data.auth_req_id !== 'string' || typeof data.expires_in !== 'number') {\n throw new NetworkError('ciba_initiate: the response is not a CibaInitiateResponse');\n }\n return {\n authReqId: new Sensitive(data.auth_req_id),\n expiresIn: data.expires_in,\n interval: typeof data.interval === 'number' && data.interval > 0 ? data.interval : DEFAULT_CIBA_INTERVAL_SECS,\n receivedAt: Date.now(),\n };\n }\n\n /**\n * `POST /oauth2/token` with `grant_type=urn:openid:params:grant-type:ciba`\n * (CIBA Core §10.1, CONTRACT.md §33.1) — **one** token request.\n *\n * @remarks\n * The answers of §33.3 rule 6 surface as {@link OAuthProtocolError}:\n * `authorization_pending` and `slow_down` (non-terminal), `access_denied` and\n * `expired_token` (terminal and distinct — {@link isAccessDenied},\n * {@link isExpiredToken}), `invalid_grant`, `rate_limit_exceeded`. None of\n * them is retried. A transport failure, `408`, bodiless `429` or `5xx` —\n * **whatever its body**, `500 {\"error\":\"server_error\"}` included (§34.2 P8)\n * — is retried per §16 within the call; no other `4xx` is.\n *\n * A `200` is the §12 token set; its ID token is validated as for every other\n * grant (no nonce). **Store the returned tokens before anything else**: a\n * request is redeemed once, and a second `cibaPoll` for it is\n * `invalid_grant` (§33.7 rule 7). The tokens are returned, never adopted as\n * this client's credential.\n */\n async cibaPoll(params: CibaPollParams): Promise<OidcTokenSet> {\n return this.#cibaPoll(params, undefined);\n }\n\n /** {@link cibaPoll}; `bound` is `cibaAwait`'s deadline, which a §16 retry inside the poll must not pass. */\n async #cibaPoll(params: CibaPollParams, bound: PollDeadline | undefined): Promise<OidcTokenSet> {\n const operation = 'ciba_poll';\n const auth = this.#cibaClientAuth(operation);\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const url = this.#endpointUrl(this.#requiredEndpoint(configuration, 'token_endpoint'), params.tenantId);\n const form = new URLSearchParams();\n form.set('grant_type', CIBA_GRANT_TYPE);\n form.set('auth_req_id', params.authReqId.expose());\n form.set('client_id', auth.clientId);\n if (auth.clientSecret !== undefined) form.set('client_secret', auth.clientSecret);\n\n const outcome = await withRetry<{ wire?: TokenResponseWire; error?: AxiamError }>(\n async () => {\n const response = await this.#postCibaForm(url, form, operation);\n if (response.status >= 200 && response.status < 300) {\n // §33.7 rule 7: consume the 200 before anything else — and a body\n // that does not parse is not retried, since the server may already\n // have redeemed the request.\n const wire = jsonBody(response.data) as TokenResponseWire | undefined;\n if (!wire || typeof wire.access_token !== 'string') {\n return { error: new NetworkError('ciba_poll: the response is not a TokenResponse') };\n }\n return { wire };\n }\n // §33.7 rule 5, §34.2 P8: a 5xx is transient whatever its body —\n // AXIAM's own token endpoint answers `500 {\"error\":\"server_error\"}` —\n // so it is retried under §16 before any `error` member is read.\n if (response.status >= 500) {\n throw transient(retryableNetworkError(`${operation}: HTTP ${response.status}`, response));\n }\n if (response.status >= 300 && response.status < 400) {\n return { error: redirectRefused(operation, response.status) };\n }\n const protocol = oauth2ErrorFromBody(\n jsonBody(response.data),\n response.status === 429 ? retryAfterMs(response) : undefined,\n );\n if (protocol) return { error: protocol }; // decisive, never retried\n if (statusIsRetryable(response.status)) {\n throw transient(retryableNetworkError(`${operation}: HTTP ${response.status}`, response));\n }\n return { error: mapHttpStatusToError(response.status, `${operation}: HTTP ${response.status}`) };\n },\n {\n idempotent: true,\n operation,\n enabled: this.#session.retryEnabled,\n telemetry: this.#session.telemetry.dispatcher,\n ...(bound !== undefined ? deadlineBoundedRetry(bound, 'CIBA request') : {}),\n },\n );\n if (outcome.error) throw outcome.error;\n return this.#toTokenSet(outcome.wire as TokenResponseWire, configuration, undefined);\n }\n\n /**\n * Poll for `initiated`'s outcome until it is decided or expires (§33.1,\n * §33.7). Surfaces nothing to the user — AXIAM notified them.\n *\n * @remarks\n * - The first poll waits one `interval` (the response's, or 5 s); polling\n * earlier only earns `slow_down` and a longer wait.\n * - `slow_down` adds 5 s to the interval, cumulatively and permanently;\n * `authorization_pending` never lowers it.\n * - `rate_limit_exceeded`, and a transport failure or `5xx` that outlived\n * §16's retries inside {@link cibaPoll}, are not terminal: the loop waits\n * the interval and polls again.\n * - Polling stops at `receivedAt + expiresIn`, even if the server has not\n * said `expired_token`: when the next wait would reach the deadline, the\n * same `expired_token` is raised locally, without a request. A §16 retry\n * inside {@link cibaPoll} is bounded the same way (§34.2 P10): a wait that\n * would reach the deadline is not served and nothing is sent after it.\n * - `access_denied`, `expired_token`, `invalid_grant` and any other answer\n * end the loop.\n *\n * Returns the token set without adopting it as this client's credential —\n * the posture of `deviceLogin` and `loginClientCredentials`.\n *\n * **Ping mode:** do not loop. Answer the ping (`cibaHandlePing`) with `204`,\n * then call {@link cibaPoll} once — and once more at `interval` if that\n * answered `authorization_pending` or `slow_down`. Fall back to this loop\n * once half of `expiresIn` has passed without a ping: a ping is delivered at\n * least once, never exactly once, and may not arrive at all (§33.7 rule 6).\n */\n async cibaAwait(initiated: CibaInitiateResponse, params: CibaAwaitParams = {}): Promise<OidcTokenSet> {\n const clock = params.clock ?? SYSTEM_CIBA_CLOCK;\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const deadline = initiated.receivedAt + initiated.expiresIn * 1000;\n let interval = initiated.interval > 0 ? initiated.interval : DEFAULT_CIBA_INTERVAL_SECS;\n for (;;) {\n const waitMs = interval * 1000;\n if (clock.now() + waitMs >= deadline) {\n throw new OAuthProtocolError(\n 'expired_token',\n 'the CIBA request expired before it was decided (client-side deadline from expires_in; CONTRACT.md §33.7 rule 4)',\n );\n }\n await clock.sleep(waitMs);\n try {\n return await this.#cibaPoll(\n {\n authReqId: initiated.authReqId,\n configuration,\n ...(params.tenantId !== undefined ? { tenantId: params.tenantId } : {}),\n },\n { deadline, clock },\n );\n } catch (err) {\n if (err instanceof OAuthProtocolError) {\n if (err.error === 'authorization_pending' || err.error === 'rate_limit_exceeded') continue;\n if (err.error === 'slow_down') {\n interval += CIBA_SLOW_DOWN_INCREMENT_SECS; // cumulative, never reset\n continue;\n }\n throw err;\n }\n if (err instanceof NetworkError && TRANSIENT_POLL_FAILURES.has(err)) continue;\n throw err;\n }\n }\n }\n\n /**\n * Check a ping AXIAM delivered to your notification endpoint and return the\n * `auth_req_id` it names (CIBA Core §10.2, CONTRACT.md §33.1). **No I/O.**\n *\n * @param headers the request's headers — prefer Node's `req.rawHeaders`,\n * which keeps a duplicated `Authorization` that `req.headers` drops.\n * @param body the raw body (`string` / `Uint8Array`) or an already-parsed object.\n * @param expectedToken the `clientNotificationToken` you sent with the request.\n *\n * @remarks\n * 1. Exactly one `Authorization` header, `Bearer` (any case), one space, and\n * the token — compared in constant time (`crypto.timingSafeEqual`).\n * Otherwise `AuthError`, whose message names no value.\n * 2. A JSON object with a non-empty string `auth_req_id`; any other member\n * is ignored. Otherwise a local `ValidationError`.\n *\n * It neither answers the HTTP request nor calls the token endpoint: answer\n * `204` as soon as this returns, **then** {@link cibaPoll} — AXIAM retries a\n * ping that is not answered quickly, and the ping says only that the\n * request was decided, never how. Nor does it check that the `auth_req_id`\n * is one you issued: the token endpoint answers `invalid_grant` for any\n * other.\n */\n cibaHandlePing(\n headers: CibaPingHeaders,\n body: string | Uint8Array | Record<string, unknown>,\n expectedToken: Sensitive<string>,\n ): Sensitive<string> {\n const refused = (): AuthError =>\n new AuthError('ciba ping refused: the Authorization header is not the expected bearer (CONTRACT.md §33.1)');\n const values = authorizationValues(headers);\n if (values.length !== 1) throw refused();\n const value = values[0]!;\n const space = value.indexOf(' ');\n if (space < 0) throw refused();\n const scheme = value.slice(0, space);\n const token = value.slice(space + 1);\n if (scheme.toLowerCase() !== 'bearer' || token === '') throw refused();\n const expected = expectedToken instanceof Sensitive ? expectedToken.expose() : undefined;\n if (typeof expected !== 'string' || expected === '') throw refused();\n if (!constantTimeEqual(token, expected)) throw refused();\n\n let parsed: unknown = body;\n if (typeof body === 'string' || body instanceof Uint8Array) {\n try {\n parsed = JSON.parse(typeof body === 'string' ? body : Buffer.from(body).toString('utf8'));\n } catch {\n throw cibaRefusal('ciba_handle_ping', 'body', 'the ping body is not JSON');\n }\n }\n const id =\n parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>).auth_req_id\n : undefined;\n if (typeof id !== 'string' || id === '') {\n throw cibaRefusal('ciba_handle_ping', 'auth_req_id', 'the ping body carries no non-empty auth_req_id string');\n }\n return new Sensitive(id);\n }\n\n /** The client's credential for the CIBA calls (§33.1): never anonymous. */\n #cibaClientAuth(operation: string): { clientId: string; clientSecret?: string } {\n const secret = this.#options.clientSecret;\n if (secret !== undefined) {\n return { clientId: this.#options.clientId, clientSecret: exposeSecret(secret) };\n }\n if (this.#session.presentsClientCertificate) {\n // tls_client_auth: the certificate is the credential; client_id only.\n return { clientId: this.#options.clientId };\n }\n throw new AuthError(\n `${operation} requires client authentication: a CIBA client is never public — construct the OidcClient ` +\n 'with a clientSecret, or the session with a §6.1 client certificate (CONTRACT.md §33.1)',\n );\n }\n\n /**\n * POST a CIBA form through the session transport (§5 `X-Tenant-ID`, §6 TLS)\n * with every status resolved, so the CIBA error mapping — `error` at any\n * status, §33.4 — decides, and a `401` never enters the §9 guard. A transport\n * failure becomes a `NetworkError` that carries no axios cause: its `config`\n * holds the form, and the form holds the client secret.\n */\n async #postCibaForm(url: string, form: URLSearchParams, operation: string): Promise<AxiosResponse<unknown>> {\n try {\n return await this.#session.axios.post<unknown>(url, form.toString(), {\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n validateStatus: () => true,\n maxRedirects: 0,\n });\n } catch (err) {\n const code =\n err && typeof err === 'object' && typeof (err as { code?: unknown }).code === 'string'\n ? ` (${(err as { code: string }).code})`\n : '';\n throw transient(new NetworkError(`${operation}: the request failed before any response arrived${code}`));\n }\n }\n\n /**\n * One device-poll attempt under §16 (CONTRACT.md §14.2 rule 6, §16.2; C164-25): a `5xx` or\n * a transport failure is retried **inside** the poll (three requests in all, the `Retry-After`\n * a floor) before it surfaces as a `NetworkError`; the loop then takes its next interval. A\n * `429` is never retried here — it is rule 9's wait, the loop's — nor is any answer the\n * server decided (`400`, `401`).\n */\n async #postDevicePoll(\n url: string,\n form: URLSearchParams,\n bound: PollDeadline | undefined,\n ): Promise<TokenResponseWire> {\n const operation = 'device_poll';\n const outcome = await withRetry<{ wire?: TokenResponseWire; error?: AxiamError }>(\n async () => {\n try {\n const response = await this.#session.axios.post<TokenResponseWire>(url, form.toString(), {\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n maxRedirects: 0,\n });\n return { wire: response.data };\n } catch (err) {\n // Already an SDK error (the response interceptor mapped it): a decided answer.\n if (err instanceof AxiamError) return { error: err };\n const status = axiosStatus(err);\n const response = (err as { response?: AxiosResponse }).response;\n if (status === undefined) {\n throw new NetworkError(`${operation}: the request failed before any response arrived`, sanitizeAxiosError(err));\n }\n if (status >= 500) {\n throw retryableNetworkError(`${operation}: HTTP ${status}`, response);\n }\n return { error: pollRateLimit(err) ?? mapOidcError(err, url, 'token request failed') };\n }\n },\n {\n idempotent: true,\n operation,\n enabled: this.#session.retryEnabled,\n telemetry: this.#session.telemetry.dispatcher,\n ...(bound !== undefined ? deadlineBoundedRetry(bound, 'device authorization') : {}),\n },\n );\n if (outcome.error) throw outcome.error;\n return outcome.wire!;\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(this.#requiredEndpoint(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 * The RFC 8705 §5 alias for `name`, or `undefined` when this call is not\n * going over mutual TLS or the document publishes no aliases (CONTRACT.md\n * §21.3 rule 2).\n *\n * Three things this deliberately does NOT do, each of them a documented way\n * to get rule 2 wrong:\n *\n * * It never treats an absent `mtls_endpoint_aliases` as an error. Absence\n * means \"no separate mTLS host\", not \"mTLS unsupported\" — a deployment\n * running `client_auth = optional` on one listener serves both\n * populations at the conventional endpoints and correctly publishes\n * nothing.\n * * It is keyed by {@link MtlsEndpointAliases}, so only the seven aliasable\n * endpoints can reach it. `authorization_endpoint`,\n * `end_session_endpoint` and `jwks_uri` are unrepresentable here rather\n * than merely unused: they are front-channel or public, and an mTLS host\n * would raise a certificate-chooser dialog in the user's browser.\n * * It never touches `issuer`, which is an identifier and not an endpoint.\n * §10.1 rule 3 still compares a token's `iss` to `configuration.issuer`\n * by exact string, including for a token minted at an alias endpoint.\n *\n * An alias that IS present and cannot carry a certificate throws\n * (§21.3.1 vector C, contract 1.43) — see {@link assertUsableMtlsAlias}.\n */\n #aliasFor(\n configuration: OidcConfiguration,\n name: keyof MtlsEndpointAliases,\n replaces: string | undefined,\n ): string | undefined {\n if (!this.#session.presentsClientCertificate) {\n // A client with no certificate does not read the member at all — not\n // even to validate it. A deployment whose aliases are malformed must not\n // break the clients that never use them.\n return undefined;\n }\n const alias = configuration.mtls_endpoint_aliases?.[name];\n if (alias === undefined) {\n return undefined;\n }\n assertUsableMtlsAlias(alias, replaces);\n return alias;\n }\n\n /** An always-advertised endpoint, preferring its §21.3 rule 2 mTLS alias. */\n #requiredEndpoint(\n configuration: OidcConfiguration,\n name: 'token_endpoint' | 'userinfo_endpoint' | 'revocation_endpoint' | 'introspection_endpoint',\n ): string {\n return this.#aliasFor(configuration, name, configuration[name]) ?? configuration[name];\n }\n\n /**\n * A conditionally-advertised endpoint, preferring its §21.3 rule 2 mTLS\n * alias. `undefined` still means \"this server does not support the feature\" —\n * the caller raises that, and never concatenates a URL onto the issuer.\n */\n #optionalEndpoint(\n configuration: OidcConfiguration,\n name:\n | 'device_authorization_endpoint'\n | 'pushed_authorization_request_endpoint'\n | 'backchannel_authentication_endpoint',\n ): string | undefined {\n return this.#aliasFor(configuration, name, configuration[name]) ?? configuration[name];\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 // CONTRACT 1.52 N4.4 (C-12): client-credentials adoption is one of the\n // session-establishing calls that REPLACES a previously-adopted device\n // credential. Without this, a client that had called\n // authenticateDevice() and then adopted client-credentials kept riding\n // the stale device token on every later same-origin request —\n // installDeviceTokenInterceptor sends it unconditionally whenever\n // `deviceAccessToken` is set, regardless of what new credential was\n // just adopted here.\n this.#session.deviceAccessToken = undefined;\n // CONTRACT 1.52 N5.5 (C-12): client-credentials adoption carries no\n // LoginUserInfo, so it resets the §5.2 acting-tenant gate to unknown —\n // the same as a WebAuthn authentication, an SSO completion, or a device\n // login. Without this, a session that had recorded an earlier login's\n // (possibly non-organization-level) principalScope kept gating\n // actingTenant() on that STALE report after adopting an unrelated\n // service-account credential, instead of letting the server's 403\n // decide as N5.5 requires.\n this.#session.principalScope = undefined;\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) || isOAuth2Endpoint(url, this.#session.baseUrl)) {\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 // §12.1 rule 3 (C165-14): never follow a redirect from an `/oauth2/*` POST.\n maxRedirects: 0,\n };\n try {\n return await this.#session.axios.post<T>(url, form.toString(), config);\n } catch (err) {\n // §2 / §14.2 rule 9 (C164-23): a `429` carrying an `error` member from one of the OAuth2\n // form endpoints (token, device authorization, introspection, revocation, PAR, exchange)\n // is that OAuth2 error (AXIAM's own is `{\"error\":\"rate_limit_exceeded\"}`, with no\n // description), not a bare `NetworkError`. Gated by the call site, not `mapOidcError`, which\n // also maps discovery, the federation routes and UMA, where a `429` stays a `NetworkError`\n // (C164-31). A 5xx stays one whatever its body (§14.2 rule 6).\n if (axiosStatus(err) === 429) {\n const raw = (err as { response?: AxiosResponse }).response;\n const protocol = oauth2ErrorFromBody(axiosBody(err), raw ? retryAfterMs(raw) : undefined);\n if (protocol) throw protocol;\n }\n throw mapOidcError(err, url, fallbackMessage);\n }\n }\n\n /**\n * The shared body of the federation POSTs that establish a session: one\n * wire call, then the same post-login sync `login()`/`verifyMfa()` perform\n * (§4, §3) — reading the freshly-set `axiam_csrf`/`axiam_access` cookies out\n * of the jar.\n */\n /**\n * CONTRACT.md §5.2 rule 1 (C-12 question 5): a federation sign-in completes a\n * new session, possibly as a different principal, and its response carries no\n * LoginUserInfo. Forget what the previous login reported, so `actingTenant()`\n * does not gate on a stale principal and sends the header for the server to\n * decide, and drop the §17 memo, whose entries answered for that principal.\n * Called only after the server accepted the completion; a refused one\n * establishes no session and changes nothing.\n */\n #forgetPreviousPrincipal(): void {\n this.#session.principalScope = undefined;\n this.#session.decisionMemo.clear();\n // CONTRACT 1.52 N4.4 (C-12): an SSO/federation completion is one of the\n // session-establishing calls that REPLACES a previously-adopted device\n // credential. Without this, a client that had called\n // authenticateDevice() and then completed a federation sign-in kept\n // riding the stale device token on every later request —\n // installDeviceTokenInterceptor sends it unconditionally whenever\n // `deviceAccessToken` is set, regardless of what new session was just\n // established.\n // CONTRACT 1.52 N4.4 (C-12): an SSO/federation completion is one of the\n // session-establishing calls that REPLACES a previously-adopted device\n // credential. Without this, a client that had called\n // authenticateDevice() and then completed a federation sign-in kept\n // riding the stale device token on every later request —\n // installDeviceTokenInterceptor sends it unconditionally whenever\n // `deviceAccessToken` is set, regardless of what new session was just\n // established.\n this.#session.deviceAccessToken = undefined;\n }\n\n async #completeFederationSession(\n url: string,\n body: Record<string, string>,\n fallbackMessage: string,\n ): Promise<SsoCompleteResult> {\n const response = await this.#postJson<SsoLoginSuccessResponseWire>(url, body, fallbackMessage);\n\n this.#session.authenticated = true;\n this.#forgetPreviousPrincipal();\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 /** 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\n/**\n * Constant-time string comparison for `cibaHandlePing` (§33.1 rule 1):\n * `crypto.timingSafeEqual` over the UTF-8 bytes. A length mismatch is\n * answered `false` after comparing the presented value with itself, so the\n * time taken does not depend on where the two first differ.\n */\nfunction constantTimeEqual(token: string, expectedToken: string): boolean {\n const presented = Buffer.from(token, 'utf8');\n const expected = Buffer.from(expectedToken, 'utf8');\n if (presented.length !== expected.length) {\n timingSafeEqual(presented, presented);\n return false;\n }\n return timingSafeEqual(presented, expected);\n}\n","// CONTRACT.md §10.4 — the optional session-revocation feed poller (contract\n// 1.44; AXIAM threats T-39 and T-143).\n//\n// WHAT THIS NARROWS, AND WHAT IT IS NOT\n//\n// An AXIAM access token is self-contained and valid for up to fifteen minutes,\n// and the §10 guard verifies it locally. A logout, a role removal or an\n// account disable therefore does not reach a token already in a caller's hands\n// until it expires — §10.2 records that, and the documented answer has been\n// \"route the decision through gRPC introspection instead\", which is correct and\n// costs a round trip PER REQUEST.\n//\n// A deployment may publish `GET /oauth2/revocations`: the base64url-unpadded\n// SHA-256 of every session id revoked within the last access-token lifetime. A\n// guard that polls it rejects a revoked session within ONE POLL INTERVAL\n// instead, for one cacheable fetch per interval.\n//\n// It is NOT A CONTROL, and every rule below follows from that:\n//\n// * Default off. Nothing polls unless a caller attaches one.\n// * Never on the request path. `isRevoked` answers from the cached set and,\n// at most, starts a refresh whose result the NEXT caller sees.\n// * Never fail closed. An unreachable feed, a non-200, a body that does not\n// parse, an `alg` this build does not know — every one behaves exactly as\n// no feed at all. Not as an empty list: an empty list asserts that nothing\n// has been revoked, which is a guard silently honouring no revocations\n// while appearing to honour them.\n// * It only ever rejects. Every §10.1 rule runs first and still decides.\n// * A token with no `sid` is never matched. There is no session behind a\n// client-credentials token, an RPT or a token exchange, and hashing `jti`\n// instead would match nothing while looking like it worked.\n\nimport { createHash } from 'node:crypto';\n\n/**\n * The only digest the feed publishes, and the only one this poller accepts.\n *\n * A document naming anything else is treated as unusable — exactly as an\n * unreachable feed is — rather than as a list of entries that happen not to\n * match. Silently matching nothing is how a guard ends up reporting that it\n * honours revocations while honouring none.\n */\nconst SUPPORTED_ALG = 'SHA-256';\n\n/** The shortest interval a caller may configure (§10.4 rule 2), in ms. */\nexport const MIN_POLL_INTERVAL_MS = 15_000;\n\n/** The default interval, and the one §10.4 recommends, in ms. */\nexport const DEFAULT_POLL_INTERVAL_MS = 30_000;\n\n/**\n * The largest number of entries kept in the cache (§10.4 rule 2).\n *\n * The server bounds the document by its own revocation rate over one token\n * lifetime, so this is defence against a server that stops doing so — a cache\n * with no ceiling is an allocation an unauthenticated endpoint controls.\n * Overflow drops the WHOLE set rather than truncating it: a truncated set is a\n * guard that admits some revoked sessions and reports none, which is worse\n * than one that admits all of them and says the feed is unusable.\n */\nexport const MAX_ENTRIES = 100_000;\n\n/** Options for {@link RevocationFeed}. */\nexport interface RevocationFeedOptions {\n /** Poll interval in milliseconds. Clamped to {@link MIN_POLL_INTERVAL_MS}. */\n pollIntervalMs?: number;\n /** Injected for tests. Defaults to `globalThis.fetch`. */\n fetchImpl?: typeof fetch;\n /** Injected for tests. Defaults to `Date.now`. */\n now?: () => number;\n}\n\n/**\n * A poller for one deployment's revocation feed.\n *\n * Share one instance across the guards that should poll once between them,\n * rather than once each.\n */\nexport class RevocationFeed {\n readonly #feedUrl: string;\n readonly #pollIntervalMs: number;\n readonly #fetchImpl: typeof fetch;\n readonly #now: () => number;\n\n /**\n * `undefined` means \"never successfully fetched\", which is NOT the same as\n * an empty set — and is why this is not a bare `Set`.\n */\n #entries: Set<string> | undefined;\n #lastAttempt: number | undefined;\n /** Collapses a burst of stale-cache callers into one fetch. */\n #inFlight: Promise<void> | undefined;\n\n constructor(baseUrl: string, options: RevocationFeedOptions = {}) {\n this.#feedUrl = new URL('/oauth2/revocations', baseUrl).toString();\n this.#pollIntervalMs = Math.max(\n options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS,\n MIN_POLL_INTERVAL_MS,\n );\n this.#fetchImpl = options.fetchImpl ?? globalThis.fetch.bind(globalThis);\n this.#now = options.now ?? Date.now;\n }\n\n /**\n * The feed entry for a `sid`, as the server computes it.\n *\n * Base64url without padding over the claim's EXACT string — never a parsed\n * and re-rendered UUID, or the answer depends on this SDK's parser rather\n * than on the feed.\n */\n static entryFor(sid: string): string {\n return createHash('sha256').update(sid, 'utf8').digest('base64url');\n }\n\n /**\n * Has this session been revoked, as far as this poller knows?\n *\n * `false` whenever the answer is not a confident yes — a feed never fetched,\n * unreachable, malformed, or simply not listing this session. The caller\n * admits the request in all of those cases, which is §10.4 rule 3 and is the\n * whole reason the feature is safe to turn on.\n *\n * Never blocks on the network beyond the first call: once the cache is warm,\n * a stale cache starts a refresh and this answers from what it currently\n * has.\n */\n async isRevoked(sid: string): Promise<boolean> {\n await this.#refreshIfStale();\n return this.#entries?.has(RevocationFeed.entryFor(sid)) ?? false;\n }\n\n /** Fetch now, whatever the interval says. For tests, and for warming. */\n async refresh(): Promise<void> {\n this.#inFlight ??= this.#doRefresh().finally(() => {\n this.#inFlight = undefined;\n });\n await this.#inFlight;\n }\n\n async #refreshIfStale(): Promise<void> {\n const last = this.#lastAttempt;\n if (last !== undefined && this.#now() - last < this.#pollIntervalMs) {\n return;\n }\n await this.refresh();\n }\n\n async #doRefresh(): Promise<void> {\n this.#lastAttempt = this.#now();\n const fetched = await this.#fetchOnce();\n if (fetched !== undefined) {\n this.#entries = fetched;\n }\n // On failure the previous set is deliberately left in place: a blip must\n // not un-revoke a session the guard already knows about.\n }\n\n /**\n * One fetch. `undefined` for every kind of failure, which the caller treats\n * identically — see the file header on why \"unusable\" must not collapse into\n * \"empty\".\n */\n async #fetchOnce(): Promise<Set<string> | undefined> {\n try {\n const response = await this.#fetchImpl(this.#feedUrl, { method: 'GET' });\n if (!response.ok) {\n return undefined;\n }\n const document: unknown = await response.json();\n if (typeof document !== 'object' || document === null) {\n return undefined;\n }\n const { alg, revoked } = document as { alg?: unknown; revoked?: unknown };\n if (alg !== SUPPORTED_ALG) {\n return undefined;\n }\n if (!Array.isArray(revoked) || revoked.length > MAX_ENTRIES) {\n return undefined;\n }\n return new Set(revoked.filter((e): e is string => typeof e === 'string'));\n } catch {\n return undefined;\n }\n }\n}\n","// Public types for the OIDC / SSO relying-party helpers (CONTRACT.md §12.1).\n//\n// Naming convention used throughout — deliberate, and worth copying verbatim\n// into the other SDKs so the eight implementations stay legible as one family:\n//\n// * Types that ARE a protocol document keep their wire spelling in\n// snake_case: `OidcConfiguration` (the OIDC Discovery 1.0 metadata\n// document) and `IdTokenClaims` (JWT claims). A caller cross-references\n// these field names against OIDC Core / RFC 8414, so renaming them would\n// be a lossy translation. `AxiamClaims` in node/jwks.ts already sets this\n// precedent.\n// * Types that are an SDK-shaped RESULT use the repo's camelCase public-API\n// convention (as `LoginResult` does): `OidcTokenSet`, `IntrospectionResult`,\n// `AuthorizationRequest`, `SsoStartResult`, `SsoCompleteResult`. These are\n// not verbatim wire objects — they carry `Sensitive<T>`-wrapped fields and\n// derived data (`idClaims`) that the wire body does not have.\n//\n// The five §12.5 secret fields — `access_token`, `refresh_token`, `id_token`,\n// `client_secret`, `code_verifier` — are `Sensitive<string>` wherever they\n// appear below. `state` and `nonce` are NOT secrets (§12.3 rule 2) and are\n// plain strings.\n\nimport type { Sensitive } from '../core/index.js';\nimport type { IdTokenClaims } from './oidcIdToken.js';\n\n// ---------------------------------------------------------------------------\n// Discovery\n// ---------------------------------------------------------------------------\n\n/**\n * RFC 8705 §5 `mtls_endpoint_aliases` — the seven endpoints re-based on the\n * host that performs the mutual-TLS handshake (wire schema\n * `MtlsEndpointAliases`, contract 1.40; the seventh, CIBA's\n * `backchannel_authentication_endpoint`, contract 1.58).\n *\n * @remarks\n * A TLS listener decides whether to request a client certificate during the\n * handshake, before it has seen any HTTP, so \"ask for a certificate on\n * `/oauth2/token` but not on `/oauth2/authorize`\" is not something one listener\n * can do. A deployment wanting both runs two, and this object is how the second\n * one is named.\n *\n * Only these seven are ever aliased. `authorization_endpoint` and\n * `end_session_endpoint` are front-channel and `jwks_uri` is public, so\n * CONTRACT.md §21.3 rule 2 forbids synthesising an alias for any of them —\n * sending a browser to an mTLS host raises a native certificate-chooser dialog\n * most users cannot answer. `issuer` is not aliased either, and §10.1 rule 3\n * still compares `iss` against it by exact string.\n *\n * Every member is optional even though the server's schema marks them\n * required. AXIAM builds them from one path through a shared macro and so\n * always publishes the complete set, but RFC 8705 §5 permits an OP to alias\n * fewer, and the shape of this member must never be why a client stops\n * working — the same principle rule 2 point 1 states for the object as a\n * whole, one level in. An absent entry falls back to the top-level endpoint of\n * the same name, exactly as an absent object does.\n */\nexport interface MtlsEndpointAliases {\n /** The mTLS token endpoint — RFC 8705 §2 client authentication and §3 the mint of a certificate-bound token. */\n token_endpoint?: string;\n /** The mTLS userinfo endpoint — OIDC Core §5.3, reached with an access token that may carry `cnf`. */\n userinfo_endpoint?: string;\n /** The mTLS revocation endpoint — RFC 7009 §2.1, which authenticates the client. */\n revocation_endpoint?: string;\n /** The mTLS introspection endpoint — RFC 7662 §2.1, which authenticates the caller. */\n introspection_endpoint?: string;\n /** The mTLS device authorization endpoint — RFC 8628 §3.1, which authenticates the client. */\n device_authorization_endpoint?: string;\n /** The mTLS pushed authorization request endpoint — RFC 9126 §2, which authenticates the client. */\n pushed_authorization_request_endpoint?: string;\n /**\n * The mTLS CIBA backchannel authentication endpoint — CIBA Core §7, which\n * authenticates the client (contract 1.58, §21.3.1: the **seventh** alias;\n * a `tls_client_auth` CIBA client has no other way to present its\n * certificate on a two-listener deployment).\n */\n backchannel_authentication_endpoint?: string;\n}\n\n/**\n * The OIDC Discovery 1.0 metadata document served by\n * `GET /.well-known/openid-configuration` (wire schema\n * `OidcDiscoveryDocument`). Every field is required by the server's schema.\n *\n * @remarks\n * `issuer` is the **authoritative** issuer for ID-token validation\n * (CONTRACT.md §12.4 rule 3). It may legitimately differ from the client's\n * `baseUrl` when AXIAM runs behind a proxy, so this SDK never rejects a\n * document on an issuer/base-URL mismatch (§12.3 rule 6). Likewise `jwks_uri`\n * is read from here rather than hardcoded.\n */\nexport interface OidcConfiguration {\n /** The authorization server's issuer identifier — the value an ID token's `iss` claim must equal exactly. */\n issuer: string;\n /** The authorization endpoint `oidcBegin` builds its redirect URL from. */\n authorization_endpoint: string;\n /** The token endpoint used by `oidcExchange`, `oidcRefresh` and `loginClientCredentials`. */\n token_endpoint: string;\n /** The userinfo endpoint. Advertised by the server but deliberately NOT called by any SDK (§12.3 rule 5). */\n userinfo_endpoint: string;\n /** URI of the JWKS document whose keys verify ID-token signatures (§12.4 rule 2). */\n jwks_uri: string;\n /** The RFC 7009 revocation endpoint used by `revoke`. */\n revocation_endpoint: string;\n /** The RFC 7662 introspection endpoint used by `introspect`. */\n introspection_endpoint: string;\n /** OAuth2 `response_type` values the server supports. */\n response_types_supported: string[];\n /** Subject identifier types the server supports. */\n subject_types_supported: string[];\n /** ID-token signing algorithms the server advertises. Informational only: §12.4 rule 1 pins verification to `EdDSA` regardless of what appears here. */\n id_token_signing_alg_values_supported: string[];\n /** Scopes the server supports. */\n scopes_supported: string[];\n /** Client-authentication methods the token endpoint supports (`client_secret_post`, §12.1 note 3). */\n token_endpoint_auth_methods_supported: string[];\n /** Claims the server may include in an ID token. */\n claims_supported: string[];\n /** Grant types the token endpoint supports. */\n grant_types_supported: string[];\n /**\n * RFC 8628 device authorization endpoint, used by `deviceAuthorize` (§14.1).\n *\n * Optional because a server that does not implement the device grant does\n * not advertise it, and because this document may come from a non-AXIAM OP.\n * Its absence is an error at call time, never a cue to build the URL by\n * concatenation.\n */\n device_authorization_endpoint?: string;\n /**\n * OIDC RP-Initiated Logout 1.0 `end_session_endpoint`, used by `logoutUrl`\n * (§12.7.2 rule 1).\n *\n * Optional for the same reason, and the rule is stricter here: §12.7.2\n * rule 1 forbids synthesising this URL from the issuer. Code that\n * concatenates works against AXIAM and breaks against every other OP the\n * same application is pointed at.\n */\n end_session_endpoint?: string;\n /**\n * RFC 9126 pushed authorization request endpoint, used by `oidcPar` (§26.1).\n *\n * Optional for the same reason as the two above, and with the same rule: its\n * absence is an error at call time, never a cue to build `<issuer>/oauth2/par`\n * by concatenation.\n */\n pushed_authorization_request_endpoint?: string;\n /**\n * RFC 7636 §4.3 / RFC 8414 §2 — the PKCE code-challenge methods the\n * authorization endpoint accepts. AXIAM publishes `[\"S256\"]` and only\n * `[\"S256\"]` (contract 1.42, §21.5).\n *\n * Informational only: this SDK implements S256 and nothing else, so it\n * neither negotiates against this list nor falls back to `plain` — `plain`\n * is not implemented anywhere here.\n *\n * **Optional even though the server's schema marks it required**, and the\n * reason is the same one §21.5 gives: *RFC 8414 defines no default for this\n * member, so its absence does not mean `S256`*. This struct must still parse\n * a document from a non-AXIAM OP that omits it, exactly as it does for every\n * other member modelled optional here.\n */\n code_challenge_methods_supported?: string[];\n /**\n * RFC 8414 §2 — the JWS algorithms the token endpoint accepts on a\n * `private_key_jwt` client assertion. AXIAM publishes\n * `[\"PS256\", \"ES256\", \"EdDSA\"]` (contract 1.42, §21.5).\n *\n * Informational only, and optional for the same reason as\n * {@link OidcConfiguration.code_challenge_methods_supported}: RFC 8414\n * defines no default, so absence is not a statement about what the OP\n * accepts.\n */\n token_endpoint_auth_signing_alg_values_supported?: string[];\n /**\n * RFC 8414 §2 — the client-authentication methods the revocation endpoint\n * accepts; AXIAM publishes the token endpoint's list (contract 1.60,\n * §21.5).\n *\n * Informational only, and optional: a server before 1.0.0 omits all four\n * revocation and introspection members, and RFC 8414 then reads this one\n * as `client_secret_basic` alone. Neither changes how `revoke`\n * authenticates — it keeps the method this client was configured with\n * (§12.1 rules 3 and 4).\n */\n revocation_endpoint_auth_methods_supported?: string[];\n /**\n * RFC 8414 §2 — the client-authentication methods the introspection\n * endpoint accepts; AXIAM publishes the token endpoint's list without\n * `none`, since introspection refuses a public client (contract 1.60,\n * §21.5). Informational and optional, as above.\n */\n introspection_endpoint_auth_methods_supported?: string[];\n /**\n * RFC 8414 §2 — the JWS algorithms a `private_key_jwt` assertion at the\n * revocation endpoint may use; equal to\n * {@link OidcConfiguration.token_endpoint_auth_signing_alg_values_supported}\n * on AXIAM (contract 1.60, §21.5). Informational and optional.\n */\n revocation_endpoint_auth_signing_alg_values_supported?: string[];\n /**\n * RFC 8414 §2 — the JWS algorithms a `private_key_jwt` assertion at the\n * introspection endpoint may use (contract 1.60, §21.5). Informational and\n * optional.\n */\n introspection_endpoint_auth_signing_alg_values_supported?: string[];\n /**\n * CIBA Core §4 — the backchannel authentication endpoint `cibaInitiate`\n * posts to (contract 1.58, §21.5, §33.1). Optional: its absence means the\n * server does not support CIBA, and is an error at call time, never a cue\n * to build `<issuer>/oauth2/bc-authorize` by concatenation.\n */\n backchannel_authentication_endpoint?: string;\n /**\n * CIBA Core §4 — the token delivery modes the server offers. AXIAM\n * publishes `[\"poll\", \"ping\"]`. A statement about the server: which mode a\n * given client holds is its registration's answer.\n */\n backchannel_token_delivery_modes_supported?: string[];\n /** CIBA Core §4 — AXIAM publishes `false`, and this SDK never sends a `user_code` (§33.3 rule 3). */\n backchannel_user_code_parameter_supported?: boolean;\n /** CIBA Core §4 — the algorithms a signed authentication request may use: `[\"PS256\", \"ES256\", \"EdDSA\"]` (§33.2). */\n backchannel_authentication_request_signing_alg_values_supported?: string[];\n /** Whether the OP sends back-channel logout tokens. */\n backchannel_logout_supported?: boolean;\n /** Whether those logout tokens carry `sid`. AXIAM always sends it. */\n backchannel_logout_session_supported?: boolean;\n /**\n * RFC 8705 §5 endpoint aliases for a deployment that terminates mutual TLS\n * on a host other than the issuer's own (contract 1.40, §21.3 rule 2).\n *\n * Optional, and **absence means \"no separate host\", not \"mTLS unsupported\"**:\n * a deployment running `client_auth = optional` on a single listener serves\n * both populations at the conventional endpoints and correctly publishes\n * nothing here. A client that treats absence as an error refuses the most\n * common mTLS topology AXIAM ships. The server omits the key rather than\n * serialising `null`.\n */\n mtls_endpoint_aliases?: MtlsEndpointAliases;\n}\n\n// ---------------------------------------------------------------------------\n// oidcBegin\n// ---------------------------------------------------------------------------\n\n/**\n * The result of `oidcBegin` — everything the caller needs to start an\n * authorization-code + PKCE login (CONTRACT.md §12.1).\n *\n * @remarks\n * **The caller owns this state** (§12.3 rule 1). The SDK stores nothing: it\n * keeps no copy of `state`, `nonce` or `codeVerifier` in process-global state\n * or any implicit cache. Persist all three in your own HTTP session (or in an\n * {@link OidcStateStore}), redirect the browser to {@link url}, and pass\n * `nonce` + `codeVerifier` back into `oidcExchange` when the code arrives.\n */\nexport interface AuthorizationRequest {\n /** The fully-built authorization URL to redirect the browser to. */\n url: string;\n /** CSPRNG CSRF value (≥128 bits, base64url unpadded) to compare against the `state` the IdP returns. Not a secret (§12.3 rule 2). */\n state: string;\n /** CSPRNG replay-protection value (≥128 bits) that must equal the ID token's `nonce` claim. Not a secret (§12.3 rule 2). */\n nonce: string;\n /** The PKCE verifier, secret for its whole lifetime (§12.5). Pass it back into `oidcExchange`. */\n codeVerifier: Sensitive<string>;\n}\n\n/**\n * Arguments to `oidcPar` (CONTRACT.md §26.1).\n *\n * The parameters come from an {@link AuthorizationRequest} that `oidcBegin`\n * already produced — §26.2 rule 1 forbids a second generator for `state`,\n * `nonce` and PKCE, and the `codeVerifier` the caller must keep for\n * `oidcExchange` is the one `oidcBegin` gave them.\n */\nexport interface OidcParParams {\n /** The request `oidcBegin` returned. Its `url` is replaced by {@link PushedAuthorizationRequest.authorizationUrl}. */\n request: AuthorizationRequest;\n /** The relying party's redirect URI — the same value that will be sent at `oidcExchange` (§26.2 rule 6). */\n redirectUri: string;\n /** Requested scope. `openid` is added when absent, exactly as `oidcBegin` does. */\n scope?: string | string[];\n /** The discovery document, for the `authorization_endpoint`. Fetched via `oidcDiscover` when omitted. */\n configuration?: OidcConfiguration;\n /** Tenant UUID override for the mandatory `?tenant_id=` query parameter (§12.1 note 2). */\n tenantId?: string;\n /**\n * RFC 9449 §10.1 `dpop_jkt` — the base64url SHA-256 JWK thumbprint of the\n * key the client will use for DPoP proofs on the eventual token request.\n * Sent in the pushed form **only when set**; omitted entirely otherwise\n * (§12.1: an absent optional field is absent, never empty).\n *\n * @remarks\n * **The caller supplies this value; the SDK does not derive it.** This SDK\n * implements the resource-server half of DPoP — §21.7.2 proof\n * *verification* — and ships no proof generator, so it holds no DPoP key to\n * take a thumbprint of. A client that does generate proofs computes the\n * thumbprint from its own public JWK and passes it here;\n * `jwkThumbprintS256` (exported from the node entry point) is there for\n * exactly that and produces the RFC 7638 value this parameter wants.\n *\n * Why it is worth pushing at all: without it the authorization code is bound\n * to a DPoP key only at the token request, so an attacker who steals the code\n * can redeem it with a key of their own. RFC 9449 §10 binds the code to the\n * key at authorization time instead, which is the point of pushing the\n * request over the back channel in the first place.\n */\n dpopJkt?: string;\n /**\n * The provider hint to push (contract 1.65, §26.2 rule 8): the same optional\n * `idpHint` {@link OidcBeginParams.idpHint} takes, validated the same way.\n * When set, the pushed form carries `axiam_idp_hint` exactly once; it is\n * absent otherwise. It rides the pushed body only — the authorization URL\n * built from the `request_uri` stays exactly `client_id` and `request_uri`.\n *\n * @remarks\n * When this is unset, the `axiam_idp_hint` that the `oidcBegin` URL\n * ({@link OidcParParams.request}) carries is pushed instead (D-N36); when\n * both are set, this argument wins and the URL's hint is not pushed.\n */\n idpHint?: string;\n}\n\n/**\n * The result of a pushed authorization request (CONTRACT.md §26.1).\n *\n * The server answered `201` — RFC 9126 §2.2 specifies Created, and a success\n * predicate written `status === 200` would treat every successful push as a\n * failure.\n */\nexport interface PushedAuthorizationRequest {\n /**\n * The authorization URL to redirect the browser to.\n *\n * Carries **exactly** `client_id` and `request_uri` and nothing else: the\n * server refuses a request that mixes a `request_uri` with inline\n * authorization parameters rather than merging them, because merging is\n * where parameter confusion lives (§26.2 rule 2).\n */\n authorizationUrl: string;\n /** The opaque, single-use handle. Wrapped per §26.5 — it is a bearer handle to a formed authorization request. */\n requestUri: Sensitive<string>;\n /** Seconds until `requestUri` expires. Not advisory (§26.2 rule 3). */\n expiresIn: number;\n /** The `state` from the pushed request, to compare against what the IdP returns. */\n state: string;\n /** The `nonce` from the pushed request, to compare against the ID token's claim. */\n nonce: string;\n /** The PKCE verifier to pass into `oidcExchange` — the same one `oidcBegin` produced. */\n codeVerifier: Sensitive<string>;\n}\n\n/** Arguments to `oidcBegin` (pure local computation — no network I/O). */\nexport interface OidcBeginParams {\n /** The discovery document, as returned by `oidcDiscover`. `authorization_endpoint` is taken from it and never hardcoded (§12.1 rule 5). */\n configuration: OidcConfiguration;\n /** The relying party's redirect URI, echoed back into `oidcExchange` unchanged. */\n redirectUri: string;\n /** Requested scope, as a string or an array. `openid` is added automatically when absent (§12.1 rule 4). Defaults to `openid`. */\n scope?: string | string[];\n /**\n * Extra authorization-request parameters (e.g. `prompt`, `login_hint`,\n * `ui_locales`). §12.1 rule 5 allows caller-supplied additions but forbids\n * the SDK from adding any of its own beyond the mandated eight, so\n * attempting to override one of those eight throws.\n */\n extraParams?: Record<string, string>;\n /**\n * Which sign-in provider to send the browser to (contract 1.65, §12.1\n * \"`idp_hint`\"): a provider's UUID, its `provider_slug` or a branded kind\n * name (`google`, `apple`, …). Emitted as the single query parameter\n * `axiam_idp_hint` — the ninth parameter of §12.1 rule 5 — and only when set.\n *\n * @remarks\n * Validated for emptiness and length only: an empty string or one longer\n * than 256 UTF-8 bytes throws a `ValidationError` and no URL is built. It is\n * never trimmed, case-folded, parsed as a UUID or looked up. An unresolvable\n * hint is ignored by the server, so there is nothing to handle on that\n * outcome. When set it replaces any `axiam_idp_hint` in `extraParams`\n * (emitted exactly once). There is no `kc_idp_hint` alias.\n */\n idpHint?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Token sets\n// ---------------------------------------------------------------------------\n\n/**\n * A token set returned by the OAuth2 token endpoint (wire schema\n * `TokenResponse`), returned by `oidcExchange`, `oidcRefresh` and\n * `loginClientCredentials`.\n *\n * @remarks\n * `accessToken`, `refreshToken` and `idToken` are {@link Sensitive} (§12.5):\n * `toString()`, `JSON.stringify()` and `console.log`/`util.inspect` all\n * redact them to `[SENSITIVE]`, and the raw value is reachable only through\n * the documented-`@internal` `expose()` accessor.\n *\n * `idClaims` is present exactly when `idToken` is, and holds the\n * **already-validated** claim set (§12.4) — validation happens before this\n * object is ever constructed, so an `OidcTokenSet` in your hands is never\n * partially trusted (§12.4 rule 7).\n */\nexport interface OidcTokenSet {\n /** The OAuth2 access token (§12.5 secret). */\n accessToken: Sensitive<string>;\n /** The token type the server issued (`Bearer`). */\n tokenType: string;\n /** Access-token lifetime in seconds from the time of the response. */\n expiresIn: number;\n /**\n * Granted scope, when the server narrowed or echoed it.\n *\n * On an `oidcRefresh` result this is the **refresh response's** scope and the\n * token's scope from then on — never the original grant's. The server\n * intersects a grant with the client's current registration at every\n * refresh, so it may be narrower (and carry no ID token once `openid` is\n * gone), permanently for that grant (contract 1.60, §12.1).\n */\n scope?: string;\n /** The refresh token, when the grant issued one (§12.5 secret). */\n refreshToken?: Sensitive<string>;\n /** The raw ID token, when the grant issued one (§12.5 secret). */\n idToken?: Sensitive<string>;\n /** The validated ID-token claims — present exactly when {@link idToken} is (§12.1, §12.4). */\n idClaims?: IdTokenClaims;\n}\n\n/** Arguments to `oidcExchange` (`grant_type=authorization_code`). */\nexport interface OidcExchangeParams {\n /** The authorization code the IdP redirected back with. */\n code: string;\n /** The verifier from the matching {@link AuthorizationRequest}. Accepts the `Sensitive` wrapper or a bare string (e.g. rehydrated from your own session store). */\n codeVerifier: Sensitive<string> | string;\n /** The same `redirect_uri` that was sent on the authorization request. */\n redirectUri: string;\n /** The `nonce` from the matching {@link AuthorizationRequest}. MANDATORY — §12.4 rule 6 is not optional for this grant. */\n nonce: string;\n /** Tenant UUID for the token endpoint's required `tenant_id` query parameter. Defaults to the client's configured `tenantId` when it was built in UUID form (§12.3 rule 4). */\n tenantId?: string;\n /** A pre-fetched discovery document, to avoid re-reading the (cached) one. Fetched via `oidcDiscover` when omitted. */\n configuration?: OidcConfiguration;\n}\n\n/** Arguments to `oidcRefresh` (`grant_type=refresh_token`). */\nexport interface OidcRefreshParams {\n /** The refresh token to redeem. Accepts the `Sensitive` wrapper or a bare string. */\n refreshToken: Sensitive<string> | string;\n /** Optional narrowed scope to request. Omitted from the form body when absent. */\n scope?: string;\n /** Tenant UUID for the `tenant_id` query parameter (§12.3 rule 4). */\n tenantId?: string;\n /** A pre-fetched discovery document. Fetched via `oidcDiscover` when omitted. */\n configuration?: OidcConfiguration;\n}\n\n/** Arguments to `loginClientCredentials` (`grant_type=client_credentials`). */\nexport interface LoginClientCredentialsParams {\n /** Optional scope to request. This grant requests no `openid` scope and the response carries no `id_token` (§12.1). */\n scope?: string;\n /** Tenant UUID for the `tenant_id` query parameter (§12.3 rule 4). */\n tenantId?: string;\n /** A pre-fetched discovery document. Fetched via `oidcDiscover` when omitted. */\n configuration?: OidcConfiguration;\n /**\n * Adopt the returned `access_token` as this client's bearer credential for\n * subsequent REST calls on the same session — the §12.1\n * \"`login_client_credentials` as a credential source\" allowance (a **MAY**,\n * hence opt-in and `false` by default).\n *\n * When `true` the token is held behind {@link Sensitive} inside a request\n * interceptor closure and emitted as `Authorization: Bearer …`; it is never\n * written to `axios.defaults`, a public property, or the cookie jar, so it\n * stays unreachable through any public getter (§12.3 rule 2).\n */\n adoptAsCredential?: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Introspection / revocation\n// ---------------------------------------------------------------------------\n\n/** Arguments to `introspect` (RFC 7662). Requires confidential-client credentials (§12.1 note 4). */\nexport interface IntrospectParams {\n /** The token to introspect. Accepts the `Sensitive` wrapper or a bare string. */\n token: Sensitive<string> | string;\n /** Optional RFC 7662 `token_type_hint` (`access_token` / `refresh_token`). */\n tokenTypeHint?: string;\n /** Tenant UUID for the `tenant_id` query parameter (§12.3 rule 4). */\n tenantId?: string;\n /** A pre-fetched discovery document. Fetched via `oidcDiscover` when omitted. */\n configuration?: OidcConfiguration;\n}\n\n/** Arguments to `revoke` (RFC 7009). Requires confidential-client credentials (§12.1 note 4). */\nexport interface RevokeParams {\n /** The token to revoke. Accepts the `Sensitive` wrapper or a bare string. */\n token: Sensitive<string> | string;\n /** Optional RFC 7009 `token_type_hint`. */\n tokenTypeHint?: string;\n /** Tenant UUID for the `tenant_id` query parameter (§12.3 rule 4). */\n tenantId?: string;\n /** A pre-fetched discovery document. Fetched via `oidcDiscover` when omitted. */\n configuration?: OidcConfiguration;\n}\n\n/**\n * The RFC 7662 introspection result (wire schema `IntrospectionResponse`).\n * Only `active` is guaranteed; the server omits the metadata fields for an\n * inactive token.\n */\nexport interface IntrospectionResult {\n /** Whether the token is currently active. */\n active: boolean;\n /** Subject the token was issued to. */\n sub?: string;\n /** Client the token was issued to. */\n clientId?: string;\n /** Scope granted to the token. */\n scope?: string;\n /** Token type (`Bearer`). */\n tokenType?: string;\n /** Expiry time, epoch seconds. */\n exp?: number;\n /** Issued-at time, epoch seconds. */\n iat?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Federation SSO (upstream IdP)\n// ---------------------------------------------------------------------------\n\n/** Arguments to `ssoStart` (`POST /api/v1/auth/federation/oidc/start`). */\nexport interface SsoStartParams {\n /** UUID of the server-side federation configuration identifying the upstream IdP. */\n federationConfigId: string;\n /** Post-login destination, stored server-side and echoed back by `ssoComplete`. */\n redirectUri: string;\n /** Tenant UUID. One tenant form (`tenantId` or `tenantSlug`) is required; defaults to the client's configuration (§5.1). */\n tenantId?: string;\n /** Tenant slug. Alternative to {@link tenantId}. */\n tenantSlug?: string;\n /** Organization UUID. One org form (`orgId` or `orgSlug`) is required; defaults to the client's configuration (§5.1). */\n orgId?: string;\n /** Organization slug. Alternative to {@link orgId}. */\n orgSlug?: string;\n}\n\n/**\n * The result of `ssoStart` (wire schema `OidcStartResponse`).\n *\n * @remarks\n * There is deliberately **no nonce**: on the federation path the nonce never\n * leaves the server (§12.1 note 7). Round-trip {@link state} into\n * `ssoComplete` unmodified — the server stores it single-use with a 10-minute\n * TTL and recovers the whole login context from it.\n */\nexport interface SsoStartResult {\n /** The upstream IdP authorization URL to redirect the browser to. */\n authorizeUrl: string;\n /** Single-use CSRF state to round-trip back into `ssoComplete` unmodified. */\n state: string;\n /** Remaining TTL of the server-side state row, in seconds (600 = 10 min). */\n expiresInSecs: number;\n}\n\n/** Arguments to `ssoComplete` (`POST /api/v1/auth/federation/oidc/callback`). */\nexport interface SsoCompleteParams {\n /** The `state` value the IdP redirected back with — must be the one `ssoStart` returned. */\n state: string;\n /** The authorization code the IdP redirected back with. */\n code: string;\n}\n\n/**\n * The result of `ssoComplete` (wire schema `SsoLoginSuccessResponse`).\n *\n * @remarks\n * Carries **no token material** — the session arrives as `Set-Cookie`, so the\n * §4 cookie jar is what actually captures it (§12.1 note 6). Use a Node\n * session (`createNodeSession`) or the session is silently lost.\n */\nexport interface SsoCompleteResult {\n /** The provisioned/linked user's UUID. */\n userId: string;\n /** The established session's UUID. */\n sessionId: string;\n /** Session/access-token lifetime in seconds. */\n expiresIn: number;\n /** The post-login destination that was stored during `ssoStart`. */\n redirectUri: string;\n}\n\n// ---------------------------------------------------------------------------\n// Public \"Sign in with X\" login providers (contract 1.38)\n// ---------------------------------------------------------------------------\n\n/**\n * `protocol` value selecting `ssoStart` (CONTRACT.md §12.1 note 10).\n */\nexport const PROTOCOL_OIDC_CONNECT = 'OidcConnect';\n\n/** `protocol` value selecting `ssoStartOauth2` (§12.1 note 10). */\nexport const PROTOCOL_OAUTH2 = 'OAuth2';\n\n/**\n * `protocol` value selecting the SAML login endpoint, which is **not** a §12\n * vocabulary operation (§12.1 note 10).\n */\nexport const PROTOCOL_SAML = 'Saml';\n\n/**\n * The query parameter the server delivers a handoff code in, on the SPA's own\n * callback URL (CONTRACT.md §12.1 note 12).\n */\nexport const HANDOFF_QUERY_PARAM = 'axiam_handoff';\n\n/**\n * How long a handoff code is valid, in seconds (§12.1 note 12).\n *\n * @remarks\n * It exists to survive one redirect. Redeem it immediately, once.\n */\nexport const HANDOFF_CODE_TTL_SECS = 60;\n\n/**\n * One sign-in button (wire schema `PublicFederationProvider`).\n *\n * @remarks\n * This is an **unauthenticated** response and carries only what a button\n * needs. There is no `client_id`, no `metadata_url`, no endpoint URL and no\n * secret — absent by construction rather than filtered out — and §12.1 note 9\n * forbids an SDK from expecting one.\n */\nexport interface FederationProvider {\n /**\n * Config id, to be echoed back to the matching start operation.\n *\n * Pass it through unmodified: inheritance is resolved server-side (§12.1\n * note 13) and this id is how the server is told what resolution produced.\n */\n id: string;\n /**\n * Which provider this is, for the button's branding — `google`, `github`,\n * `generic_oidc`, … **Not** what selects the start operation; see\n * {@link protocol}.\n */\n providerKind: string;\n /** The operator's display name for the provider. */\n displayName: string;\n /**\n * `OidcConnect`, `Saml` or `OAuth2` — the value that selects which start\n * operation to call (§12.1 note 10). Compare against\n * {@link PROTOCOL_OIDC_CONNECT}, {@link PROTOCOL_OAUTH2} and\n * {@link PROTOCOL_SAML}.\n *\n * Kept as the wire string rather than narrowed to a union the SDK enforces:\n * the server owns this vocabulary, and a value added server-side must not\n * become a parse failure for the whole list.\n *\n * An `OAuth2` provider issues **no ID token** — the server authenticates by\n * calling a configured userinfo endpoint, so there is no signature, no\n * `nonce` and no `aud` (§12.1 note 11). A surface rendering these buttons\n * SHOULD make that distinction visible rather than presenting the two as\n * equivalent.\n */\n protocol: string;\n /**\n * Whether AXIAM ships this provider's own sign-in mark, which its button\n * must then use. `false` for the generic kinds, whose buttons read \"Sign in\n * with `displayName`\" and use {@link buttonIcon} where one was uploaded.\n */\n hasBundledMark: boolean;\n /**\n * `true` when the provider is inherited from the organization rather than\n * configured on this tenant (§12.1 note 13). Informational — it is not\n * needed to sign in, and nothing in this SDK computes it.\n */\n inherited: boolean;\n /**\n * The operator's uploaded button icon as a bounded raster `data:` URL.\n *\n * `undefined` for most providers: present only for generic ones whose\n * operator uploaded a mark.\n */\n buttonIcon?: string;\n}\n\n/**\n * The result of `ssoProviders` (wire schema\n * `PublicFederationProvidersResponse`).\n *\n * @remarks\n * An **empty** {@link providers} is a normal success, never an error (§12.1\n * note 9).\n */\nexport interface FederationProviderList {\n /** The providers to offer, in a stable server-defined order. */\n providers: FederationProvider[];\n}\n\n/**\n * Arguments to `ssoProviders` (`GET /api/v1/auth/federation/providers`).\n *\n * @remarks\n * Every field is optional and all four travel as **query** parameters — this\n * is a `GET` with no body (§12.1). Unset forms fall back to the session's own\n * configuration (§5.1); when neither the arguments nor the session supply a\n * workspace the request is still sent, and still answers `200` with an empty\n * list.\n */\nexport interface SsoProvidersParams {\n /** Organization UUID. Alternative to {@link orgSlug}. */\n orgId?: string;\n /** Organization slug, as typed on a login page. */\n orgSlug?: string;\n /** Tenant UUID. Alternative to {@link tenantSlug}. */\n tenantId?: string;\n /** Tenant slug. Omitted or blank means the organization's own scope. */\n tenantSlug?: string;\n}\n\n/**\n * Arguments to `ssoStartOauth2` (`POST /api/v1/auth/federation/oauth2/start`).\n *\n * @remarks\n * Deliberately identical in shape to {@link SsoStartParams}, because the wire\n * schemas are: `OAuth2StartRequest` and `OidcStartRequest` differ in name\n * only. There is **no** PKCE field, and there must not be — the verifier is\n * generated and held server-side (§12.1 note 11).\n */\nexport interface SsoStartOauth2Params {\n /** UUID of the federation configuration, from {@link FederationProvider.id}. */\n federationConfigId: string;\n /**\n * The SPA callback route. Sent to the provider verbatim, so it must match\n * what is registered there byte for byte.\n */\n redirectUri: string;\n /** Tenant UUID; defaults to the session's configuration (§5.1). */\n tenantId?: string;\n /** Tenant slug. Alternative to {@link tenantId}. */\n tenantSlug?: string;\n /** Organization UUID; defaults to the session's configuration (§5.1). */\n orgId?: string;\n /** Organization slug. Alternative to {@link orgId}. */\n orgSlug?: string;\n}\n\n/**\n * Arguments to `ssoCompleteOauth2`\n * (`POST /api/v1/auth/federation/oauth2/callback`).\n */\nexport interface SsoCompleteOauth2Params {\n /** The `state` the provider redirected back with — the one `ssoStartOauth2` returned, unmodified. */\n state: string;\n /** The authorization code the provider redirected back with. */\n code: string;\n}\n\n/**\n * Arguments to `ssoCompleteHandoff` (`POST /api/v1/auth/federation/handoff`).\n */\nexport interface SsoCompleteHandoffParams {\n /**\n * The single-use code read from the {@link HANDOFF_QUERY_PARAM} query\n * parameter on the SPA's callback URL.\n *\n * Valid for {@link HANDOFF_CODE_TTL_SECS} seconds and redeemable **once**.\n */\n code: string;\n}\n\n// ---------------------------------------------------------------------------\n// Wire types (snake_case, mirror the server schemas verbatim)\n// ---------------------------------------------------------------------------\n\n/** 200 body of `POST /oauth2/token` (wire schema `TokenResponse`). */\nexport interface TokenResponseWire {\n access_token: string;\n token_type: string;\n expires_in: number;\n scope?: string | null;\n refresh_token?: string | null;\n id_token?: string | null;\n}\n\n/** 200 body of `POST /oauth2/introspect` (wire schema `IntrospectionResponse`). */\nexport interface IntrospectionResponseWire {\n active: boolean;\n sub?: string | null;\n client_id?: string | null;\n scope?: string | null;\n token_type?: string | null;\n exp?: number | null;\n iat?: number | null;\n}\n\n/** 200 body of `POST /api/v1/auth/federation/oidc/start` (wire schema `OidcStartResponse`). */\nexport interface OidcStartResponseWire {\n authorize_url: string;\n state: string;\n expires_in_secs: number;\n}\n\n/** 200 body of `POST /api/v1/auth/federation/oidc/callback` (wire schema `SsoLoginSuccessResponse`). */\nexport interface SsoLoginSuccessResponseWire {\n user_id: string;\n session_id: string;\n expires_in: number;\n redirect_uri: string;\n}\n\n/** One item of `GET /api/v1/auth/federation/providers` (wire schema `PublicFederationProvider`). */\nexport interface PublicFederationProviderWire {\n id: string;\n provider_kind: string;\n display_name: string;\n protocol: string;\n has_bundled_mark: boolean;\n inherited: boolean;\n button_icon?: string | null;\n}\n\n/** 200 body of `GET /api/v1/auth/federation/providers` (wire schema `PublicFederationProvidersResponse`). */\nexport interface PublicFederationProvidersResponseWire {\n providers: PublicFederationProviderWire[];\n}\n\n/**\n * 200 body of `POST /api/v1/auth/federation/oauth2/start` (wire schema\n * `OAuth2StartResponse`).\n *\n * @remarks\n * The PKCE verifier is **not** here and never will be: it stays server-side in\n * the login-state row, for the same reason the OIDC `nonce` does (§12.1\n * note 11).\n */\nexport interface OAuth2StartResponseWire {\n authorize_url: string;\n state: string;\n expires_in_secs: number;\n}\n\n// ---------------------------------------------------------------------------\n// §14 Device Authorization Grant (RFC 8628)\n// ---------------------------------------------------------------------------\n\n/** Arguments to `deviceAuthorize` (CONTRACT.md §14.1). */\nexport interface DeviceAuthorizeParams {\n /** Scopes to request, as a string or array. */\n scope?: string | string[];\n /** Tenant UUID for the mandatory `tenant_id` query parameter (§12.1 note 2). */\n tenantId?: string;\n /** A pre-fetched discovery document; fetched via `oidcDiscover` when absent. */\n configuration?: OidcConfiguration;\n}\n\n/**\n * The `DeviceAuthorizationResponse` — what the device shows its user, plus the\n * `device_code` it polls with.\n *\n * @remarks\n * `deviceCode` is {@link Sensitive} (§14.5): a bearer credential for the\n * lifetime of the grant. `userCode` deliberately is **not** — it exists to be\n * read aloud and typed by a human, and wrapping it would defeat the one thing\n * it is for. Neither may be logged; displaying `userCode` is the caller's job.\n */\nexport interface DeviceAuthorization {\n /** The device's polling credential (§14.5 secret). */\n deviceCode: Sensitive<string>;\n /** The short code the human types into the verification page. */\n userCode: string;\n /** Where the human goes to enter {@link DeviceAuthorization.userCode}. */\n verificationUri: string;\n /**\n * The verification URI with the user code already embedded, when the server\n * sent one — prefer it when the device can render a QR code.\n *\n * Never synthesised by concatenation when absent (§14.3): its format is the\n * server's to choose.\n */\n verificationUriComplete?: string;\n /** Seconds until the grant expires. Polling stops here (§14.2 rule 4). */\n expiresIn: number;\n /** Seconds between polls, from the response, defaulted to 5 s when omitted. */\n interval: number;\n}\n\n/** Arguments to `devicePoll` (CONTRACT.md §14.1). */\nexport interface DevicePollParams {\n /** The `deviceCode` from {@link DeviceAuthorization}. */\n deviceCode: Sensitive<string> | string;\n /** Tenant UUID for the `tenant_id` query parameter. */\n tenantId?: string;\n /** A pre-fetched discovery document. */\n configuration?: OidcConfiguration;\n}\n\n/** Arguments to `deviceLogin` (CONTRACT.md §14.3). */\nexport interface DeviceLoginParams {\n /** Scopes to request. */\n scope?: string | string[];\n /** Tenant UUID for the `tenant_id` query parameter. */\n tenantId?: string;\n /** A pre-fetched discovery document. */\n configuration?: OidcConfiguration;\n /**\n * Called with the {@link DeviceAuthorization} **before the first poll**\n * (§14.3 rule 2), so the caller can display the code. The SDK never prints\n * it: what the device does with it is the application's decision.\n */\n onUserCode: (authorization: DeviceAuthorization) => void | Promise<void>;\n /**\n * The clock the polling loop waits on and measures the `expires_in` deadline\n * against (§14.2 rule 4); defaults to `Date.now` and `setTimeout`. Injectable\n * so the schedule is testable without sleeping.\n */\n clock?: CibaClock;\n}\n\n/** 200 body of `POST /oauth2/device_authorization`. */\nexport interface DeviceAuthorizationResponseWire {\n device_code: string;\n user_code: string;\n verification_uri: string;\n verification_uri_complete?: string | null;\n expires_in: number;\n interval?: number | null;\n}\n\n/**\n * **201** body of `POST /oauth2/par` (CONTRACT.md §26.1).\n *\n * RFC 9126 §2.2 specifies Created, not OK — a success predicate written\n * `status === 200` treats every successful push as a failure.\n */\nexport interface PushedAuthorizationResponseWire {\n request_uri: string;\n expires_in: number;\n}\n\n// ---------------------------------------------------------------------------\n// §15 Token Exchange (RFC 8693)\n// ---------------------------------------------------------------------------\n\n/**\n * Arguments to `tokenExchange` (CONTRACT.md §15.1).\n *\n * @remarks\n * `subjectToken` is the only required field; everything else is optional and\n * **named**, because four optional strings in positional order is a bug\n * waiting to be written (§15.1).\n */\nexport interface TokenExchangeParams {\n /** The token being exchanged (§15.5 secret). */\n subjectToken: Sensitive<string> | string;\n /**\n * What kind of token `subjectToken` is. **Required** (§15.1).\n *\n * @remarks\n * There is no default. A defaulted type would be the SDK choosing which kind\n * of credential you are holding, which is exactly what §15.7 forbids — so\n * TypeScript refuses the call at compile time instead.\n *\n * Pass `ACCESS_TOKEN_TYPE` for the same-domain exchange of §15.1, or\n * `JWT_TOKEN_TYPE` for a trusted external issuer's JWT (§15.7).\n *\n * The SDK never reads `subjectToken` to decide this value (§15.7). Which\n * kind of token you hold is something only you know; AXIAM refuses refresh\n * and ID token types by name, and the SDK will not retry a refusal as a\n * different type.\n */\n subjectTokenType: string;\n /**\n * The acting party, when this is a **delegation** (§15.2 rule 1).\n *\n * Its absence selects **impersonation** — a different operation with\n * different risk. The SDK never fills this in for you.\n *\n * It must have been issued to the exchanging client (§15.2 rule 9, contract\n * 1.60): the usual actor is **the same client's own `client_credentials`\n * token** — `(await oidc.loginClientCredentials()).accessToken`. A token\n * issued to another client, a console sign-in or a service account is\n * answered `invalid_request` (\"actor_token was not issued to the exchanging\n * client\"), which is surfaced unchanged and never retried or dropped.\n */\n actorToken?: Sensitive<string> | string;\n /** Scopes to request. Omitted from the body when absent. */\n scopes?: string[];\n /** The service the issued token is for. */\n audience?: string;\n /** RFC 8707 synonym of `audience`; the server refuses the pair when they disagree. */\n resource?: string;\n /** Tenant UUID for the `tenant_id` query parameter. */\n tenantId?: string;\n /** A pre-fetched discovery document. */\n configuration?: OidcConfiguration;\n}\n\n/**\n * The result of an exchange (wire schema `TokenExchangeResponse`).\n *\n * @remarks\n * **There is no `refreshToken` field, and that is deliberate** (§15.2 rule 4).\n * RFC 8693 issues none, so the type cannot represent one: an application that\n * wants a fresh exchanged token re-runs the exchange. This result also never\n * enters the §9 single-flight refresh guard — there is nothing to refresh.\n */\nexport interface ExchangedToken {\n /** The issued token (§15.5 secret). */\n accessToken: Sensitive<string>;\n /**\n * What the server actually issued. Mandatory in RFC 8693 §2.2.1 and\n * surfaced rather than dropped (§15.2 rule 6), so a client that asked for\n * one type and got another can tell.\n */\n issuedTokenType: string;\n /** The token type (`Bearer`). */\n tokenType: string;\n /** Lifetime in seconds — never longer than the subject token's remaining life. */\n expiresIn: number;\n /**\n * **The granted scope, which may be narrower than requested** even on\n * success (§15.2 rule 7). Read it rather than assuming the request was\n * honoured verbatim.\n */\n scope?: string;\n}\n\n/** 200 body of a token-exchange `POST /oauth2/token`. */\nexport interface TokenExchangeResponseWire {\n access_token: string;\n issued_token_type: string;\n token_type: string;\n expires_in: number;\n scope?: string | null;\n}\n\n// ---------------------------------------------------------------------------\n// §12.7 Logout helpers\n// ---------------------------------------------------------------------------\n\n/** Arguments to `logoutUrl` (CONTRACT.md §12.7.2). */\nexport interface LogoutUrlParams {\n /**\n * A previously-issued ID token, placed in `id_token_hint` — the only\n * *authenticated* statement of which session is being ended.\n */\n idToken: Sensitive<string> | string;\n /**\n * Where the OP should send the browser afterwards. Honoured only on exact\n * match against the client's registered allow-list — a server-side check the\n * SDK deliberately does not duplicate (§12.7.2 rule 3).\n */\n postLogoutRedirectUri?: string;\n /**\n * An opaque value echoed back on the redirect. Generated and checked by the\n * caller (§12.7.2 rule 2), never by the SDK.\n */\n state?: string;\n /** A pre-fetched discovery document. */\n configuration?: OidcConfiguration;\n}\n\n/**\n * What a verified logout token names (§12.7.3).\n *\n * @remarks\n * Deliberately **not** a bare boolean: the RP has to know *which* session to\n * end, and a verifier that only says \"valid\" would force the caller to\n * re-parse the token themselves, with none of the checks this type is proof\n * of.\n */\nexport interface VerifiedLogoutToken {\n /**\n * The session that ended. **When present, end only this session** — falling\n * back to \"every session for `sub`\" is over-reach the AXIAM server itself\n * refuses to make.\n */\n sid?: string;\n /** The subject whose session ended. */\n sub?: string;\n /**\n * Replay identifier.\n *\n * **The RP dedups on this, not the SDK.** Back-channel delivery is\n * at-least-once with retry, so a valid token legitimately arrives twice; the\n * SDK has no durable store and an in-memory guard would silently drop a real\n * second logout after a restart. Surfaced, never consumed.\n */\n jti: string;\n}\n\n// ---------------------------------------------------------------------------\n// §20 UMA 2.0 — Protection API and ticket grant\n// ---------------------------------------------------------------------------\n\n/**\n * A UMA resource set — an AXIAM resource seen through the Protection API\n * (CONTRACT.md §20.1).\n *\n * `_id` is **the AXIAM resource id**, not a parallel identifier: the same UUID\n * is directly usable as the `resourceId` of a later {@link RequestedPermission},\n * and as the resource id anywhere else in this SDK.\n */\nexport interface ResourceSet {\n /** Assigned by the server on registration; absent on the way in. */\n id?: string;\n /** Human-readable name, shown in the admin UI. */\n name: string;\n /**\n * Free-form resource type. Defaults server-side to `uma_resource` when\n * omitted, so a resource server that leaves it out does not produce a row\n * that sorts oddly next to hand-made ones.\n */\n type?: string;\n /**\n * The scope names a resource server may ask for on this resource.\n *\n * **Replaced wholesale by an update, never merged** (§20.2 rule 8). This SDK\n * does not read the current scopes and fold them into an update payload as a\n * convenience — doing so would make removing a scope impossible through it.\n */\n resourceScopes?: string[];\n}\n\n/** One `(resource, scopes)` pair a resource server requires (§20.1). */\nexport interface RequestedPermission {\n /** The AXIAM resource id — the same UUID the Protection API returned as `_id`. */\n resourceId: string;\n /**\n * Scope names, each of which the resource must already declare. Matched\n * exactly: no prefix or wildcard semantics in either direction.\n */\n resourceScopes: string[];\n}\n\n/**\n * One entry of an RPT's `permissions` claim.\n *\n * **A record of a decision already made, not a live authorization answer**\n * (§20.2 rule 7). These are the pairs the engine allowed when the RPT was\n * minted; a grant revoked afterwards does not empty a live RPT. Do not cache\n * them beyond the token's own expiry — which is why that expiry is short.\n */\nexport interface RptPermission {\n resourceId: string;\n resourceScopes: string[];\n /** Absolute expiry, seconds since the epoch. */\n exp: number;\n}\n\n/**\n * A Requesting Party Token (§20.1).\n *\n * **There is no `refreshToken` field, and that is deliberate** (§20.2 rule 5).\n * The grant issues none, so an RPT cannot outlive the ticket that authorised\n * it; an application that wants a fresh one re-runs the grant. This result\n * never enters the §9 single-flight refresh guard — there is nothing to refresh.\n */\nexport interface RequestingPartyToken {\n /** The RPT itself (§20.6 secret). */\n accessToken: Sensitive<string>;\n /** Always `Bearer`. */\n tokenType: string;\n /** `min(claimToken remaining, server ceiling, 300 s)`. */\n expiresIn: number;\n}\n\n/**\n * A parsed `WWW-Authenticate: UMA` challenge (§20.3).\n */\nexport interface UmaChallenge {\n /** The protection realm the resource server named. */\n realm?: string;\n /**\n * The authorization server the resource server nominates.\n *\n * **Not automatically trusted.** See `umaParseChallenge`.\n */\n asUri?: string;\n /** The ticket to exchange — a bearer credential for its 60-second life. */\n ticket?: Sensitive<string>;\n}\n\n/** Arguments to `umaExchangeTicket` (§20.1). */\nexport interface UmaExchangeTicketParams {\n /** The permission ticket, from `umaRequestTicket` or a parsed challenge. */\n ticket: Sensitive<string> | string;\n /**\n * The requesting party's access token.\n *\n * **Required**, though UMA 2.0 §3.3.1 marks it optional: v1 implements\n * neither incremental authorization nor claims-gathering, so this is the only\n * channel that names a requesting party (§20.2 rule 2).\n */\n claimToken: Sensitive<string> | string;\n /** Tenant UUID for the `tenant_id` query parameter. */\n tenantId?: string;\n /** A pre-fetched discovery document. */\n configuration?: OidcConfiguration;\n}\n\n/** Wire shape of a resource set (snake_case, as the server sends it). */\nexport interface ResourceSetWire {\n _id?: string;\n name: string;\n type?: string;\n resource_scopes?: string[];\n}\n\n/** Wire shape of the RPT the ticket grant returns. */\nexport interface RptResponseWire {\n access_token: string;\n token_type: string;\n expires_in: number;\n}\n\n// ---------------------------------------------------------------------------\n// §33 CIBA — client-initiated backchannel authentication (contract 1.58)\n// ---------------------------------------------------------------------------\n\n/**\n * Whom `cibaInitiate` asks AXIAM to authenticate: **exactly one** hint\n * (§33.2). The type makes both, or neither, unwritable; a JavaScript caller\n * that builds one anyway is refused locally with a `ValidationError`.\n * `login_hint_token` is not offered (§33.3 rule 3).\n */\nexport type CibaUserHint =\n | {\n /** A username, then an e-mail address, within the tenant. Personal data: never logged by the SDK. */\n loginHint: string;\n /** Not with `loginHint`. */\n idTokenHint?: never;\n }\n | {\n /** An ID token this deployment issued to this client; it names the user only. */\n idTokenHint: string;\n /** Not with `idTokenHint`. */\n loginHint?: never;\n };\n\n/**\n * How the client receives the outcome, as it registered (§33.3 rule 1).\n * Poll is the default; push is not offered (the server does not).\n */\nexport type CibaDelivery =\n | {\n /** The client polls the token endpoint (`cibaAwait`). */\n mode: 'poll';\n }\n | {\n /** AXIAM pings the client's registered notification endpoint, then the client polls once. */\n mode: 'ping';\n /**\n * The bearer AXIAM presents at the ping; keep it to check the ping with\n * `cibaHandlePing`. Required and non-empty (1–1 024 visible ASCII; at least\n * 22 for a `fapi2` client). Never returned by AXIAM.\n */\n clientNotificationToken: Sensitive<string>;\n };\n\n/** The algorithms a signed CIBA request may use (§33.2). */\nexport type CibaSigningAlg = 'PS256' | 'ES256' | 'EdDSA';\n\n/**\n * Arguments to `cibaInitiate` (§33.2 `CibaInitiateRequest`).\n *\n * Exactly the members set are sent. `bindingMessage` and `loginHint` can be\n * personal data: the SDK never logs them. There is no parameter for\n * `login_hint_token`, `user_code` or `request_uri` — AXIAM refuses each\n * (§33.3 rule 3) — and no channel for any other form parameter.\n */\nexport type CibaInitiateParams = CibaUserHint & {\n /** Space-separated; must include `openid` (the server checks; the SDK does not pre-validate, §33.3 rule 5). */\n scope: string;\n /** Shown to the user on the approval page — what lets them tell the request they started from an attacker's. Required for a `fapi2` client. */\n bindingMessage?: string;\n /** The requested lifetime in seconds, 30–600 (absent: 300). Sent as a string on the form, as a number inside a signed request. */\n requestedExpiry?: number;\n /** Space-separated authentication context classes. */\n acrValues?: string;\n /** RFC 8707 resource indicator. */\n resource?: string;\n /** Poll (default) or ping, as registered. */\n delivery?: CibaDelivery;\n /**\n * Send the request as one signed JWT (`request`, CIBA Core §7.1.1) —\n * required of a client that registered\n * `backchannel_authentication_request_signing_alg`, refused from one that\n * did not. Build it with `CibaRequestSigner.create`.\n */\n signer?: import('./oidc.js').CibaRequestSigner;\n /** Tenant UUID for the `tenant_id` query parameter (§12.3 rule 4). */\n tenantId?: string;\n /** A pre-fetched discovery document. */\n configuration?: OidcConfiguration;\n};\n\n/**\n * `CibaInitiateResponse` (§33.2), plus when it was received.\n *\n * **A successful initiate proves nothing about the user** (§33.3 rule 4):\n * AXIAM answers a hint that names nobody, a locked user and a real one\n * identically. The only signal that a user did not answer is `expired_token`.\n */\nexport interface CibaInitiateResponse {\n /** The request's id at the token endpoint — a bearer credential for the grant (§33.5). Never parse or length-check it. */\n authReqId: Sensitive<string>;\n /** The request's lifetime in seconds — authoritative (§33.7 rule 4). */\n expiresIn: number;\n /** The minimum seconds between token requests: the response's value, or 5 when it was absent or zero (§33.7 rule 2). */\n interval: number;\n /** When the response was received, in epoch milliseconds; `cibaAwait`'s deadline is this plus `expiresIn`. */\n receivedAt: number;\n}\n\n/** Arguments to `cibaPoll`. */\nexport interface CibaPollParams {\n /** The `auth_req_id` from {@link CibaInitiateResponse} or a ping. */\n authReqId: Sensitive<string>;\n /** Tenant UUID for the `tenant_id` query parameter. */\n tenantId?: string;\n /** A pre-fetched discovery document. */\n configuration?: OidcConfiguration;\n}\n\n/**\n * The clock `cibaAwait` waits on — injectable so its schedule is testable\n * without sleeping (§33.8 tests 6 and 7).\n */\nexport interface CibaClock {\n /** The current time, epoch milliseconds. */\n now(): number;\n /** Wait `ms` milliseconds. */\n sleep(ms: number): Promise<void>;\n}\n\n/** Arguments to `cibaAwait`. */\nexport interface CibaAwaitParams {\n /** Tenant UUID for the `tenant_id` query parameter. */\n tenantId?: string;\n /** A pre-fetched discovery document. */\n configuration?: OidcConfiguration;\n /** The clock to wait on; defaults to `Date.now` and `setTimeout`. */\n clock?: CibaClock;\n}\n\n/**\n * The request headers `cibaHandlePing` accepts, in whichever shape the HTTP\n * framework hands them over:\n *\n * - Node's `req.rawHeaders` (a flat `[name, value, name, value, …]` array) —\n * **prefer it**: `req.headers` silently drops a duplicated `Authorization`,\n * which §33.1 requires refusing;\n * - an iterable of `[name, value]` pairs (a fetch `Headers`, a `Map`);\n * - a header record (`req.headers`), a value possibly an array.\n */\nexport type CibaPingHeaders =\n | readonly string[]\n | Iterable<readonly [string, string]>\n | Record<string, string | readonly string[] | undefined>;\n\n// ---------------------------------------------------------------------------\n// Native sign-in with a provider ID token (CONTRACT.md §37, contract 1.65)\n// ---------------------------------------------------------------------------\n\n/** Options of `OidcClient.loginWithProviderIdToken` beyond its three positional inputs (§37.1). */\nexport interface LoginWithProviderIdTokenOptions {\n /**\n * Scopes to request, sent space-joined as `scope`. Sent **only when named**:\n * an omitted or empty list sends no `scope` field, which the server reads as\n * the empty set — no `openid`, hence no `id_token` in the response. The SDK\n * adds no scope of its own (§37.2 rule 7); pass `openid` to receive\n * `idClaims`.\n */\n scopes?: readonly string[];\n /** An RFC 8707 `resource` indicator. Sent only when set. */\n resource?: string;\n /** Tenant UUID for the `tenant_id` query parameter (§12.3 rule 4). A slug-only client must pass it. */\n tenantId?: string;\n /** A pre-fetched discovery document. Fetched via `oidcDiscover` when omitted. */\n configuration?: OidcConfiguration;\n}\n\n/**\n * The pair {@link nativeNonce} returns (CONTRACT.md §37.4): give `hashed` to\n * the provider's SDK and `raw` to `loginWithProviderIdToken`.\n */\nexport interface ProviderNonce {\n /**\n * The raw nonce: at least 32 CSPRNG bytes, base64url without padding. A\n * credential (§37.6) — held behind {@link Sensitive}, and to be kept only for\n * the length of the sign-in attempt.\n */\n raw: Sensitive<string>;\n /** `SHA-256(raw)` as 64 lower-case hexadecimal characters; not a secret. */\n hashed: string;\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/authz.ts","../../src/middleware/authzCore.ts","../../src/middleware/cookieHeader.ts","../../src/management/errors.ts","../../src/middleware/mcpCore.ts","../../src/node/oidcState.ts","../../src/middleware/oidcLoginCore.ts","../../src/node/oidcIdToken.ts","../../src/node/jwks.ts","../../src/middleware/peerCertificate.ts","../../src/middleware/verifyCore.ts","../../src/middleware/express.ts","../../src/middleware/fastify.ts","../../src/rest/bareTransport.ts","../../src/rest/interceptors.ts","../../src/rest/retry.ts","../../src/rest/session.ts","../../src/node/oidcPkce.ts","../../src/node/oidc.ts","../../src/node/revocationFeed.ts","../../src/node/oidcTypes.ts"],"names":["retryAfterMs","timingSafeEqual","document","invalidRequestBody","LOOPBACK_HOSTS","createHash","randomBytes","authzDeniedBody","missingCredentialsBody","invalidTokenBody","csrfDeniedBody","sendOidcOutcome","sleep","UUID_RE","fetch","NODE_INSPECT_CUSTOM","refuse","constantTimeEqual"],"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,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,UAAA,CAAU,SAAS,CAAA;AAAA,EACjD;AACF,CAAA;AA0CO,IAAM,kBAAA,GAAN,MAAM,mBAAA,SAA2B,SAAA,CAAU;AAAA;AAAA,EAEvC,KAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,gBAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,YAAA;AAAA,EAET,WAAA,CAAY,KAAA,EAAe,gBAAA,GAA2B,EAAA,EAAIA,aAAAA,EAAuB;AAG/E,IAAA,KAAA,CAAM,m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y (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 /**\n * The server's human-readable `error_description`. Never contains token\n * material. Empty when the server sent none: RFC 6749 §5.2 makes the member\n * OPTIONAL, and §2 (contract 1.53, §28.12.3) dispatches on `error` alone.\n */\n readonly errorDescription: string;\n /**\n * The server's `Retry-After` in milliseconds, when this error is a `429` that carried one in\n * delta-seconds form (contract 1.65 §37.3, C165-17). Absent otherwise; an HTTP-date is not read.\n * Additive: honour it before retrying a rate-limited native sign-in or CIBA call.\n */\n readonly retryAfterMs?: number;\n\n constructor(error: string, errorDescription: string = '', retryAfterMs?: number) {\n // `\"<error>: <error_description>\"`, or just `\"<error>\"` when the server\n // sent no description — never a dangling `\": \"`.\n super(errorDescription ? `${error}: ${errorDescription}` : error);\n this.name = 'OAuthProtocolError';\n this.error = error;\n this.errorDescription = errorDescription;\n if (retryAfterMs !== undefined) this.retryAfterMs = retryAfterMs;\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 /**\n * What is safe to keep of the underlying transport error: its name, message,\n * code and status, and the response's status, body and allow-listed headers\n * (§2, X-3). Never the request — its body or its headers — which may carry a\n * write-only secret (contract 1.59 R-18).\n */\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 * The tolerant `/oauth2/*` error decoder (CONTRACT.md §2, §28.12.3, §33.4):\n * an {@link OAuthProtocolError} for any body that is an object carrying a\n * **non-empty string `error`**, whatever the status, with `error_description`\n * used when it is a string and left empty otherwise.\n *\n * Distinct from {@link isOAuth2ErrorBody}, which requires both members and\n * gates the two status-qualified rows of {@link mapHttpStatusToError}: those\n * rows are unchanged. This is for the call paths whose contract text says to\n * dispatch on `error` at any status — the RFC 7592 client-configuration\n * operations (a `401 {\"error\":\"invalid_token\"}` carries no description) and\n * CIBA (a `429 {\"error\":\"rate_limit_exceeded\"}`).\n *\n * Returns `undefined` for anything else, so the caller falls back to §2's\n * status rows.\n */\nexport function oauth2ErrorFromBody(body: unknown, retryAfterMs?: number): OAuthProtocolError | undefined {\n if (body === null || typeof body !== 'object' || Array.isArray(body)) {\n return undefined;\n }\n const record = body as Record<string, unknown>;\n if (typeof record.error !== 'string' || record.error === '') {\n return undefined;\n }\n const description = typeof record.error_description === 'string' ? record.error_description : '';\n return new OAuthProtocolError(record.error, description, retryAfterMs);\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 * Reduce an axios-error-shaped `err` to the diagnostics that are safe to keep\n * as `NetworkError.cause` (CR-04, D-16, X-3; contract 1.59 R-18).\n *\n * An axios error is a map of everything the request touched: `config` holds\n * the serialized request body (`config.data` — a password, a `bind_secret`, a\n * SCIM `credential`, an SSF `authorization_header`, a form-encoded client\n * secret) and the request headers (the session's bearer and CSRF token);\n * `request` is the live `ClientRequest`, whose buffered output holds the same\n * body; and `response` carries both again (`response.config`,\n * `response.request`) beside the server's headers, which may set cookies. A\n * shallow copy that redacted only the response headers left all of that\n * reachable from `console.log(err)` on any `5xx` or transport failure.\n *\n * So the cause is **rebuilt from an allow-list**, never copied: `name`,\n * `message` and `code` when they are strings, `status` when it is a number,\n * and a `response` of `status`, `statusText`, the server's `data` and its\n * headers with every value not on `SAFE_RESPONSE_HEADERS` replaced by\n * `[REDACTED]`. Nothing else survives — no `config`, no `request`, no stack.\n *\n * Applies to anything carrying `response`, `config` or `request`, or flagged\n * `isAxiosError`, including a transport failure that has no response at all.\n * The caller's original object is never mutated. Other inputs — a plain\n * `Error`, a string, `undefined` — 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 {\n name?: unknown;\n message?: unknown;\n code?: unknown;\n status?: unknown;\n response?: unknown;\n isAxiosError?: unknown;\n };\n const hasResponse = candidate.response !== null && typeof candidate.response === 'object';\n const isRequestError =\n hasResponse || 'config' in candidate || 'request' in candidate || candidate.isAxiosError === true;\n if (!isRequestError) {\n return err;\n }\n\n const sanitized: Record<string, unknown> = {};\n for (const key of ['name', 'message', 'code'] as const) {\n const value = candidate[key];\n if (typeof value === 'string') sanitized[key] = value;\n }\n if (typeof candidate.status === 'number') sanitized.status = candidate.status;\n\n if (hasResponse) {\n const response = candidate.response as {\n status?: unknown;\n statusText?: unknown;\n headers?: unknown;\n data?: unknown;\n };\n const kept: Record<string, unknown> = {};\n if (typeof response.status === 'number') kept.status = response.status;\n if (typeof response.statusText === 'string') kept.statusText = response.statusText;\n if (response.headers !== null && typeof response.headers === 'object') {\n const headers: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(response.headers as Record<string, unknown>)) {\n headers[key] = SAFE_RESPONSE_HEADERS.has(key.toLowerCase()) ? value : REDACTED_HEADER;\n }\n kept.headers = headers;\n }\n if ('data' in response) kept.data = response.data;\n sanitized.response = kept;\n }\n return sanitized;\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","// Shared authz result shape (SDK-Q10, C2) — dependency-free, per D-04's\n// core/*.ts rule (no @grpc/grpc-js, amqplib, axios, jose, or node:util\n// imports here).\n//\n// Both the REST transport (`rest/types.ts`) and the gRPC transport\n// (`grpc/client.ts`) resolve to the exact same public decision shape —\n// `{ allowed, reason? }` — so it is defined once here and re-exported by\n// both `rest/index.ts` and `grpc/index.ts` under the same `AccessDecision`\n// name, rather than declaring two structurally-identical interfaces that\n// could drift out of sync.\n\n/**\n * The outcome of an access check, shared by the REST (`AxiamClient.checkAccess`\n * / `.batchCheck`) and gRPC (`AuthzGrpcClient.checkAccess` / `.batchCheck`)\n * transports (CONTRACT.md §1). `reason` is present (and non-empty) only when\n * `allowed` is `false`.\n */\nexport interface AccessDecision {\n /**\n * Whether the checked action on the checked resource is permitted.\n *\n * **This field alone carries the outcome.** {@link AccessDecision.reasonCode}\n * explains it and never contradicts it.\n */\n allowed: boolean;\n /** Present (and non-empty) only when `allowed` is `false`; a human-readable reason the check was denied. */\n reason?: string;\n /**\n * Machine-readable decision reason (CONTRACT.md §11 rule 9, B1\n * deny-override): `\"allowed\"`, `\"no_grant\"`, or `\"denied_by_rule\"`.\n *\n * **The two refusals mean opposite things to the person on the other end.**\n * `no_grant` says *ask an admin for access*; `denied_by_rule` says *an admin\n * has already decided*. An application that cannot tell them apart sends\n * users to raise tickets that will be refused — which is why the contract\n * forbids collapsing them into a bare `false`.\n *\n * Absent when the server does not send the field: a newer SDK against an\n * older server treats it as absent, never as an error. An unrecognised value\n * is surfaced verbatim and never changes {@link AccessDecision.allowed} —\n * which is why this is a `string` rather than a union, so a code the SDK has\n * never heard of still reaches the caller intact.\n */\n reasonCode?: string;\n}\n\n/**\n * The three `reasonCode` values CONTRACT.md §11 rule 9 defines.\n *\n * @remarks\n * Constants rather than a union type, so an unrecognised server value is still\n * assignable to {@link AccessDecision.reasonCode} and reaches the caller —\n * a closed union would force the SDK to drop it or lie about it.\n */\nexport const ReasonCode = {\n /** An allow grant matched and no deny did. */\n ALLOWED: 'allowed',\n /** Nothing matched — default deny. *Ask an admin for access.* */\n NO_GRANT: 'no_grant',\n /** An explicit deny rule matched and overrode any allow. *An admin has already decided.* */\n DENIED_BY_RULE: 'denied_by_rule',\n} as const;\n","// Shared declarative-authorization core (CONTRACT.md §11) — the ONE\n// resource-resolution + check-access + error-mapping path both the Express\n// and Fastify `requireAccess`/`requireAccessHook` guards call, mirroring how\n// `verifyCore.ts`'s `authenticateRequest` is the one §10 verification path\n// shared by both frameworks.\n//\n// §11.2.1 (composition with the §10 guard): these helpers NEVER perform\n// their own token extraction/verification — they only read the identity\n// already injected onto the request by `axiamMiddleware`/`axiamPlugin` (or\n// by `requireAuth`/`requireAuthHook` mounted earlier in the same chain). If\n// that identity is absent, the caller (express.ts/fastify.ts) responds 401\n// without ever reaching this module.\n\nimport { AuthzError, NetworkError, type Sensitive } from '../core/index.js';\nimport type { AccessCheck, AccessDecision } from '../rest/types.js';\nimport type { AxiamIdentity, VerifiableSession } from './verifyCore.js';\n\n/**\n * The minimal shape `requireAccess`/`requireAccessHook` need from an authz\n * transport — satisfied structurally by `AxiamClient` (`checkAccess`\n * already accepts `subjectId`, §1/FND-04) without importing the class\n * itself, so this module pulls in no axios/grpc dependency.\n */\nexport interface AuthzChecker {\n /** Issue a single access check for the authenticated end user (`subjectId`, §11.2.2). Satisfied structurally by `AxiamClient.checkAccess`. */\n checkAccess(check: AccessCheck): Promise<AccessDecision>;\n}\n\n/**\n * `VerifiableSession` extended with an optional authz-capable client\n * (CONTRACT.md §11). `requireAuth`/`requireRole` only need the base\n * `VerifiableSession` shape; `requireAccess`/`requireAccessHook` additionally\n * require `authzClient` to be set — enforced by {@link assertAuthzClient},\n * which throws synchronously at guard-construction time (route-setup time),\n * not per-request, when it is absent.\n */\nexport interface AuthzVerifiableSession extends VerifiableSession {\n /** Authz transport required by `requireAccess`/`requireAccessHook` (validated by {@link assertAuthzClient}); unused by `requireAuth`/`requireRole`. */\n authzClient?: AuthzChecker;\n}\n\n/** Marker produced by {@link fromParam} — resolve the resource id from a named path/route parameter. */\nexport interface ResourceParamRef {\n /** Discriminant marking the path/route-parameter resolution strategy (§11.2.3.b). */\n readonly kind: 'param';\n /** The path/route parameter name the resource id is read from. */\n readonly name: string;\n}\n\n/**\n * `resource_param` precedence option (§11.2.3.b): resolve the resource id\n * from the named path/route parameter (`req.params[name]` /\n * `request.params[name]`) at request time.\n */\nexport function fromParam(name: string): ResourceParamRef {\n return { kind: 'param', name };\n}\n\n/** `resolver` precedence option (§11.2.3.c): a language-idiomatic callback resolving the resource id from the request. */\nexport type ResourceResolver<TReq> = (req: TReq) => string;\n\n/**\n * The `resource` argument accepted by `requireAccess`/`requireAccessHook`:\n * a static literal (§11.2.3.a, for singleton resources), {@link fromParam}\n * (§11.2.3.b), or a resolver callback (§11.2.3.c).\n */\nexport type ResourceSpec<TReq> = string | ResourceParamRef | ResourceResolver<TReq>;\n\n/** Thrown by {@link resolveResourceId} when the resource id cannot be resolved — mapped to 400 `invalid_request` by callers, never a silent allow (§11.2.3). */\nexport class ResourceResolutionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ResourceResolutionError';\n Object.setPrototypeOf(this, ResourceResolutionError.prototype);\n }\n}\n\n/**\n * Resolve the resource id from `req` per `spec`'s precedence (§11.2.3).\n * `getParams` abstracts over Express's `req.params` and Fastify's\n * `request.params`, both `Record<string, string | undefined>`-shaped at\n * runtime. A missing/empty resolution — a missing path parameter, or a\n * resolver returning an empty string — is a **programming error** raised as\n * {@link ResourceResolutionError}; it is never a silent allow and never a\n * nil/empty-id fallback (§11.2.3).\n */\nexport function resolveResourceId<TReq>(\n req: TReq,\n spec: ResourceSpec<TReq>,\n getParams: (req: TReq) => Record<string, string | undefined> | undefined,\n): string {\n let resourceId: string | undefined;\n if (typeof spec === 'function') {\n resourceId = spec(req);\n } else if (typeof spec === 'string') {\n resourceId = spec;\n } else {\n resourceId = getParams(req)?.[spec.name];\n }\n if (!resourceId) {\n const label = typeof spec === 'object' ? `route param \"${spec.name}\"` : 'resource';\n throw new ResourceResolutionError(`unable to resolve ${label} from request`);\n }\n return resourceId;\n}\n\n/** Optional per-guard settings for `requireAccess`/`requireAccessHook`. */\nexport interface RequireAccessOptions {\n /** Sub-resource scope, passed through to `checkAccess` verbatim (§11.2.4). */\n scope?: string;\n /** Debug-only denial logger (§11.2.8) — never receives the token, only `action`/`resourceId`. */\n logger?: AuthzLogger;\n /**\n * When set, a denial also carries a `WWW-Authenticate: UMA` challenge\n * (§20.3): the guard mints a permission ticket for the action it just refused\n * and tells the caller where to redeem it.\n *\n * Opt-in — see {@link UmaChallenger} for why that matters.\n */\n umaChallenge?: UmaChallenger;\n}\n\n/**\n * Mints a permission ticket. Structurally the `umaRequestTicket` method of an\n * `OidcClient`, taken as a function so this module does not depend on the\n * Node-only OIDC entry point — the middleware core is shared with the browser\n * build, which has no Protection API client.\n */\nexport type UmaTicketMinter = (\n pat: string,\n permissions: ReadonlyArray<{ resourceId: string; resourceScopes: string[] }>,\n) => Promise<Sensitive<string>>;\n\n/**\n * A configured `WWW-Authenticate: UMA` challenge emitter (§20.3, emit half).\n *\n * Attach one via {@link RequireAccessOptions.umaChallenge} and a denial stops\n * being a bare 403: the guard mints a fresh permission ticket for the pairs the\n * caller lacked and returns it in the header, so a UMA-aware client knows where\n * to go for authority instead of only being told \"no\".\n *\n * **Opt-in, and deliberately so.** Emitting a challenge means minting a\n * credential — a wire call to the Protection API, and a live ticket, produced\n * on a path the caller did not explicitly request. A guard that did that on\n * every denial by default would turn each unauthorized request into a\n * Protection API call, which is a denial-of-service amplifier pointed at your\n * own authorization server.\n *\n * **Failure is not escalation.** If minting fails — the PAT expired, the\n * Protection API is down, the resource declares none of the requested scopes —\n * the denial still surfaces as an ordinary 403 without a challenge. A caller\n * who was going to be refused is refused either way; letting a Protection API\n * outage turn a deny into a 500 would hand the outage a second consequence, and\n * letting it turn into an allow would be a security bug.\n */\nexport interface UmaChallenger {\n /** The protection realm to name in the header. */\n realm: string;\n /**\n * The authorization server to send the caller to — normally this\n * deployment's issuer, read from discovery rather than concatenated by hand.\n */\n asUri: string;\n /**\n * A Protection API Token: a *client-credentials* token carrying the\n * `uma_protection` scope (§20.2 rule 1). A user token cannot stand in — a\n * minted ticket is bound to the `client_id` that minted it.\n */\n pat: string;\n /** Typically `oidcClient.umaRequestTicket.bind(oidcClient)`. */\n mint: UmaTicketMinter;\n}\n\n/** Minimal logger seam for the §11.2.8 debug-only denial/error log (mirrors `amqp/consumer.ts`'s `ConsumeLogger`). */\nexport interface AuthzLogger {\n /** Emit a debug-only denial/error record (§11.2.8) — receives `action`/`resourceId` context, never the token. */\n debug(event: string, message: string, context?: Record<string, unknown>): void;\n}\n\n/**\n * Validate that `session.authzClient` is configured, returning it. Throws\n * synchronously (guard-construction time, i.e. route-setup time — not\n * per-request) when absent, per the task's \"helpers throw at construction\n * if absent\" requirement.\n */\nexport function assertAuthzClient(session: AuthzVerifiableSession): AuthzChecker {\n if (!session.authzClient) {\n throw new Error(\n 'requireAccess/requireAccessHook require session.authzClient (an AuthzChecker with checkAccess) to be configured (CONTRACT.md §11)',\n );\n }\n return session.authzClient;\n}\n\n/** Standardized JSON error body shape (§10/§11 — `{ error, message }`). */\nexport interface ErrorBody {\n /** Stable machine-readable error code (e.g. `authentication_failed`, `authorization_denied`). */\n error: string;\n /** Human-readable explanation; never contains token material. */\n message: string;\n}\n\nexport function missingAuthBody(): ErrorBody {\n return {\n error: 'authentication_failed',\n message: 'no authenticated identity on the request — mount axiamMiddleware/axiamPlugin (or requireAuth/requireAuthHook) first',\n };\n}\n\nexport function invalidRequestBody(message: string): ErrorBody {\n return { error: 'invalid_request', message };\n}\n\nexport function authzDeniedBody(message: string): ErrorBody {\n return { error: 'authorization_denied', message };\n}\n\nexport function authzUnavailableBody(message: string): ErrorBody {\n return { error: 'authz_unavailable', message };\n}\n\n/** The outcome of an `evaluateAccess` call — one arm per §11.2.5's error-mapping table (the 401/400 arms are handled by callers before this is ever invoked). */\nexport type CheckOutcome =\n | {\n /** The check passed — the caller proceeds to the handler. */\n kind: 'allowed';\n }\n | {\n /** The check was evaluated and denied (`allowed: false` or a server 403) → HTTP 403. */\n kind: 'denied';\n /** Denial message surfaced in the 403 body. */\n message: string;\n /**\n * The complete `WWW-Authenticate` value, when a {@link UmaChallenger} was\n * configured *and* minting succeeded (§20.3). Absent otherwise, including\n * when minting failed — the denial stands either way.\n */\n challenge?: string;\n /**\n * The decision's `reason_code` (§11 rule 9), surfaced verbatim so the\n * caller can apply §28.5 rule 5 — `no_grant` is the one denial a bearer\n * challenge may invite a client to retry, and `denied_by_rule` is not.\n *\n * Absent when the decision carried none, and absent on the `AuthzError`\n * arm: a server 403 names no reason code, and §11 rule 9 requires an\n * absent one to leave the outcome alone.\n */\n reasonCode?: string;\n }\n | {\n /** The authz transport failed — fail-closed → HTTP 503, never an allow. */\n kind: 'unavailable';\n /** Failure message surfaced in the 503 body. */\n message: string;\n };\n\n/**\n * Call `checker.checkAccess` with `subjectId` set to the *authenticated\n * request's* user id (§11.2.2 — never the app's own service-account\n * identity) and map the outcome per §11.2.5:\n * - `allowed: false` → `denied`\n * - `AuthzError` (server 403/409) → `denied`\n * - `NetworkError`, or any other unexpected failure → `unavailable`\n * (fail-closed: a transport failure is never treated as an allow).\n *\n * Never caches the decision (§11.2.6) — a plain per-call `await`.\n */\nexport async function evaluateAccess(\n checker: AuthzChecker,\n action: string,\n resourceId: string,\n subjectId: string,\n scope?: string,\n challenger?: UmaChallenger,\n): Promise<CheckOutcome> {\n try {\n const decision = await checker.checkAccess({ action, resourceId, scope, subjectId });\n if (!decision.allowed) {\n return deny(\n decision.reason ?? 'access denied',\n action,\n resourceId,\n challenger,\n decision.reasonCode,\n );\n }\n return { kind: 'allowed' };\n } catch (err) {\n if (err instanceof AuthzError) {\n return deny(err.message, action, resourceId, challenger);\n }\n if (err instanceof NetworkError) {\n return { kind: 'unavailable', message: err.message };\n }\n // Fail closed (§11.2.5): any unexpected failure is treated as\n // \"couldn't decide\", never a silent allow.\n return { kind: 'unavailable', message: 'authorization service unavailable' };\n }\n}\n\n/**\n * Build the denial, minting a §20.3 challenge when one was configured.\n *\n * Only ever reached on a path that has already decided to refuse, so minting\n * cannot change the outcome — at worst it fails and the caller gets the plain\n * 403 they would have got anyway.\n */\nasync function deny(\n message: string,\n action: string,\n resourceId: string,\n challenger?: UmaChallenger,\n reasonCode?: string,\n): Promise<CheckOutcome> {\n if (!challenger) return { kind: 'denied', message, reasonCode };\n try {\n // §20.2: the UMA scope is the AXIAM *action*, which is what makes the ticket\n // ask for exactly the authority this check just refused — and what keeps a\n // deny rule vetoing the resulting RPT the same way it vetoed the check.\n const ticket = await challenger.mint(challenger.pat, [{ resourceId, resourceScopes: [action] }]);\n return {\n kind: 'denied',\n message,\n reasonCode,\n challenge: umaChallengeHeaderValue(challenger.realm, challenger.asUri, ticket.expose()),\n };\n } catch {\n // Deliberately swallowed; see UmaChallenger's \"failure is not escalation\".\n // Not logged either: the §11.2.8 logger never receives credentials, and the\n // failure reason from a Protection API call can contain a token echo.\n return { kind: 'denied', message, reasonCode };\n }\n}\n\n/**\n * Format the header value. Duplicated from the Node-only `umaChallengeHeader`\n * rather than imported, because this module is in the browser build's\n * dependency graph and that one is not — the format is four literals and a\n * template, and a shared import would drag the whole OIDC entry point along.\n */\nfunction umaChallengeHeaderValue(realm: string, asUri: string, ticket: string): string {\n return `UMA realm=\"${realm}\", as_uri=\"${asUri}\", ticket=\"${ticket}\"`;\n}\n\n/**\n * Local (no server round-trip) role check (§11.2.9, §11.2 rule 11): true iff\n * `roles` and the identity's roles share at least one entry, by exact,\n * case-sensitive equality.\n *\n * `identityRoles` is {@link AxiamIdentity.roles} — the verified token's `roles`\n * claim and nothing else (contract 1.68; N15). `undefined` (the token carries\n * no `roles` claim) and `[]` (it says the user holds none) both fail: the check\n * fails closed and never falls back to `scope`.\n */\nexport function hasAnyRole(identityRoles: readonly string[] | undefined, roles: readonly string[]): boolean {\n if (!Array.isArray(identityRoles)) {\n return false;\n }\n return roles.some((role) => identityRoles.includes(role));\n}\n\n/**\n * Local (no server round-trip) scope check (§11.1 `require_scope`, §11.2 rule\n * 11 (d); contract 1.68): true iff the identity's granted OAuth2 scopes —\n * {@link AxiamIdentity.scopes}, the token's `scope` claim split on single\n * spaces — contain at least one of `scopes`, each compared as a whole entry by\n * exact, case-sensitive equality. `undefined` (no `scope` claim) fails.\n */\nexport function hasAnyScope(identityScopes: readonly string[] | undefined, scopes: readonly string[]): boolean {\n if (!Array.isArray(identityScopes)) {\n return false;\n }\n return scopes.some((scope) => identityScopes.includes(scope));\n}\n","// Internal Cookie header parser + token extractor (D-27, CONTRACT.md §10).\n//\n// No `cookie-parser`/`@fastify/cookie` peer dependency — a small\n// RFC6265-lenient splitter shared by both Express and Fastify middleware,\n// mirroring the Rust extractor's cookie-then-Bearer fallback order\n// (the Rust SDK's src/middleware/actix.rs:129-149).\n\nimport { timingSafeEqual } from 'node:crypto';\n\n/**\n * Parse a raw `Cookie` request header into a name -> value map.\n * Lenient: splits on `;`, trims whitespace, splits each pair on the first\n * `=` only (cookie values may themselves contain `=`, e.g. base64/JWT).\n */\nexport function parseCookieHeader(header: string | undefined): Record<string, string> {\n const cookies: Record<string, string> = {};\n if (!header) {\n return cookies;\n }\n for (const pair of header.split(';')) {\n const trimmed = pair.trim();\n if (!trimmed) {\n continue;\n }\n const eqIndex = trimmed.indexOf('=');\n if (eqIndex === -1) {\n continue;\n }\n const name = trimmed.slice(0, eqIndex).trim();\n const value = trimmed.slice(eqIndex + 1).trim();\n if (name) {\n cookies[name] = value;\n }\n }\n return cookies;\n}\n\n/** Name of the cookie carrying the AXIAM access token (`axiam_access`). */\nexport const ACCESS_COOKIE_NAME = 'axiam_access';\n\n/**\n * Where an extracted bearer credential came from. Load-bearing for the CSRF\n * gate below (CONTRACT.md §3): a token sourced from the `axiam_access`\n * cookie is attached to a request automatically by the browser (including\n * cross-site ones, in a same-site deployment), so it is NOT CSRF-immune the\n * way an `Authorization: Bearer` header is — a cross-site attacker cannot\n * set arbitrary request headers, but the browser will still send cookies.\n */\nexport type CredentialSource = 'cookie' | 'header';\n\n/** A bearer credential together with where it was read from. */\nexport interface ExtractedCredential {\n /** The raw bearer token value. */\n token: string;\n /** Whether the token came from the `axiam_access` cookie or the `Authorization` header — load-bearing for the CSRF gate (§3). */\n source: CredentialSource;\n}\n\n/**\n * Extract the bearer credential and its source: `axiam_access` cookie\n * first, falling back to `Authorization: Bearer <token>` (case-insensitive\n * scheme), else `undefined` — mirrors the Rust extractor's\n * cookie-then-Bearer order.\n */\nexport function extractCredential(\n cookieHeader: string | undefined,\n authHeader: string | undefined,\n): ExtractedCredential | undefined {\n const cookies = parseCookieHeader(cookieHeader);\n const cookieToken = cookies[ACCESS_COOKIE_NAME];\n if (cookieToken) {\n return { token: cookieToken, source: 'cookie' };\n }\n\n if (!authHeader) {\n return undefined;\n }\n\n const trimmed = authHeader.trim();\n const spaceIndex = trimmed.indexOf(' ');\n if (spaceIndex === -1) {\n return undefined;\n }\n const scheme = trimmed.slice(0, spaceIndex);\n const credentials = trimmed.slice(spaceIndex + 1).trim();\n if (scheme.toLowerCase() !== 'bearer' || !credentials) {\n return undefined;\n }\n return { token: credentials, source: 'header' };\n}\n\n/**\n * Extract just the bearer token, discarding its source. Retained for\n * backward compatibility with existing (non-CSRF-aware) callers/exports;\n * new code that needs to gate on credential source should call\n * {@link extractCredential} directly.\n */\nexport function extractToken(\n cookieHeader: string | undefined,\n authHeader: string | undefined,\n): string | undefined {\n return extractCredential(cookieHeader, authHeader)?.token;\n}\n\n/** Name of the double-submit CSRF cookie (`axiam_csrf`). */\nexport const CSRF_COOKIE_NAME = 'axiam_csrf';\n/** Name of the CSRF request header (`x-csrf-token`) matched against {@link CSRF_COOKIE_NAME}. */\nexport const CSRF_HEADER_NAME = 'x-csrf-token';\n\nconst SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);\n\n/**\n * Whether `method` is a \"safe\" (non-state-changing) HTTP method per\n * CONTRACT.md §3 (state-changing = POST/PUT/PATCH/DELETE). An\n * undefined/empty method is treated as safe: real Express/Fastify\n * requests always populate `req.method`, so this only affects\n * hand-constructed callers that omit it, and defaulting to \"no CSRF\n * required\" never weakens the check for a real HTTP request.\n */\nexport function isSafeMethod(method: string | undefined): boolean {\n if (!method) {\n return true;\n }\n return SAFE_METHODS.has(method.toUpperCase());\n}\n\n/**\n * Cookie double-submit check (CONTRACT.md §3): `csrfHeaderValue` (the\n * `X-CSRF-Token` request header) must be present and equal, in constant\n * time, to the `axiam_csrf` cookie value.\n *\n * Rationale: cookie-sourced requests aren't CSRF-immune, and in any\n * same-site deployment where `axiam_access` reaches the app, the\n * non-`httpOnly` `axiam_csrf` cookie does too (§3) — this mirrors, locally,\n * the same double-submit check the AXIAM server performs on its own\n * endpoints.\n *\n * Never throws: a missing header/cookie or a length mismatch both return\n * `false` (mirrors amqp/hmac.ts's `verifyPayload` idiom — `timingSafeEqual`\n * throws on unequal-length buffers, so length is checked first).\n */\nexport function isCsrfValid(\n cookieHeader: string | undefined,\n csrfHeaderValue: string | undefined,\n): boolean {\n if (!csrfHeaderValue) {\n return false;\n }\n const cookies = parseCookieHeader(cookieHeader);\n const csrfCookie = cookies[CSRF_COOKIE_NAME];\n if (!csrfCookie) {\n return false;\n }\n const received = Buffer.from(csrfHeaderValue, 'utf8');\n const expected = Buffer.from(csrfCookie, 'utf8');\n if (received.length !== expected.length) {\n return false;\n }\n return timingSafeEqual(received, expected);\n}\n","/**\n * The §27.4 rule 7 error sub-types.\n *\n * §2 fixes the taxonomy at three error types and §27 does not widen it. What\n * it adds is a *classification* inside two of them, because a management\n * surface produces refusals §2 never had to describe — §2 has no 404 row at\n * all, since nothing before §27 could return one.\n *\n * TypeScript has real subclassing, so these are subclasses: every\n * `catch (e) { if (e instanceof AuthzError) … }` written before §27 keeps\n * working, and a caller who needs the distinction narrows further.\n */\n\nimport { AuthzError, NetworkError } from '../core/errors.js';\n\n/** One field-level complaint inside a {@link ValidationError}. */\nexport interface FieldError {\n /** The offending field's name, as the server names it. */\n field: string;\n /** What is wrong with it. */\n message: string;\n}\n\n/**\n * HTTP 404 — the resource does not exist, **or** belongs to another tenant.\n *\n * The server answers identically in both cases on purpose: a distinguishable\n * \"exists but not yours\" lets a caller enumerate another tenant's ids. That is\n * why this is an {@link AuthzError} rather than a category of its own — in a\n * multi-tenant IAM the two really are one outcome.\n */\nexport class NotFoundError extends AuthzError {\n /** The registry operation that found nothing, e.g. `\"users.get\"`. */\n readonly operation: string;\n\n constructor(operation: string, message: string) {\n super(message);\n this.name = 'NotFoundError';\n this.operation = operation;\n Object.setPrototypeOf(this, NotFoundError.prototype);\n }\n}\n\n/**\n * HTTP 409 — a uniqueness or state conflict, such as a role name already taken.\n *\n * Never retried (§27.4 rule 8): a 409 is the server telling the truth, not a\n * transient fault, and a retry produces the identical answer one round-trip\n * later.\n */\nexport class ConflictError extends AuthzError {\n /** The registry operation that conflicted. */\n readonly operation: string;\n /**\n * The body's `reason_code`, as the server spelled it (contract 1.62, §36.4),\n * or `undefined` when the body carries none (a server that predates it, or a\n * `409` of an operation that does not name one).\n *\n * The `409` of every `network` operation says which conflict it is:\n * `stale_version`, `strands_profile`, `has_children`, `site_gone`,\n * `duplicate_name`, `duplicate_vlan`, `duplicate_rank`, `profile_exists` or\n * `other` (§36.3 rule 2). The vocabulary is **open**: a value this SDK does\n * not know is surfaced verbatim, and a caller branches on this member —\n * never on `message`, which an SDK must not parse. It is not the `reason` of\n * an authorization decision (§3), which is a human string.\n */\n readonly reasonCode?: string;\n\n constructor(operation: string, message: string, reasonCode?: string) {\n super(message);\n this.name = 'ConflictError';\n this.operation = operation;\n this.reasonCode = reasonCode;\n Object.setPrototypeOf(this, ConflictError.prototype);\n }\n}\n\n/**\n * HTTP 400/422 — the request was rejected.\n *\n * §2 maps 400 to `NetworkError`, described as an \"SDK programming error\". That\n * description was written when nothing but the SDK itself could produce a 400.\n * On this surface a 400 is usually a *user's* invalid input — an email that is\n * not an email, a slug already taken — and an application needs to tell that\n * from a broken socket without matching on message text. The parent type is\n * inherited from §2 rather than chosen here.\n */\nexport class ValidationError extends NetworkError {\n /** The HTTP status the server answered with — 400 or 422. */\n readonly status: number;\n /** The registry operation that was rejected. */\n readonly operation: string;\n /** Per-field detail, where the server sent any. Empty is normal. */\n readonly fields: FieldError[];\n\n constructor(operation: string, status: number, message: string, fields: FieldError[]) {\n super(message);\n this.name = 'ValidationError';\n this.status = status;\n this.operation = operation;\n this.fields = fields;\n Object.setPrototypeOf(this, ValidationError.prototype);\n }\n}\n\n/**\n * Pull field-level detail out of an error body, on a best-effort basis.\n *\n * Two shapes are recognised — an array of `{field, message}` and an object\n * keyed by field name. A body in neither shape yields no fields rather than an\n * error: failing to parse an error body would replace a useful message with a\n * useless one.\n *\n * @internal\n */\nexport function parseFieldErrors(body: unknown): FieldError[] {\n if (!body || typeof body !== 'object') return [];\n const errors = (body as { errors?: unknown }).errors;\n if (Array.isArray(errors)) {\n return errors.filter(\n (e): e is FieldError =>\n !!e && typeof e === 'object' && typeof (e as FieldError).field === 'string',\n );\n }\n if (errors && typeof errors === 'object') {\n return Object.entries(errors as Record<string, unknown>)\n .filter(([, v]) => typeof v === 'string')\n .map(([field, message]) => ({ field, message: message as string }));\n }\n return [];\n}\n","// MCP resource-server helpers (CONTRACT.md §28, RFC 9728 + RFC 6750) — the\n// ONE §28 implementation both the Express and Fastify surfaces are built on,\n// mirroring how `verifyCore.ts` is the one §10 verification path and\n// `authzCore.ts` the one §11 decision path.\n//\n// §28.0: this SDK implements the RESOURCE SERVER's half and nothing else.\n// AXIAM is the authorization server and implements none of §28; the MCP\n// client's half (parsing a challenge, fetching a document, deciding whether to\n// trust the authorization server it names) is deliberately not in this\n// contract version, for the same reason §20.3 stops at parsing.\n//\n// **No operation here performs network I/O**, so §16 (retry) and §9\n// (single-flight refresh) do not apply and nothing in this module touches the\n// SDK client's own session. All three operations are pure local computation,\n// like `oidcBegin` (§12.1) and `umaParseChallenge` (§20.5).\n//\n// **Nothing here is a source of truth about a token.** The document is a claim\n// a resource server publishes about itself; the challenge is a hint it gives a\n// caller that already failed. Whether a request is authorized stays §10.1's\n// and §11's decision, unchanged and unreachable from here.\n\nimport type { Request as ExpressRequest, Response as ExpressResponse, Router } from 'express';\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';\nimport { ReasonCode } from '../core/authz.js';\nimport { ValidationError } from '../management/errors.js';\nimport { extractCredential } from './cookieHeader.js';\n\n/**\n * RFC 9728 §3.1's well-known prefix — the segment inserted between a\n * resource's authority and its path to reach the document that describes it.\n */\nexport const PROTECTED_RESOURCE_METADATA_PREFIX = '/.well-known/oauth-protected-resource';\n\n/**\n * The three hosts §28.2 rule 2 lets an `http` URL use, and the only ones.\n *\n * They are AXIAM's RFC 8252 §7.3 loopback hosts, reused verbatim. There is\n * deliberately no flag, environment variable or debug build that widens this:\n * a resource server reachable over plaintext on a routable host publishes an\n * identifier an attacker can impersonate.\n */\nconst LOOPBACK_HOSTS: ReadonlySet<string> = new Set(['127.0.0.1', '[::1]', 'localhost']);\n\n/** RFC 6750 §3.1's three error codes — the complete vocabulary a challenge may name (§28.4). */\nexport type BearerChallengeError = 'invalid_request' | 'invalid_token' | 'insufficient_scope';\n\nconst BEARER_CHALLENGE_ERRORS: ReadonlySet<string> = new Set<BearerChallengeError>([\n 'invalid_request',\n 'invalid_token',\n 'insufficient_scope',\n]);\n\n// ---------------------------------------------------------------------------\n// Refusals (§28.2, §28.4, §28.5) — always `ValidationError`, never a new type\n// ---------------------------------------------------------------------------\n\n/**\n * Raise §28's refusal.\n *\n * §28.6 pins the error taxonomy: \"§28's refusals are `ValidationError`; no new\n * type\". This SDK's {@link ValidationError} is §27.4 rule 7's sub-type of\n * `NetworkError`, so `status` names the HTTP code an AXIAM server would answer\n * with for the same rejected field — **400** — even though no server was asked\n * and no request was made. `operation` names the §28 operation that refused,\n * the way a management refusal names `users.get`.\n */\nfunction refuse(operation: string, field: string, message: string): never {\n throw new ValidationError(operation, 400, `${field}: ${message} (CONTRACT.md §28)`, [\n { field, message },\n ]);\n}\n\n// ---------------------------------------------------------------------------\n// Character classes (RFC 6749 Appendix A) — §28.2 rule 5, §28.4\n// ---------------------------------------------------------------------------\n\n/** `NQCHAR`: `%x21` / `%x23`–`%x5B` / `%x5D`–`%x7E`. No space, no `\"`, no `\\`, no control, no non-ASCII. */\nfunction isNqchar(code: number): boolean {\n return code === 0x21 || (code >= 0x23 && code <= 0x5b) || (code >= 0x5d && code <= 0x7e);\n}\n\n/** `NQSCHAR`: `NQCHAR` plus the space (`%x20`). */\nfunction isNqschar(code: number): boolean {\n return code === 0x20 || isNqchar(code);\n}\n\nfunction isAll(value: string, predicate: (code: number) => boolean): boolean {\n for (let i = 0; i < value.length; i += 1) {\n if (!predicate(value.charCodeAt(i))) return false;\n }\n return true;\n}\n\n// ---------------------------------------------------------------------------\n// Absolute-URI parsing (§28.2 rules 1, 2, 3, 7)\n// ---------------------------------------------------------------------------\n\n/**\n * `scheme://authority[path][?query][#fragment]`, matched against the caller's\n * string exactly as given.\n *\n * Deliberately not `new URL()`: that parser *normalises* — it lowercases the\n * host, resolves `..` segments, appends a path to an authority-only URL and\n * re-encodes. §28.2 forbids adjusting a value to make it pass, and §28.3\n * derives the document's own path from this string, so what is validated must\n * be what was written.\n */\nconst ABSOLUTE_URI = /^([A-Za-z][A-Za-z0-9+.-]*):\\/\\/([^/?#]*)([^?#]*)(\\?[^#]*)?(#[\\s\\S]*)?$/;\n\n/** The pieces of an absolute URI, sliced out of the caller's string without normalisation. */\ninterface ParsedUri {\n /** The scheme, verbatim (compared case-insensitively, stored as written). */\n scheme: string;\n /** The authority, verbatim — `userinfo@host:port` included. */\n authority: string;\n /** The path component: empty, or starting with `/`. A trailing slash is preserved. */\n path: string;\n /** True when the string carried a `?`, even an empty one. */\n hasQuery: boolean;\n /** True when the string carried a `#`, even an empty one. */\n hasFragment: boolean;\n}\n\nfunction parseAbsoluteUri(raw: string): ParsedUri | undefined {\n const match = ABSOLUTE_URI.exec(raw);\n if (!match) return undefined;\n const authority = match[2] ?? '';\n if (authority === '') return undefined;\n return {\n scheme: match[1] ?? '',\n authority,\n path: match[3] ?? '',\n hasQuery: match[4] !== undefined,\n hasFragment: match[5] !== undefined,\n };\n}\n\n/**\n * The host inside an authority: `userinfo@` stripped, port stripped, an IPv6\n * literal's brackets kept (so `[::1]` compares as §28.2 rule 2 spells it).\n *\n * Stripping `userinfo` is what makes `http://localhost@evil.example.com/` a\n * refusal rather than a loopback pass — the host there is `evil.example.com`.\n */\nfunction hostOf(authority: string): string {\n const at = authority.lastIndexOf('@');\n const hostport = at >= 0 ? authority.slice(at + 1) : authority;\n if (hostport.startsWith('[')) {\n const close = hostport.indexOf(']');\n return close < 0 ? hostport : hostport.slice(0, close + 1);\n }\n const colon = hostport.indexOf(':');\n return colon < 0 ? hostport : hostport.slice(0, colon);\n}\n\n/** How much of §28.2 rule 1 a particular member is held to — rule 7 and §28.4's `resource_metadata` relax two parts of it. */\ninterface UriPolicy {\n /** `true` for `resource_documentation` (§28.2 rule 7) and `resource_metadata` (§28.4): a page for a human may be parameterised. */\n allowQuery: boolean;\n /** `true` for the same two members, for the same reason. */\n allowFragment: boolean;\n}\n\nconst IDENTIFIER: UriPolicy = { allowQuery: false, allowFragment: false };\nconst LOCATOR: UriPolicy = { allowQuery: true, allowFragment: true };\n\n/**\n * §28.2 rules 1 and 2, applied to one member. Returns the parse so a caller\n * that needs the path (§28.3) does not parse twice.\n */\nfunction requireAbsoluteUri(\n operation: string,\n field: string,\n raw: unknown,\n policy: UriPolicy,\n): ParsedUri {\n if (typeof raw !== 'string' || raw === '') {\n refuse(operation, field, 'must be a non-empty absolute URI');\n }\n const parsed = parseAbsoluteUri(raw);\n if (!parsed) {\n refuse(\n operation,\n field,\n `must be an absolute URI with a scheme and an authority, not ${JSON.stringify(raw)}`,\n );\n }\n if (parsed.hasQuery && !policy.allowQuery) {\n refuse(operation, field, 'must carry no query — §28.3 derives the metadata path from it');\n }\n if (parsed.hasFragment && !policy.allowFragment) {\n refuse(operation, field, 'must carry no fragment');\n }\n const scheme = parsed.scheme.toLowerCase();\n if (scheme === 'https') return parsed;\n if (scheme === 'http' && LOOPBACK_HOSTS.has(hostOf(parsed.authority).toLowerCase())) {\n return parsed;\n }\n refuse(\n operation,\n field,\n `must use https — http is accepted only on 127.0.0.1, [::1] or localhost, and ${JSON.stringify(raw)} is neither`,\n );\n}\n\nfunction requireList(operation: string, field: string, value: unknown): readonly unknown[] {\n if (!Array.isArray(value)) refuse(operation, field, 'must be a list');\n return value;\n}\n\n// ---------------------------------------------------------------------------\n// §28.1 / §28.2 — `protectedResourceMetadata`\n// ---------------------------------------------------------------------------\n\n/**\n * The RFC 9728 §2 document, carrying **at most** the five members §28.2\n * permits, in that order, and no others.\n *\n * Member names are the wire names, because this object serializes to the\n * document byte for byte. RFC 9728 defines further members; §28.2 forbids\n * emitting them in this contract version — a member one SDK emits and ten do\n * not is a divergence the cross-SDK review would have to reconcile.\n *\n * Two members are **omitted rather than emitted empty or `null`**:\n * `scopes_supported` when the caller passed no scopes, and\n * `resource_documentation` when the caller passed none.\n */\nexport interface ProtectedResourceMetadataDocument {\n /** The resource identifier this server publishes for itself — the string an RFC 8707 `resource` parameter carries and the `aud` the guard checks. */\n readonly resource: string;\n /** The issuer identifiers of the authorization servers that guard this resource. At least one, each verbatim. */\n readonly authorization_servers: readonly string[];\n /** The scope tokens this resource server understands, in the caller's order. Omitted when the caller passed none. */\n readonly scopes_supported?: readonly string[];\n /** Always `[\"header\"]` in this contract version — §10's guard reads a bearer credential from the `Authorization` header alone. */\n readonly bearer_methods_supported: readonly string[];\n /** A human-readable documentation page. Omitted when the caller passed none; never `null`. */\n readonly resource_documentation?: string;\n}\n\n/**\n * The arguments of §28.1's `protected_resource_metadata`, as one options\n * object — this SDK's idiom for a constructor with five inputs, and the shape\n * `RequireAccessOptions` and `OidcLoginOptions` already use. The canonical\n * order is preserved in the declaration so a port author can read the two\n * side by side.\n */\nexport interface ProtectedResourceMetadataOptions {\n /** The resource identifier. Absolute, `https` (or `http` on a loopback host), with no query and no fragment. A trailing slash is significant. */\n resource: string;\n /** The issuer identifiers of the authorization servers guarding it — at least one, no duplicates, no query, no fragment. */\n authorizationServers: readonly string[];\n /** The scope tokens this resource server understands. Order is preserved, duplicates are refused, and an empty list omits the member. */\n scopesSupported: readonly string[];\n /** Defaults to `[\"header\"]`, and `[\"header\"]` is the only accepted value in this contract version. */\n bearerMethodsSupported?: readonly string[];\n /** Optional documentation page for a human. May carry a query and a fragment; omitted from the document when absent. */\n resourceDocumentation?: string;\n}\n\n/**\n * What {@link protectedResourceMetadata} returns: the document, the path it is\n * served at, and the URL that path resolves to.\n *\n * {@link ProtectedResourceMetadata.metadataUrl} exists so that the guard's\n * `resourceMetadataUrl` option is fed from the helper that derived it rather\n * than retyped — retyping is how the two come to disagree, and a challenge\n * pointing at a document that is not this resource server's is worse than no\n * challenge at all.\n */\nexport interface ProtectedResourceMetadata {\n /** The RFC 9728 §2 document, ready to serialize. */\n readonly document: ProtectedResourceMetadataDocument;\n /** The absolute path the document is served at, derived from the resource per §28.3 — never chosen. */\n readonly metadataPath: string;\n /** {@link ProtectedResourceMetadata.metadataPath} resolved against the resource's scheme and authority. Feed this to the guard's `resourceMetadataUrl`. */\n readonly metadataUrl: string;\n}\n\n/**\n * `protectedResourceMetadata(options)` (CONTRACT.md §28.1) — build and\n * validate the RFC 9728 protected-resource metadata document this server\n * publishes about itself, and derive the path and URL it is served at.\n *\n * @remarks\n * **Validation happens here and it refuses; it never repairs.** Every §28.2\n * rule is checked before any route exists and before any request is served,\n * and a violation throws `ValidationError`. Nothing is normalised, trimmed,\n * lowercased or re-encoded to make it pass: a value that needs adjusting is a\n * configuration mistake an operator fixes in one line, and a helper that\n * quietly fixed it would publish a document describing a resource server that\n * does not exist.\n *\n * **Nothing in the document may come from a request** (§28.2 rule 8). Both\n * `resource` and `authorizationServers` are configuration; this SDK offers no\n * option to build either from the `Host` header, the `Forwarded`/`X-Forwarded-*`\n * family or the request URL, because a document assembled from the request is\n * a document an attacker can point at an authorization server of their\n * choosing — the whole handshake redirected with one header.\n *\n * @example\n * ```ts\n * const metadata = protectedResourceMetadata({\n * resource: 'https://mcp.example.com/mcp',\n * authorizationServers: ['https://axiam.example.com'],\n * scopesSupported: ['mcp:read', 'mcp:tools'],\n * });\n * metadata.metadataPath; // '/.well-known/oauth-protected-resource/mcp'\n * metadata.metadataUrl; // 'https://mcp.example.com/.well-known/oauth-protected-resource/mcp'\n * ```\n *\n * @throws ValidationError when any §28.2 rule is violated.\n */\nexport function protectedResourceMetadata(\n options: ProtectedResourceMetadataOptions,\n): ProtectedResourceMetadata {\n const op = 'protectedResourceMetadata';\n\n // Rule 1 + rule 2.\n const resource = options.resource;\n const parsed = requireAbsoluteUri(op, 'resource', resource, IDENTIFIER);\n\n // Rule 3 + rule 4: at least one entry, each an issuer verbatim, no duplicates.\n const servers = requireList(op, 'authorization_servers', options.authorizationServers);\n if (servers.length === 0) {\n refuse(\n op,\n 'authorization_servers',\n 'must name at least one authorization server — a document that names none answers none of the question the client asked',\n );\n }\n const seenServers = new Set<string>();\n const authorizationServers: string[] = [];\n for (const entry of servers) {\n requireAbsoluteUri(op, 'authorization_servers', entry, IDENTIFIER);\n const issuer = entry as string;\n if (seenServers.has(issuer)) {\n refuse(op, 'authorization_servers', `duplicate entry ${JSON.stringify(issuer)}`);\n }\n seenServers.add(issuer);\n authorizationServers.push(issuer);\n }\n\n // Rule 5: NQCHAR tokens, order preserved, duplicates refused, empty omits.\n const scopes = requireList(op, 'scopes_supported', options.scopesSupported);\n const seenScopes = new Set<string>();\n const scopesSupported: string[] = [];\n for (const scope of scopes) {\n if (typeof scope !== 'string' || scope === '' || !isAll(scope, isNqchar)) {\n refuse(\n op,\n 'scopes_supported',\n `${JSON.stringify(scope)} is not a scope token — one or more NQCHAR (no space, no '\"', no '\\\\', no control character, no non-ASCII)`,\n );\n }\n if (seenScopes.has(scope)) refuse(op, 'scopes_supported', `duplicate scope ${JSON.stringify(scope)}`);\n seenScopes.add(scope);\n scopesSupported.push(scope);\n }\n\n // Rule 6: exactly [\"header\"].\n const methods = requireList(\n op,\n 'bearer_methods_supported',\n options.bearerMethodsSupported ?? ['header'],\n );\n if (methods.length !== 1 || methods[0] !== 'header') {\n refuse(\n op,\n 'bearer_methods_supported',\n `must be exactly [\"header\"] in this contract version — §10's guard reads a bearer credential from the Authorization header alone, so ${JSON.stringify(methods)} would describe behaviour this SDK does not have`,\n );\n }\n\n // Rule 7: absolute URL, query and fragment permitted, omitted when absent.\n const documentation = options.resourceDocumentation;\n if (documentation !== undefined) {\n requireAbsoluteUri(op, 'resource_documentation', documentation, LOCATOR);\n }\n\n // §28.2 fixes the member order. Insertion order is what `JSON.stringify`\n // emits, so the conditional spreads sit where the omitted members belong.\n const document: ProtectedResourceMetadataDocument = Object.freeze({\n resource,\n authorization_servers: Object.freeze(authorizationServers) as readonly string[],\n ...(scopesSupported.length > 0\n ? { scopes_supported: Object.freeze(scopesSupported) as readonly string[] }\n : {}),\n bearer_methods_supported: Object.freeze(['header']) as readonly string[],\n ...(documentation !== undefined ? { resource_documentation: documentation } : {}),\n });\n\n const metadataPath = deriveMetadataPath(parsed.path);\n return Object.freeze({\n document,\n metadataPath,\n metadataUrl: `${parsed.scheme}://${parsed.authority}${metadataPath}`,\n });\n}\n\n/**\n * §28.3's derivation: RFC 9728 §3.1 inserts the well-known segment between the\n * authority and the path. An empty path and a bare `/` both reach the root\n * form; anything else is appended, **trailing slash included** — it is part of\n * the identifier a client compares, and two resources that differ only by it\n * are two resources.\n */\nfunction deriveMetadataPath(resourcePath: string): string {\n if (resourcePath === '' || resourcePath === '/') return PROTECTED_RESOURCE_METADATA_PREFIX;\n return PROTECTED_RESOURCE_METADATA_PREFIX + resourcePath;\n}\n\n// ---------------------------------------------------------------------------\n// §28.4 — `bearerChallenge`\n// ---------------------------------------------------------------------------\n\n/** The arguments of §28.1's `bearer_challenge`, in canonical order. */\nexport interface BearerChallengeOptions {\n /** The document's URL — the one parameter that is always present. May carry a query and a fragment. */\n resourceMetadataUrl: string;\n /** One of RFC 6750 §3.1's three codes, or absent when the request carried no authentication information at all. */\n error?: BearerChallengeError;\n /**\n * A human-readable description, for an application building **its own**\n * challenge for its own 400.\n *\n * The SDK's guards never set it: expired, not yet valid, wrong tenant, wrong\n * audience, bad signature, `alg` confusion, an unsatisfiable `cnf`, a revoked\n * `sid` — §28.4 makes all of them `invalid_token`, indistinguishably. Every\n * distinction a 401 draws for an unauthenticated stranger is an oracle.\n */\n errorDescription?: string;\n /** The scope the route asked for, verbatim — one or more tokens joined by a single space. */\n scope?: string;\n}\n\n/**\n * `bearerChallenge(options)` (CONTRACT.md §28.4) — build the **value** of a\n * `WWW-Authenticate` header, never the whole header line and never a map. The\n * caller sets the header.\n *\n * @remarks\n * Parameters appear in a fixed order — `error`, `error_description`, `scope`,\n * `resource_metadata` — separated by exactly `, `. `resource_metadata` is\n * always present; the other three are omitted when not given.\n *\n * **Every value is quoted and no value is ever escaped.** RFC 6750 §3 restricts\n * each parameter to a character set that cannot contain `\"` or `\\`, so a value\n * needing an escape is a value that does not belong in a challenge: this\n * function refuses it rather than escaping, truncating or stripping it. A\n * challenge is built from the code's own constants and a route's own\n * configuration, so an invalid one is a programming error, not a runtime\n * condition to degrade around.\n *\n * @example\n * ```ts\n * bearerChallenge({ resourceMetadataUrl: metadata.metadataUrl });\n * // Bearer resource_metadata=\"https://mcp.example.com/.well-known/oauth-protected-resource/mcp\"\n *\n * bearerChallenge({ resourceMetadataUrl: metadata.metadataUrl, error: 'insufficient_scope', scope: 'mcp:tools' });\n * // Bearer error=\"insufficient_scope\", scope=\"mcp:tools\", resource_metadata=\"https://…/mcp\"\n * ```\n *\n * @throws ValidationError when any parameter is outside RFC 6750's syntax.\n */\nexport function bearerChallenge(options: BearerChallengeOptions): string {\n const op = 'bearerChallenge';\n const params: string[] = [];\n\n if (options.error !== undefined) {\n if (!BEARER_CHALLENGE_ERRORS.has(options.error)) {\n refuse(\n op,\n 'error',\n `must be one of invalid_request, invalid_token, insufficient_scope — RFC 6750 §3.1 defines no others, and ${JSON.stringify(options.error)} is not among them`,\n );\n }\n params.push(`error=\"${options.error}\"`);\n }\n\n if (options.errorDescription !== undefined) {\n const description = options.errorDescription;\n if (typeof description !== 'string' || description === '' || !isAll(description, isNqschar)) {\n refuse(\n op,\n 'error_description',\n 'must be one or more NQSCHAR (no \\'\"\\', no \\'\\\\\\', no control character, no non-ASCII) — a value needing an escape does not belong in a challenge',\n );\n }\n params.push(`error_description=\"${description}\"`);\n }\n\n if (options.scope !== undefined) {\n const scope = options.scope;\n if (typeof scope !== 'string' || scope === '') {\n refuse(op, 'scope', 'must be one or more scope tokens joined by a single space');\n }\n for (const token of scope.split(' ')) {\n if (token === '' || !isAll(token, isNqchar)) {\n refuse(\n op,\n 'scope',\n `${JSON.stringify(scope)} is not a space-joined list of scope tokens — no leading, trailing or doubled space, and no empty token`,\n );\n }\n }\n params.push(`scope=\"${scope}\"`);\n }\n\n const url = options.resourceMetadataUrl;\n requireAbsoluteUri(op, 'resource_metadata', url, LOCATOR);\n if (!isAll(url, isNqchar)) {\n refuse(\n op,\n 'resource_metadata',\n 'must carry no \\'\"\\', no \\'\\\\\\', no space and no control character — a correctly encoded URL cannot, so one that does has not been encoded',\n );\n }\n params.push(`resource_metadata=\"${url}\"`);\n\n return `Bearer ${params.join(', ')}`;\n}\n\n// ---------------------------------------------------------------------------\n// §28.5 — the `resourceMetadataUrl` guard option\n// ---------------------------------------------------------------------------\n\n/**\n * The two guard settings §28.5 reads. Satisfied structurally by\n * `VerifiableSession`, which is where an integrator actually sets them; taken\n * as its own shape so `serveProtectedResourceMetadata` can cross-check a guard\n * without depending on the verification core.\n */\nexport interface McpGuardConfig {\n /** §10.1 row 6's expected audience, under the name this SDK already gives it. §28 adds no second audience option. */\n expectedAudience?: string;\n /** §28.5's option: the URL of this resource server's metadata document. Setting it is what turns §28 on. */\n resourceMetadataUrl?: string;\n}\n\n/**\n * The §28 challenge values a guard emits, all built once at guard-construction\n * time so that an invalid one is a startup failure rather than a surprise on\n * the 401 path.\n *\n * `undefined` where {@link McpGuardConfig.resourceMetadataUrl} is unset, which\n * is how \"§28 is off\" stays byte-for-byte indistinguishable from \"§28 is\n * absent\" (§28.5 rule 1).\n */\nexport interface McpGuardChallenges {\n /** §28.4 vector 1 — the request carried **no** authentication information, so RFC 6750 §3 says not to name an error. */\n readonly noCredential: string;\n /** §28.4 vector 2 — a credential was presented and rejected. The only thing the 401 ever says about why. */\n readonly invalidToken: string;\n /** §28.4 vector 3 — present only where the route named a scope; emitted on a `no_grant` denial and nowhere else. */\n readonly insufficientScope?: string;\n /** The document's path, exempted from authentication by the §10 guard (§28.3 rule 2). */\n readonly metadataPath: string;\n}\n\n/**\n * Validate a guard's §28 configuration and precompute the challenges it will\n * emit. Called by every guard factory at construction time — route-setup time,\n * never per-request.\n *\n * @remarks\n * Returns `undefined` when `resourceMetadataUrl` is unset: §28 is opt-in, and\n * with the option absent the guard behaves exactly as it did before §28\n * existed — no header on any response, no status changed, no body changed.\n *\n * **`expectedAudience` is mandatory once `resourceMetadataUrl` is set**, and\n * the refusal names both options. A resource server that publishes \"tokens for\n * me carry this `aud`\" and then does not check `aud` has published a claim it\n * does not honour, and a token minted for a *different* resource server opens\n * it. That is the confusion RFC 8707 exists to prevent, so this is a refusal\n * rather than a warning.\n *\n * @param guard - the session the guard was built from.\n * @param operation - the guard factory's name, so the refusal says which guard refused.\n * @param scope - the route's `scope` argument, where it has one (§28.5 rule 5).\n * @throws ValidationError when `resourceMetadataUrl` is set without an expected audience, or when either it or `scope` is outside §28.4's syntax.\n */\nexport function mcpGuardChallenges(\n guard: McpGuardConfig,\n operation: string,\n scope?: string,\n): McpGuardChallenges | undefined {\n const resourceMetadataUrl = guard.resourceMetadataUrl;\n if (resourceMetadataUrl === undefined) return undefined;\n\n if (guard.expectedAudience === undefined || guard.expectedAudience === '') {\n refuse(\n operation,\n 'resourceMetadataUrl',\n 'requires expectedAudience to be set on the same session (CONTRACT.md §28.5 rule 2) — announcing a resource identifier obliges this server to check that an inbound token\\'s `aud` is that identifier, and a resource server that announces itself without checking is opened by a token minted for somebody else',\n );\n }\n\n const parsed = requireAbsoluteUri(operation, 'resourceMetadataUrl', resourceMetadataUrl, LOCATOR);\n return Object.freeze({\n noCredential: bearerChallenge({ resourceMetadataUrl }),\n invalidToken: bearerChallenge({ resourceMetadataUrl, error: 'invalid_token' }),\n ...(scope !== undefined\n ? {\n insufficientScope: bearerChallenge({\n resourceMetadataUrl,\n error: 'insufficient_scope',\n scope,\n }),\n }\n : {}),\n metadataPath: parsed.path === '' ? '/' : parsed.path,\n });\n}\n\n/**\n * Pick between §28.4's first two vectors for a 401: `invalid_token` when the\n * request carried a credential, no `error` at all when it carried none.\n *\n * §28.4 is explicit that the absent `error` is not an oversight — RFC 6750 §3\n * says a resource server SHOULD NOT name an error code when the request\n * carried no authentication information, because no credential is not a bad\n * credential, and a client has to be able to tell the two apart.\n *\n * @internal\n */\nexport function challengeFor401(\n challenges: McpGuardChallenges,\n cookieHeader: string | undefined,\n authorizationHeader: string | undefined,\n): string {\n return extractCredential(cookieHeader, authorizationHeader)\n ? challenges.invalidToken\n : challenges.noCredential;\n}\n\n/**\n * §28.5 rule 5: the one class of 403 that carries a challenge, and only it.\n *\n * A `no_grant` denial on a route that named a scope means *ask for more*,\n * which is exactly what a challenge invites a client to do. A `denied_by_rule`\n * denial means *an administrator has already decided*, and challenging on it\n * sends an MCP client all the way around the authorization loop to arrive at\n * the identical 403. An absent or unrecognised `reason_code` — an older server,\n * a value this SDK predates — is not eligible either: §11 rule 9 requires an\n * unknown code to leave the outcome alone, and the outcome here is a\n * header-free 403.\n *\n * @internal\n */\nexport function challengeFor403(\n challenges: McpGuardChallenges | undefined,\n reasonCode: string | undefined,\n): string | undefined {\n if (!challenges?.insufficientScope) return undefined;\n return reasonCode === ReasonCode.NO_GRANT ? challenges.insufficientScope : undefined;\n}\n\n/**\n * Is this request the unauthenticated `GET` of the metadata document?\n *\n * §28.3 rule 2 requires the document to be reachable with no credential of any\n * kind, and requires the SDK to exempt the path explicitly where the §10 guard\n * is applied globally — which is the normal Express `app.use(...)` and Fastify\n * `preHandler` arrangement. A document that 401s cannot start the handshake it\n * exists to start: the client would be holding a 401 and being told to go read\n * a page that answers 401.\n *\n * The exemption is derived from `resourceMetadataUrl`, so it exists only where\n * §28 is configured and covers exactly the one path that option names.\n *\n * @internal\n */\nexport function isMetadataDocumentRequest(\n challenges: McpGuardChallenges | undefined,\n method: string | undefined,\n url: string | undefined,\n): boolean {\n if (!challenges || typeof url !== 'string') return false;\n const verb = (method ?? '').toUpperCase();\n if (verb !== 'GET' && verb !== 'HEAD') return false;\n const end = url.search(/[?#]/);\n return (end < 0 ? url : url.slice(0, end)) === challenges.metadataPath;\n}\n\n// ---------------------------------------------------------------------------\n// §28.3 — `serveProtectedResourceMetadata`\n// ---------------------------------------------------------------------------\n\n/**\n * The framework object `serveProtectedResourceMetadata` registers on — §10's\n * table, unchanged: an Express application or router, or a Fastify instance.\n */\nexport type McpMetadataApp = Router | FastifyInstance;\n\n/**\n * `serveProtectedResourceMetadata(app, metadata, guard?)` (CONTRACT.md §28.3) —\n * register the one `GET` route that serves the document, on the framework's\n * own router, and return the same metadata value so the guard's\n * `resourceMetadataUrl` can be fed from it.\n *\n * @remarks\n * **The path is derived, not chosen**, and **exactly one route is registered.**\n * The root form is not also registered for a resource that has a path: a\n * deployment fronting two resources would then have two helpers competing for\n * the same root path and registration order would decide the loser. A\n * deployment fronting several resources calls this once per resource, and the\n * derived paths cannot collide because each comes from its own resource.\n *\n * The response is `200` with `Content-Type: application/json`, the document as\n * its body, `Cache-Control: public, max-age=3600` and\n * `Access-Control-Allow-Origin: *` — the last because an MCP client running in\n * a browser cannot read the document without it, and it is safe precisely\n * because the response is identical for every caller. It carries no\n * `Access-Control-Allow-Credentials`, which would be asking a browser to attach\n * the user's cookies to a request that has no use for them. Nothing is read\n * from the request, so there is no `Set-Cookie` and no per-caller content, and\n * §3a does not apply: it is a `GET`, and §3a is scoped to state-changing\n * methods and cookie-sourced credentials.\n *\n * **Serving it needs no route ordering.** Where the §10 guard is mounted\n * globally it exempts this exact path itself, from the `resourceMetadataUrl`\n * it was configured with — so the route works whether it is registered before\n * or after the guard, and on Fastify, where a `preHandler` hook applies\n * regardless of registration order.\n *\n * @param app - an Express application/router, or a Fastify instance. Register on the application root: a router mounted under a prefix would serve the document at a path the derived URL does not name.\n * @param metadata - the value {@link protectedResourceMetadata} returned.\n * @param guard - optionally, the session the §10 guard is built from. Passing it is what lets this SDK apply §28.5 rule 3 — see below.\n *\n * @throws ValidationError when `guard` is given and its `resourceMetadataUrl`\n * is not exactly the document's `metadataUrl`, or its `expectedAudience` is not\n * exactly the document's `resource`.\n *\n * Both comparisons are simple string equality (RFC 3986 §6.2.1): no\n * normalisation, no case folding of the host, no trailing-slash tolerance. A\n * trailing slash that differs between the document and the guard is a real\n * misconfiguration that will make a real client's `aud` check fail, and\n * startup is a better place to hear about it than a support ticket. Note that\n * the two strings compared are *different* strings — the resource is\n * `https://mcp.example.com/mcp` and the metadata URL is\n * `https://mcp.example.com/.well-known/oauth-protected-resource/mcp` — so each\n * is compared against its own counterpart.\n *\n * Where the guard is configured in another process this SDK can see only one\n * side and checks nothing; omit the argument there and configure both from one\n * constant, which is what `metadataUrl` is for.\n *\n * @example\n * ```ts\n * const metadata = protectedResourceMetadata({\n * resource: 'https://mcp.example.com/mcp',\n * authorizationServers: ['https://axiam.example.com'],\n * scopesSupported: ['mcp:read', 'mcp:tools'],\n * });\n * const session = {\n * ...baseSession,\n * expectedAudience: metadata.document.resource,\n * resourceMetadataUrl: metadata.metadataUrl,\n * };\n *\n * app.use(axiamMiddleware(session));\n * serveProtectedResourceMetadata(app, metadata, session);\n * ```\n */\nexport function serveProtectedResourceMetadata(\n app: McpMetadataApp,\n metadata: ProtectedResourceMetadata,\n guard?: McpGuardConfig,\n): ProtectedResourceMetadata {\n const op = 'serveProtectedResourceMetadata';\n\n if (guard) {\n if (guard.resourceMetadataUrl !== metadata.metadataUrl) {\n refuse(\n op,\n 'resourceMetadataUrl',\n `is ${JSON.stringify(guard.resourceMetadataUrl)} but this document is published at ${JSON.stringify(metadata.metadataUrl)} — the challenge would point at a document that is not this resource server's`,\n );\n }\n if (guard.expectedAudience !== metadata.document.resource) {\n refuse(\n op,\n 'expectedAudience',\n `is ${JSON.stringify(guard.expectedAudience)} but this document announces ${JSON.stringify(metadata.document.resource)} — the document would announce one identifier while the guard checked \\`aud\\` against another, so every token the flow produced would be refused`,\n );\n }\n }\n\n // Serialized once: the response is identical for every caller (§28.3 rule 4),\n // so there is nothing per-request to build.\n const body = JSON.stringify(metadata.document);\n\n if (isFastify(app)) {\n // Fastify appends `; charset=utf-8` to any `*json*` content type that\n // carries no charset parameter, and offers no supported way to suppress\n // it short of writing to `reply.raw` and losing every `onSend` hook. The\n // media type is still `application/json`, which is what §28.3 rule 1 pins\n // and what a client parses; the Express surface emits the bare form.\n app.get(metadata.metadataPath, async (_request: FastifyRequest, reply: FastifyReply) =>\n reply\n .code(200)\n .header('content-type', 'application/json')\n .header('cache-control', 'public, max-age=3600')\n .header('access-control-allow-origin', '*')\n .send(body),\n );\n return metadata;\n }\n\n app.get(metadata.metadataPath, (_req: ExpressRequest, res: ExpressResponse) => {\n // `res.setHeader`/`res.end` rather than `res.type`/`res.json`: Express\n // appends `; charset=utf-8` to a content type set through its own helper,\n // and §28.3 rule 1 pins the header to `application/json`.\n res.statusCode = 200;\n res.setHeader('Content-Type', 'application/json');\n res.setHeader('Cache-Control', 'public, max-age=3600');\n res.setHeader('Access-Control-Allow-Origin', '*');\n res.end(body);\n });\n return metadata;\n}\n\n/**\n * Tell a Fastify instance from an Express application/router.\n *\n * `addHook` is the discriminator: Fastify has it and Express has nothing of\n * the kind, so this never depends on how either library spells `get`.\n */\nfunction isFastify(app: McpMetadataApp): app is FastifyInstance {\n return typeof (app as Partial<FastifyInstance>).addHook === 'function';\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 /**\n * Optional application-owned data, e.g. the page the user was heading to\n * before login. The login glue stores it only when it is a same-origin\n * relative path (CONTRACT.md §12.8 rule 3) and checks it again before\n * redirecting, whatever a store returns.\n */\n returnTo?: string;\n /**\n * SHA-256 (lower-case hex) of the browser-binding cookie the login glue set\n * for this login (CONTRACT.md §12.3 rule 1, §12.8 rule 1; contract 1.68).\n *\n * Optional so that a store written for contract 1.67 still compiles and an\n * entry without it can still be read — but the 1.68 callback refuses such an\n * entry with the uniform 401. A caller-supplied store MUST persist and return\n * it unchanged. It is not secret (it is a digest of a random value) but it is\n * not logged either.\n */\n bindingDigest?: 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 * Default maximum number of entries a {@link MemoryOidcStateStore} holds.\n *\n * The login route is unauthenticated and every call saves one entry, so\n * without a bound a client looping on it grows the map for the whole\n * 10-minute TTL. At the bound the oldest entry is evicted: its login fails\n * once and the user starts again, which is the cheaper failure than the\n * process running out of memory.\n */\nexport const OIDC_STATE_MAX_ENTRIES = 10_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, and\n * bounded at {@link OIDC_STATE_MAX_ENTRIES} entries (oldest evicted). 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 readonly #maxEntries: 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 * @param maxEntries the most entries held at once. Defaults to\n * {@link OIDC_STATE_MAX_ENTRIES}; at the bound, saving a new entry evicts\n * the oldest. Must be a positive integer.\n */\n constructor(ttlMs: number = OIDC_STATE_TTL_MS, maxEntries: number = OIDC_STATE_MAX_ENTRIES) {\n if (!Number.isInteger(maxEntries) || maxEntries < 1) {\n throw new RangeError('MemoryOidcStateStore maxEntries must be a positive integer');\n }\n this.#ttlMs = Math.min(ttlMs, OIDC_STATE_TTL_MS);\n this.#maxEntries = maxEntries;\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 // Re-saving a state replaces it; re-insert so it counts as the newest.\n this.#entries.delete(entry.state);\n // A Map iterates in insertion order, so the first key is the oldest entry.\n while (this.#entries.size >= this.#maxEntries) {\n const oldest = this.#entries.keys().next();\n if (oldest.done) break;\n this.#entries.delete(oldest.value);\n }\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","// Shared \"Login with AXIAM\" core (CONTRACT.md §12) — the ONE\n// begin/complete + state-store + error-mapping path both the Express\n// `oidcLoginHandlers` and the Fastify `oidcLoginPlugin` call, mirroring how\n// `authzCore.ts` is the one §11 path and `verifyCore.ts` the one §10 path.\n//\n// This module is framework-agnostic on purpose: it takes plain values in and\n// returns a discriminated `OidcLoginOutcome` out, so each adapter only has to\n// translate an outcome into that framework's redirect/JSON response. It\n// performs no token extraction and touches no `req`/`reply` object.\n//\n// The browser binding (CONTRACT.md §12.8 rule 1, contract 1.68; C7) is the one\n// piece of cookie state the flow needs, and rule 1 (f) puts it here without\n// breaking that rule: `beginOidcLogin` RETURNS the `Set-Cookie` value to send,\n// and `completeOidcLogin` TAKES the presented cookie value as a parameter. The\n// adapters do the cookie I/O and nothing else. See\n// `docs/login-glue-binding.md` for the design and the order of the checks.\n//\n// The state store is what makes the two HTTP requests of a redirect flow into\n// one login: `oidcBegin` produces `state`/`nonce`/`code_verifier` in the\n// login request, and only `state` survives the round trip through the IdP, so\n// the other two must be parked somewhere the callback request can reach\n// (§12.3 rule 1 — the SDK itself stores nothing).\n\nimport { createHash, randomBytes, timingSafeEqual } from 'node:crypto';\nimport { AuthError, NetworkError } from '../core/index.js';\nimport type { OidcClient } from '../node/oidc.js';\nimport { OIDC_STATE_TTL_MS, type OidcStateEntry, type OidcStateStore } from '../node/oidcState.js';\nimport type { OidcTokenSet } from '../node/oidcTypes.js';\nimport type { AuthzLogger, ErrorBody } from './authzCore.js';\n\n/**\n * Configuration shared by the login and callback handlers (CONTRACT.md §12).\n *\n * @typeParam TRequest - the framework's request type, handed to\n * {@link OidcLoginOptions.onSuccess} (§12.8 rule 2). Express's\n * `oidcLoginHandlers` fixes it to Express's `Request`, Fastify's\n * `oidcLoginPlugin` to `FastifyRequest`. A plain `OidcLoginOptions` (the\n * default, `unknown`) is accepted by both.\n */\nexport interface OidcLoginOptions<TRequest = unknown> {\n /** The relying-party client driving the flow (built with `createOidcClient`). */\n client: OidcClient;\n /**\n * Where in-flight login state is parked between the login redirect and the\n * callback. {@link MemoryOidcStateStore} is a ready single-process\n * implementation; a multi-instance deployment needs a shared one, and that\n * store MUST persist and return {@link OidcStateEntry.bindingDigest}\n * unchanged (§12.3 rule 1) or every callback is refused.\n */\n store: OidcStateStore;\n /**\n * The relying party's redirect URI — must be the public URL of the callback\n * route, and is replayed verbatim on the token exchange (the server compares\n * the two).\n *\n * It also selects the browser-binding cookie's name (§12.8 rule 1 (b)):\n * `__Host-axiam_oidc_bind` everywhere, except `axiam_oidc_bind` (without\n * `Secure`) when it is plain `http:` on a loopback host (`localhost`,\n * `127.0.0.1`, `[::1]`), where a browser would not store a `Secure` cookie.\n */\n redirectUri: string;\n /** Requested scope. `openid` is added automatically when absent (§12.1 rule 4). */\n scope?: string | string[];\n /**\n * Where to send the browser after a successful login. Falls back to the\n * `returnTo` captured at login time — only when it passes the §12.8 rule 3\n * check — then to a JSON summary.\n */\n successRedirect?: string;\n /**\n * Optional widening of the `returnTo` rule (CONTRACT.md §12.8 rule 3).\n *\n * By default a `returnTo` is followed only when it is a same-origin relative\n * path ({@link isSafeReturnTo}). This predicate is consulted — at login and\n * again before the redirect — **only** for a value the default rule refuses,\n * and the value is honoured only when it returns `true`: for example an\n * allowlist of the application's other origins. Never pass a predicate that\n * accepts arbitrary absolute URLs; that reopens the open redirect.\n */\n allowReturnTo?: (value: string) => boolean;\n /**\n * Called with the validated token set once the exchange succeeds — the hook\n * where an application establishes its OWN session (sign a cookie, write a\n * session row, …). The SDK deliberately does not do this for you: what a\n * session means is the application's decision.\n *\n * Receives the consumed state entry too, so `returnTo` and any other\n * application data captured at login time is available, and (contract 1.68,\n * §12.8 rule 2) the framework request that completed the sign-in, so the\n * session can be created on it without ambient context. It runs only after\n * the browser binding and every §12.4 ID-token check have passed.\n */\n onSuccess?: (tokens: OidcTokenSet, entry: OidcStateEntry, request: TRequest) => void | Promise<void>;\n /** Debug-only logger. Receives failure reasons, never token material, `state`, `nonce`, the verifier or the binding cookie. */\n logger?: AuthzLogger;\n}\n\n/**\n * What the callback adapter hands {@link completeOidcLogin} besides the query:\n * the request-side inputs the framework-neutral core cannot read itself\n * (CONTRACT.md §12.8 rule 1 (f)).\n */\nexport interface OidcCallbackContext<TRequest = unknown> {\n /**\n * The value of the browser-binding cookie the callback request presented —\n * the cookie named by {@link oidcBindingCookieName} for the configured\n * `redirectUri`, and only that name. Absent means no cookie: the callback is\n * refused with the uniform 401.\n */\n bindingCookie?: string;\n /** The framework request, passed through to `onSuccess` (§12.8 rule 2). */\n request?: TRequest;\n}\n\n/**\n * What a login/callback handler should do next — one arm per response shape.\n * Adapters translate this into their framework's API and add nothing of their\n * own, so Express and Fastify cannot drift.\n */\nexport type OidcLoginOutcome =\n | {\n /** Send a 302 to {@link url}. */\n kind: 'redirect';\n /** Target of the redirect: the IdP authorization URL, or the post-login destination. */\n url: string;\n /** A complete `Set-Cookie` header value the adapter MUST send with this response (§12.8 rule 1). */\n setCookie?: string;\n }\n | {\n /** Reply `200` with {@link body} — the fallback when no post-login redirect is configured. */\n kind: 'json';\n /** A token-free summary of the established login. */\n body: OidcLoginSuccessBody;\n /** A complete `Set-Cookie` header value the adapter MUST send with this response (§12.8 rule 1). */\n setCookie?: string;\n }\n | {\n /** Reply {@link status} with the standardized `{ error, message }` body. */\n kind: 'error';\n /** HTTP status: 400 malformed callback, 401 authentication failure, 503 AXIAM unreachable. */\n status: number;\n /** Standardized error body (§10/§11 shape). */\n body: ErrorBody;\n /** A complete `Set-Cookie` header value the adapter MUST send with this response (§12.8 rule 1). */\n setCookie?: string;\n };\n\n/** The token-free success summary returned when no post-login redirect is configured. */\nexport interface OidcLoginSuccessBody {\n /** Always `true` — the ID token validated and the login completed. */\n authenticated: true;\n /** The authenticated subject from the validated ID token, when the server issued one. */\n sub?: string;\n /** Access-token lifetime in seconds, for a caller sizing its own session. */\n expiresIn: number;\n}\n\n/** The callback query parameters the flow reads (RFC 6749 §4.1.2 / §4.1.2.1). */\nexport interface OidcCallbackQuery {\n /** The `state` the IdP echoed back — matched against the stored entry. */\n state?: string;\n /** The authorization code, on success. */\n code?: string;\n /** An RFC 6749 error code, when the IdP refused instead of issuing a code. */\n error?: string;\n /** The IdP's description of {@link error}. */\n error_description?: string;\n}\n\nfunction authenticationFailedBody(message: string): ErrorBody {\n return { error: 'authentication_failed', message };\n}\n\nfunction invalidRequestBody(message: string): ErrorBody {\n return { error: 'invalid_request', message };\n}\n\nfunction unavailableBody(message: string): ErrorBody {\n return { error: 'oidc_unavailable', message };\n}\n\n/**\n * The browser-binding cookie name on every `https:` redirect URI, and on plain\n * HTTP to any host that is not loopback (CONTRACT.md §12.8 rule 1 (a)).\n */\nexport const OIDC_BINDING_COOKIE_NAME = '__Host-axiam_oidc_bind';\n\n/**\n * The browser-binding cookie name used ONLY for a plain-HTTP loopback\n * `redirectUri` (`http://localhost`, `http://127.0.0.1`, `http://[::1]`), where\n * a browser will not store the `Secure` cookie the `__Host-` prefix requires\n * (CONTRACT.md §12.8 rule 1 (b)). Never selected off loopback.\n */\nexport const OIDC_BINDING_COOKIE_NAME_LOOPBACK = 'axiam_oidc_bind';\n\n/** The uniform refusal: unknown, expired, consumed state and every binding failure (§12.8 rule 1 (c)). */\nconst UNIFORM_STATE_FAILURE = 'unknown, expired, or already-used login state';\n\nconst LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);\n\n/** Whether `redirectUri` is plain HTTP to a loopback host — the one case §12.8 rule 1 (b) relaxes. */\nfunction isPlainHttpLoopback(redirectUri: string): boolean {\n try {\n const url = new URL(redirectUri);\n return url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname);\n } catch {\n // An unparseable redirect URI is not loopback: fall to the strict name.\n return false;\n }\n}\n\n/**\n * The browser-binding cookie name for `redirectUri` (CONTRACT.md §12.8 rule 1\n * (b)): {@link OIDC_BINDING_COOKIE_NAME_LOOPBACK} for plain HTTP on a loopback\n * host, {@link OIDC_BINDING_COOKIE_NAME} everywhere else. The login sets, and\n * the callback reads, the name this returns — and only that name.\n */\nexport function oidcBindingCookieName(redirectUri: string): string {\n return isPlainHttpLoopback(redirectUri) ? OIDC_BINDING_COOKIE_NAME_LOOPBACK : OIDC_BINDING_COOKIE_NAME;\n}\n\n/** `Set-Cookie` attributes shared by the set and the clear, so the two always match. */\nfunction bindingCookieAttributes(redirectUri: string): string {\n return isPlainHttpLoopback(redirectUri) ? 'Path=/; HttpOnly; SameSite=Lax' : 'Path=/; HttpOnly; Secure; SameSite=Lax';\n}\n\n/** Max-Age of the binding cookie: the store's maximum TTL (§12.8 rule 1 (a) — at most 600 s). */\nconst BINDING_COOKIE_MAX_AGE_SEC = Math.floor(OIDC_STATE_TTL_MS / 1000);\n\nfunction setBindingCookie(redirectUri: string, value: string): string {\n return `${oidcBindingCookieName(redirectUri)}=${value}; ${bindingCookieAttributes(redirectUri)}; Max-Age=${BINDING_COOKIE_MAX_AGE_SEC}`;\n}\n\n/**\n * The clearing `Set-Cookie` header value every callback response carries\n * (§12.8 rule 1 (d)): the binding cookie's name for `redirectUri`, an empty\n * value, `Max-Age=0`, and the same `Path=/`, `HttpOnly`, `SameSite=Lax` and\n * (except on a plain-HTTP loopback `redirectUri`) `Secure` attributes it was\n * set with, and no `Domain`. A browser honours a clear only when the name and\n * those attributes repeat exactly, so a direct caller of {@link completeOidcLogin}\n * must send this value rather than build one by hand.\n *\n * The Express and Fastify adapters send it themselves when\n * {@link completeOidcLogin} throws (the store or `onSuccess` failed), so the\n * error response clears the cookie too.\n */\nexport function oidcBindingClearCookie(redirectUri: string): string {\n return `${oidcBindingCookieName(redirectUri)}=; ${bindingCookieAttributes(redirectUri)}; Max-Age=0`;\n}\n\n/**\n * Percent-encode a redirect destination for use as a `Location` header value,\n * by the rules of docs/login-glue-binding.md Decision 7 (normative there):\n *\n * 1. every lone surrogate becomes U+FFFD, so the encoder never\n * throws, whatever the surrogates' arrangement;\n * 2. every character outside the URL-safe set\n * `! # $ % & ' ( ) * + , - . / 0-9 : ; = ? @ A-Z [ \\ ] ^ _ a-z | ~` is\n * UTF-8 percent-encoded with upper-case hex (space, CR, LF, non-ASCII, `\"`,\n * `<`, `>`, `` ` ``, `{`, `}`, DEL, every control character);\n * 3. a `%` that does not start a well-formed `%XX` escape becomes `%25`; one\n * that does is kept, so an encoded value is not encoded twice.\n *\n * The result is pure ASCII. Express's `res.redirect` (`encodeurl`) differs\n * from rule 3 for `%%41` and a truncated `%2`, and from rule 1 for adjacent\n * lone surrogates (it throws), so both adapters call this first.\n *\n * @internal Exported for the framework adapters; the destination is encoded by\n * the adapter, never by the application's hook.\n */\nexport function encodeRedirectLocation(destination: string): string {\n return destination\n .replace(/[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/g, '\\uFFFD')\n .replace(/[^\\x21\\x23-\\x3B\\x3D\\x3F-\\x5F\\x61-\\x7A\\x7C\\x7E]+|%(?![0-9A-Fa-f]{2})/g, encodeURI);\n}\n\n/** SHA-256 (lower-case hex) of the ASCII bytes of the cookie value as set (§12.8 rule 1 (a)). */\nfunction bindingDigest(value: string): string {\n return createHash('sha256').update(value, 'ascii').digest('hex');\n}\n\n/**\n * Constant-time comparison of the presented cookie's digest with the entry's\n * (§12.8 rule 1 (c)). A missing cookie, a missing or ill-typed digest, or a\n * difference all return `false`.\n */\nfunction bindingMatches(entry: OidcStateEntry, presented: string | undefined): boolean {\n const stored = (entry as { bindingDigest?: unknown }).bindingDigest;\n if (typeof presented !== 'string' || presented.length === 0 || typeof stored !== 'string') {\n return false;\n }\n const expected = Buffer.from(bindingDigest(presented), 'utf8');\n const actual = Buffer.from(stored, 'utf8');\n // Both sides are 64 hex digits for a genuine entry; a length mismatch is a\n // malformed entry, not a secret, and timingSafeEqual requires equal lengths.\n if (expected.length !== actual.length) {\n return false;\n }\n return timingSafeEqual(expected, actual);\n}\n\n/**\n * The default `returnTo` rule (CONTRACT.md §12.8 rule 3; C6): `true` only for\n * a same-origin relative path — it starts with a single `/`, does not start\n * with `//` or `/\\`, and contains no `\\` anywhere and no control character\n * (U+0000–U+001F, U+007F). Absolute URLs (`https://…`), scheme-relative ones\n * (`//host/…`) and backslash forms (`/\\host`, `/a\\b`) are all refused.\n *\n * Both framework adapters reach it through {@link beginOidcLogin} (which drops\n * a refused value before storing) and {@link completeOidcLogin} (which checks\n * the stored value again before redirecting), so Express and Fastify share one\n * implementation.\n */\nexport function isSafeReturnTo(value: string): boolean {\n if (value.length === 0 || value[0] !== '/') {\n return false;\n }\n if (value.startsWith('//') || value.startsWith('/\\\\')) {\n return false;\n }\n return !/[\\\\\\u0000-\\u001f\\u007f]/.test(value);\n}\n\n/** Apply the default rule, then — only for a value it refuses — the integrator's predicate (§12.8 rule 3). */\nfunction acceptedReturnTo(value: unknown, allowReturnTo: ((value: string) => boolean) | undefined): string | undefined {\n if (typeof value !== 'string') {\n return undefined;\n }\n if (isSafeReturnTo(value)) {\n return value;\n }\n if (allowReturnTo !== undefined) {\n try {\n if (allowReturnTo(value) === true) {\n return value;\n }\n } catch {\n // A predicate that throws accepts nothing.\n }\n }\n return undefined;\n}\n\n/**\n * Step 1 — build the authorization request, park its state, and hand back the\n * redirect (CONTRACT.md §12.1 `oidc_begin`).\n *\n * Discovery is fetched through `oidcDiscover`, so its per-origin cache and\n * single-flight de-duplication apply and a busy login route does not hammer\n * the discovery endpoint (§12.3 rule 6).\n *\n * **Browser binding (contract 1.68, §12.8 rule 1 (a)).** Every login draws a\n * fresh 32-byte CSPRNG value, stores its SHA-256 on the entry as\n * {@link OidcStateEntry.bindingDigest}, and returns the value in the redirect\n * outcome's `setCookie`, which the adapter MUST send. A cookie the request\n * already presents is never reused.\n *\n * @param options the shared login configuration.\n * @param returnTo optional application destination to restore after login.\n * Stored only when it passes {@link isSafeReturnTo} (or\n * {@link OidcLoginOptions.allowReturnTo}); any other value is dropped, as if\n * none had been given (§12.8 rule 3).\n */\nexport async function beginOidcLogin<TRequest = unknown>(\n options: OidcLoginOptions<TRequest>,\n returnTo?: string,\n): Promise<OidcLoginOutcome> {\n try {\n const configuration = await options.client.oidcDiscover();\n const request = options.client.oidcBegin({\n configuration,\n redirectUri: options.redirectUri,\n ...(options.scope !== undefined ? { scope: options.scope } : {}),\n });\n const safeReturnTo = acceptedReturnTo(returnTo, options.allowReturnTo);\n if (returnTo !== undefined && safeReturnTo === undefined) {\n options.logger?.debug('axiam_sdk.oidc', 'dropped a returnTo that is not a same-origin relative path');\n }\n const binding = randomBytes(32).toString('base64url');\n await options.store.save({\n state: request.state,\n nonce: request.nonce,\n codeVerifier: request.codeVerifier,\n redirectUri: options.redirectUri,\n ...(safeReturnTo !== undefined ? { returnTo: safeReturnTo } : {}),\n bindingDigest: bindingDigest(binding),\n });\n return { kind: 'redirect', url: request.url, setCookie: setBindingCookie(options.redirectUri, binding) };\n } catch (err) {\n // A login route that cannot reach AXIAM must fail closed with 503 rather\n // than redirect the browser somewhere half-built.\n options.logger?.debug('axiam_sdk.oidc', 'oidc login could not be started', {\n reason: err instanceof Error ? err.message : 'unknown',\n });\n return { kind: 'error', status: 503, body: unavailableBody('could not start the OIDC login flow') };\n }\n}\n\n/**\n * Step 2 — validate the callback, consume the stored state, check the browser\n * binding, exchange the code, and hand back the post-login response\n * (CONTRACT.md §12.1 `oidc_exchange`, §12.8).\n *\n * Order (§12.8 rule 1 (c)): the entry is consumed FIRST, so `state` stays\n * single-use whatever happens next; then the presented binding cookie's\n * SHA-256 is compared in constant time with the entry's digest; only then is\n * the code exchanged and `onSuccess` called. Every outcome carries a\n * `setCookie` that clears the binding cookie (rule 1 (d)).\n *\n * Failure mapping:\n * - IdP returned `error=…` instead of a code → `401 authentication_failed`;\n * - `state` or `code` missing → `400 invalid_request`;\n * - `state` unknown, already consumed, or expired; no binding cookie; an entry\n * with no `bindingDigest`; or a different cookie → `401\n * authentication_failed` with ONE body, so the refusal does not say which\n * check failed, and with no request to the token endpoint;\n * - any §12.4 ID-token failure or `OAuthProtocolError` (an `AuthError`\n * sub-type) → `401 authentication_failed`;\n * - `NetworkError` → `503 oidc_unavailable`, never a silent success.\n *\n * Errors that are not a login outcome — `options.store.consume` rejects, or\n * `options.onSuccess` throws — propagate unchanged to the caller, so the\n * application's own error handling sees them. The state is already consumed\n * by then. The caller MUST still clear the binding cookie on the error\n * response it sends (rule 1 (d), \"and any other error\"), with the\n * `Set-Cookie` value {@link oidcBindingClearCookie} returns for the same\n * `redirectUri`; the Express and Fastify adapters append it before re-throwing.\n *\n * @param context the presented binding cookie and the framework request. A\n * caller that passes no `bindingCookie` has every callback refused (rule 1\n * (f)).\n */\nexport async function completeOidcLogin<TRequest = unknown>(\n options: OidcLoginOptions<TRequest>,\n query: OidcCallbackQuery,\n context: OidcCallbackContext<TRequest> = {},\n): Promise<OidcLoginOutcome> {\n const setCookie = oidcBindingClearCookie(options.redirectUri);\n\n if (query.error) {\n options.logger?.debug('axiam_sdk.oidc', 'idp returned an authorization error', { error: query.error });\n return {\n kind: 'error',\n status: 401,\n body: authenticationFailedBody(\n query.error_description ? `${query.error}: ${query.error_description}` : query.error,\n ),\n setCookie,\n };\n }\n if (!query.state || !query.code) {\n return {\n kind: 'error',\n status: 400,\n body: invalidRequestBody('callback is missing the state or code query parameter'),\n setCookie,\n };\n }\n\n // Single-use consume (§12.3 rule 1), and FIRST (§12.8 rule 1 (c)): a\n // replayed callback finds nothing, and a callback refused below for its\n // binding has still spent the state.\n const entry = await options.store.consume(query.state);\n if (!entry) {\n options.logger?.debug('axiam_sdk.oidc', 'no stored login state for the callback state');\n return { kind: 'error', status: 401, body: authenticationFailedBody(UNIFORM_STATE_FAILURE), setCookie };\n }\n if (!bindingMatches(entry, context.bindingCookie)) {\n // Login CSRF (C7): this request is not from the browser that started the\n // login. Same status and body as an unknown state; the code is NOT\n // exchanged and onSuccess is NOT called. Neither value is logged.\n options.logger?.debug('axiam_sdk.oidc', 'login state is not bound to this browser');\n return { kind: 'error', status: 401, body: authenticationFailedBody(UNIFORM_STATE_FAILURE), setCookie };\n }\n\n let tokens: OidcTokenSet;\n try {\n tokens = await options.client.oidcExchange({\n code: query.code,\n codeVerifier: entry.codeVerifier,\n nonce: entry.nonce,\n redirectUri: entry.redirectUri,\n });\n } catch (err) {\n if (err instanceof NetworkError) {\n options.logger?.debug('axiam_sdk.oidc', 'token exchange transport failure');\n return {\n kind: 'error',\n status: 503,\n body: unavailableBody('the AXIAM token endpoint is unreachable'),\n setCookie,\n };\n }\n // AuthError (including OAuthProtocolError and every §12.4 reason code) and\n // anything unexpected: a login that cannot be proven is a failed login.\n const reason = err instanceof AuthError ? err.message : 'token exchange failed';\n options.logger?.debug('axiam_sdk.oidc', 'token exchange failed', { reason });\n return { kind: 'error', status: 401, body: authenticationFailedBody(reason), setCookie };\n }\n\n await options.onSuccess?.(tokens, entry, context.request as TRequest);\n\n // §12.8 rule 3: the stored value is checked again — a caller-supplied store\n // or an entry written by older glue may hold anything.\n const destination = options.successRedirect ?? acceptedReturnTo(entry.returnTo, options.allowReturnTo);\n if (destination) {\n return { kind: 'redirect', url: destination, setCookie };\n }\n return {\n kind: 'json',\n body: {\n authenticated: true,\n ...(typeof tokens.idClaims?.sub === 'string' ? { sub: tokens.idClaims.sub } : {}),\n expiresIn: tokens.expiresIn,\n },\n setCookie,\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 *\n * A non-finite value (`NaN`, `±Infinity`) — or anything that is not a number —\n * is refused with a `TypeError` rather than clamped: `NaN` survives\n * `Math.min`/`Math.max` unchanged, and every `exp`/`iat` comparison against it\n * is `false`, so an ID token would never expire. A finite value above the\n * bound is still clamped down, not refused (§12.4 rule 5).\n *\n * @throws TypeError when `clockSkewSec` is defined and not a finite number.\n */\nexport function resolveClockSkewSec(clockSkewSec?: number): number {\n if (clockSkewSec === undefined) {\n return MAX_CLOCK_SKEW_SEC;\n }\n if (typeof clockSkewSec !== 'number' || !Number.isFinite(clockSkewSec)) {\n throw new TypeError('clockSkewSec must be a finite number of seconds');\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). The key\n// set is held by {@link JwksCache}, which implements CONTRACT.md §12.4 rule 2\n// itself (contract 1.69, D-10): a single cooldown window for refreshes\n// (unknown `kid` included), stale-if-error bounded at TTL + 300 s after the\n// last SUCCESSFUL fetch, and an empty key set treated as a failed fetch.\n// `jose` still does the key matching (`createLocalJWKSet`) and the\n// verification; it no longer fetches, because its remote key set cannot keep\n// serving a held key past a failed refresh.\n//\n// Pitfall 1 (jose is ESM-only): `jose` 5+/6.x ships no CJS entry condition,\n// so a tsup CJS build's transpiled `require('jose')` would throw\n// `ERR_REQUIRE_ESM`. `createVerifier` obtains jose via a dynamic\n// `await import('jose')`, deferring resolution to first call rather than\n// module-load time — this keeps `require('axiam-sdk/grpc')` (or any other\n// CJS entry that reaches this module) from throwing at import time.\n\nimport { AuthError } from '../core/index.js';\nimport {\n assertIdTokenAlg,\n checkIdTokenClaims,\n ID_TOKEN_ALG,\n idTokenAuthError,\n resolveClockSkewSec,\n type IdTokenClaims,\n type IdTokenExpectations,\n} from './oidcIdToken.js';\n\n/** Verified claims carried by an AXIAM access token (the JWT payload {@link Verifier.verifyAccessToken} returns). */\nexport interface AxiamClaims {\n /** Subject — user ID (UUID). */\n sub: string;\n /** Tenant ID (UUID). */\n tenant_id: string;\n /** Organization ID (UUID), if present. */\n org_id?: string;\n /** Issuer — the AXIAM authorization server that minted the token. */\n iss: string;\n /** Issued-at time (epoch seconds), if present. */\n iat?: number;\n /** Expiry time (epoch seconds); the verifier rejects the token once it has passed. */\n exp: number;\n /** Unique token ID / session id — needed for logout(). */\n jti?: string;\n /** Token audience — \"axiam:user\" | \"axiam:m2m\". */\n aud?: string;\n /** OAuth2 scopes (space-separated). */\n scope?: string;\n /**\n * RFC 7800 / RFC 8705 §3.1 confirmation claim — present **only** on a\n * sender-constrained token (CONTRACT.md §10.1 rule 9, contract 1.15).\n *\n * Its presence changes what the token *is*. Without it, the token is a\n * bearer credential: whoever holds it may use it. With it, the token names\n * a key, and accepting it without proving the caller holds that key\n * converts it straight back into a bearer token.\n *\n * {@link Verifier.verifyAccessToken} checks this against the `proofs` you\n * pass it (contract 1.51 fix) — omit `proofs` (or pass `{}`) and a token\n * carrying `cnf` is refused, never silently accepted as a bearer token.\n * Supply the evidence your transport holds (a certificate thumbprint, a\n * verified DPoP key thumbprint, or both) to accept a bound token. See\n * {@link verifyCertificateBinding} / {@link verifyTokenBinding} for the\n * shared implementation `verifyAccessToken` reuses.\n */\n cnf?: CnfClaim;\n}\n\n/**\n * RFC 7800 confirmation claim.\n *\n * Deliberately an object with one optional field rather than a union: RFC 7800\n * permits confirmation methods this SDK does not implement, and such a token\n * must still *parse*. What it must not do is validate — see\n * {@link verifyCertificateBinding}.\n */\nexport interface CnfClaim {\n /**\n * RFC 8705 §3.1 — base64url (unpadded) SHA-256 of the DER client\n * certificate the token was issued to.\n */\n 'x5t#S256'?: string;\n /**\n * RFC 9449 §6.1 — base64url (unpadded) RFC 7638 thumbprint of the DPoP\n * public key the token was issued to (contract 1.16).\n */\n jkt?: string;\n}\n\n/**\n * The proofs a caller can present for a sender-constrained token\n * (contract 1.16, CONTRACT.md §10.1 rule 9).\n *\n * Both fields are optional because a caller may hold one, both or neither —\n * and \"neither\" is legitimate for an ordinary bearer token, which is why\n * {@link verifyTokenBinding} accepts `{}` and returns when the token names no\n * confirmation.\n *\n * @remarks\n * **Every thumbprint must come from the transport.** Take the certificate\n * thumbprint from the TLS peer certificate\n * (`TLSSocket.getPeerCertificate().raw` under Node), or from a *trusted*\n * terminating proxy over a channel your application controls. Never from a\n * caller-settable header: a forgeable input makes the mechanism decorative.\n */\nexport interface PresentedProofs {\n /** RFC 8705 §3.1 `x5t#S256` of the peer certificate on this connection. */\n certificateThumbprint?: string;\n /**\n * RFC 9449 §6.1 `jkt` of the key that signed a DPoP proof this SDK has\n * **already verified** for this request's `htm`/`htu`.\n *\n * Supplying a value here asserts the proof checked out. A thumbprint lifted\n * off an unverified proof would let a proof captured from any other\n * endpoint authorize this request.\n */\n dpopThumbprint?: string;\n}\n\n/**\n * CONTRACT.md §10.1 **rule 9** — enforce a token's sender constraint against\n * the certificate the caller presented on **this** connection\n * (RFC 8705 §3, contract 1.15).\n *\n * `presentedThumbprint` is the RFC 8705 §3.1 `x5t#S256` of the peer\n * certificate: base64url, **unpadded**, SHA-256 over the **DER** encoding.\n * {@link certificateThumbprintS256} computes it from DER bytes.\n *\n * | token's `cnf` | `presentedThumbprint` | result |\n * |---|---|---|\n * | absent | anything | returns — an ordinary bearer token |\n * | `x5t#S256` | equal | returns |\n * | `x5t#S256` | different, or `undefined` | **throws** |\n * | present, no `x5t#S256` | anything | **throws** |\n *\n * The first row is why adopting this rule breaks nothing: an unbound token is\n * still accepted whether or not a certificate is present. The last row is the\n * one that is easy to get wrong — a `cnf` naming a method this SDK cannot\n * check is an *unverifiable constraint*, never *no constraint*. Read the\n * other way, a sender-constrained token silently degrades to a bearer token\n * the day a newer AXIAM issues a confirmation this SDK predates.\n *\n * @remarks\n * **The thumbprint must come from the transport.** Take it from the TLS peer\n * certificate (`TLSSocket.getPeerCertificate().raw` under Node) or from a\n * value a *trusted* terminating proxy forwarded over a channel your\n * application controls. Never from a caller-settable request header: a\n * forgeable input makes the whole mechanism decorative.\n *\n * @throws {Error} on any of the three rejecting rows. The §10 middleware\n * wraps this into an `AuthError`.\n */\nexport function verifyCertificateBinding(\n claims: Pick<AxiamClaims, 'cnf'>,\n presentedThumbprint: string | undefined,\n): void {\n const cnf = claims.cnf;\n if (cnf === undefined || cnf === null) return;\n\n const expected = cnf['x5t#S256'];\n if (typeof expected !== 'string' || expected.length === 0) {\n // Includes the DPoP case: this entry point has no proof to check, so a\n // `jkt`-bound token is refused rather than silently downgraded.\n throw new Error(\n 'token carries a cnf confirmation naming a method this entry point cannot verify ' +\n '(CONTRACT.md §10.1 rule 9 — an unverifiable constraint is not an absent one; ' +\n 'use verifyTokenBinding for DPoP)',\n );\n }\n // A token naming BOTH methods is a conjunction (contract 1.16): this\n // function can establish one half and must not answer for the whole.\n // Refusing here is what stops \"check whichever we can\".\n if (typeof cnf.jkt === 'string' && cnf.jkt.length > 0) {\n throw new Error(\n 'token names both a certificate and a DPoP key; both must hold ' +\n '(CONTRACT.md §10.1 rule 9) — use verifyTokenBinding',\n );\n }\n if (presentedThumbprint === undefined) {\n throw new Error('token is certificate-bound but no client certificate was presented');\n }\n if (!constantTimeEqual(expected, presentedThumbprint)) {\n throw new Error('token is bound to a different client certificate than the one presented');\n }\n}\n\n/**\n * CONTRACT.md §10.1 **rule 9** — enforce a token's sender constraint against\n * **every** proof the caller presented (contract 1.16).\n *\n * This is the full rule, and the one to use unless your transport genuinely\n * cannot produce a DPoP thumbprint.\n *\n * | token's `cnf` | certificate | DPoP | result |\n * |---|---|---|---|\n * | absent | anything | anything | returns — an ordinary bearer token |\n * | `x5t#S256` | equal | ignored | returns |\n * | `x5t#S256` | different or absent | ignored | **throws** |\n * | `jkt` | ignored | equal | returns |\n * | `jkt` | ignored | different or absent | **throws** |\n * | both | equal | equal | returns — **conjunction** |\n * | both | either wrong or missing | — | **throws** |\n * | present, names neither | anything | anything | **throws** |\n *\n * Two rows carry the weight. **Both present is a conjunction**: an operator\n * who turned on two constraints asked for two, and satisfying the more\n * convenient one is not compliance. **Names neither is a refusal**: a\n * confirmation this SDK cannot interpret is an unverifiable constraint, and\n * reading it as \"unconstrained\" is the exact downgrade rule 9 exists to\n * prevent. That includes an *empty* `cnf` — which is also how proto3 delivers\n * an empty `CnfClaim` over gRPC (§10.3 rule 3).\n *\n * @remarks\n * This function compares thumbprints; it does **not** verify proofs. Supply\n * `dpopThumbprint` only after checking the proof's signature, `htm`, `htu`,\n * `iat` and `jti` for *this* request.\n *\n * @throws {Error} on any rejecting row. The §10 middleware wraps this into an\n * `AuthError`.\n */\nexport function verifyTokenBinding(\n claims: Pick<AxiamClaims, 'cnf'>,\n proofs: PresentedProofs = {},\n): void {\n const cnf = claims.cnf;\n // The fast path, and the common one. First on purpose: an unbound token is\n // accepted with no proofs at all, which is what keeps existing deployments\n // working when a guard adopts this rule.\n if (cnf === undefined || cnf === null) return;\n\n const expectedCert = typeof cnf['x5t#S256'] === 'string' && cnf['x5t#S256'].length > 0\n ? cnf['x5t#S256']\n : undefined;\n const expectedJkt = typeof cnf.jkt === 'string' && cnf.jkt.length > 0 ? cnf.jkt : undefined;\n\n if (expectedCert === undefined && expectedJkt === undefined) {\n throw new Error(\n 'token carries a cnf confirmation naming no method this SDK can verify ' +\n '(CONTRACT.md §10.1 rule 9 — an unverifiable constraint is not an absent one)',\n );\n }\n\n // Each arm that applies must pass. Written as two independent checks rather\n // than a switch on the pair precisely so \"both named\" needs no branch of its\n // own — it is simply the case where both run.\n if (expectedCert !== undefined) {\n if (proofs.certificateThumbprint === undefined) {\n throw new Error('token is certificate-bound but no client certificate was presented');\n }\n if (!constantTimeEqual(expectedCert, proofs.certificateThumbprint)) {\n throw new Error('token is bound to a different client certificate than the one presented');\n }\n }\n\n if (expectedJkt !== undefined) {\n if (proofs.dpopThumbprint === undefined) {\n throw new Error('token is DPoP-bound but no verified DPoP proof was presented');\n }\n if (!constantTimeEqual(expectedJkt, proofs.dpopThumbprint)) {\n throw new Error('token is bound to a different DPoP key than the one presented');\n }\n }\n}\n\n/**\n * Constant-time string comparison for {@link verifyCertificateBinding}.\n *\n * The thumbprint is usually public — it derives from a certificate sent in the\n * clear during the handshake — so this is defence in depth. It matters most\n * for a self-signed client, where the registered thumbprint is the whole\n * credential. Hand-rolled rather than `crypto.timingSafeEqual` so that this\n * function stays usable in the browser build, where `node:crypto` is absent.\n */\nfunction constantTimeEqual(a: string, b: string): boolean {\n // Length inequality short-circuits, leaking only the length. Both operands\n // are fixed-length base64url SHA-256 digests whenever either is well-formed.\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i += 1) {\n diff |= a.charCodeAt(i) ^ b.charCodeAt(i);\n }\n return diff === 0;\n}\n\n/**\n * Compute the RFC 8705 §3.1 `x5t#S256` thumbprint of a DER client\n * certificate: base64url-encoded SHA-256, **without** padding.\n *\n * Unpadded is not a style choice — RFC 7515 §2 defines base64url in JOSE as\n * omitting `=`, and a padded value will not compare equal to what AXIAM put in\n * the token.\n *\n * Node only (it needs `node:crypto`). A browser-side guard has no peer\n * certificate to fingerprint in the first place.\n */\nexport async function certificateThumbprintS256(der: Uint8Array): Promise<string> {\n const { createHash } = await import('node:crypto');\n return createHash('sha256').update(der).digest('base64url');\n}\n\n/** Path (relative to the client base URL) of the org-wide JWKS endpoint. */\nexport const JWKS_PATH = '/oauth2/jwks';\n\nconst COOLDOWN_DURATION_MS = 60_000;\nconst TIMEOUT_DURATION_MS = 5_000;\n/** Default and maximum lifetime of a fetched key set (CONTRACT.md §12.4 rule 2, contract 1.69; D-10). */\nconst JWKS_MAX_TTL_MS = 300_000;\n/** How long past its TTL a held set keeps verifying while every refresh fails (contract 1.69; D-10). */\nconst JWKS_MAX_STALE_MS = 300_000;\n/**\n * The largest JWKS response body read, in bytes: 50 KiB, the cap the Java SDK applies. A one-key\n * EdDSA set is a few hundred bytes, so this is generous; CONTRACT.md §12.4 states no figure.\n */\nconst JWKS_MAX_BODY_BYTES = 50 * 1024;\n\n/**\n * The response body as parsed JSON, read through a byte cap. A declared `Content-Length` over the cap\n * is refused before a byte is read; otherwise the stream is counted and cancelled (closing the\n * connection) at the first byte past the cap, so a hostile endpoint is never buffered whole. Either\n * refusal throws, which is a failed refresh. Used by both fetch paths.\n */\nasync function readCappedJson(res: Response, maxBytes: number): Promise<unknown> {\n const declared = res.headers.get('content-length');\n if (declared !== null && /^\\d+$/.test(declared.trim()) && Number(declared) > maxBytes) {\n await res.body?.cancel().catch(() => undefined);\n throw new Error('JWKS response too large');\n }\n const reader = res.body?.getReader();\n if (reader === undefined) throw new Error('JWKS response has no body');\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > maxBytes) {\n await reader.cancel().catch(() => undefined);\n throw new Error('JWKS response too large');\n }\n chunks.push(value);\n }\n return JSON.parse(new TextDecoder().decode(Buffer.concat(chunks)));\n}\n\n/** The lifetime the response advertises, clamped to {@link JWKS_MAX_TTL_MS}; the default when it advertises none. An advertised value is clamped silently. */\nfunction ttlFromResponse(res: Response): number {\n const m = /(?:^|[\\s,])max-age=(\\d+)/i.exec(res.headers.get('cache-control') ?? '');\n if (m === null) return JWKS_MAX_TTL_MS;\n const ms = Number(m[1]) * 1000;\n return Number.isFinite(ms) ? Math.min(ms, JWKS_MAX_TTL_MS) : JWKS_MAX_TTL_MS;\n}\n\n/**\n * The TLS material the JWKS fetch presents, the same material the REST client\n * uses (CONTRACT.md §6 `customCa`, §6.1 client identity): `ca` extends server\n * trust, `cert`/`key` are the client identity. There is deliberately no\n * verification switch; strict server verification stays at its default.\n */\nexport interface JwksTlsOptions {\n /** PEM bundle trusted in addition to the default roots (§6). */\n ca?: string;\n /** PEM client-certificate chain (§6.1). */\n cert?: string;\n /** PEM private key for `cert` (§6.1). Secret: never logged or retained. */\n key?: string;\n}\n\n/**\n * `fetch` over `node:https` with explicit TLS material. Node's global `fetch`\n * takes no CA or client identity (only a dispatcher from the separate `undici`\n * package, which this SDK does not depend on), so a private-CA or mTLS\n * deployment needs this path. It never follows a redirect and honours `signal`\n * for cancellation and the deadline. Only `200` and `304` are answered; any\n * other status destroys the response and rejects at once. The returned promise\n * settles exactly once on every path.\n */\nasync function fetchWithTls(\n url: string,\n init: { headers: Record<string, string>; signal: AbortSignal },\n tls: JwksTlsOptions,\n): Promise<Response> {\n // `.default` is the live CommonJS module object (what instrumentation such as msw patches), not the ESM snapshot of its named exports.\n const https = (await import('node:https')).default;\n const { Readable } = await import('node:stream');\n const tlsMod = await import('node:tls');\n // `ca` would REPLACE the process trust store (bundled roots, OpenSSL's under\n // --use-openssl-ca, NODE_EXTRA_CA_CERTS). CONTRACT.md §6 makes `customCa` an\n // ADDED anchor, so it goes into a secure context that starts from that store.\n let secureContext: import('node:tls').SecureContext | undefined;\n if (tls.ca !== undefined) {\n secureContext = tlsMod.createSecureContext({\n ...(tls.cert !== undefined ? { cert: tls.cert } : {}),\n ...(tls.key !== undefined ? { key: tls.key } : {}),\n });\n (secureContext as unknown as { context: { addCACert(pem: string): void } }).context.addCACert(tls.ca);\n }\n return new Promise<Response>((resolve, reject) => {\n let settled = false;\n const settle = (fn: () => void): void => {\n if (settled) return;\n settled = true;\n fn();\n };\n const agent = new https.Agent(\n secureContext !== undefined\n ? { secureContext }\n : {\n ...(tls.cert !== undefined ? { cert: tls.cert } : {}),\n ...(tls.key !== undefined ? { key: tls.key } : {}),\n },\n );\n const fail = (message = 'unexpected JWKS status'): void => {\n agent.destroy();\n settle(() => reject(new Error(message)));\n };\n const req = https.request(\n url,\n { method: 'GET', headers: init.headers, signal: init.signal, agent },\n (res) => {\n try {\n const status = res.statusCode ?? 0;\n if (status !== 200 && status !== 304) {\n res.destroy();\n fail();\n return;\n }\n const headers = new Headers();\n for (const [name, value] of Object.entries(res.headers)) {\n if (value !== undefined) headers.set(name, Array.isArray(value) ? value.join(', ') : value);\n }\n if (status === 304) res.resume();\n const body = status === 304 ? null : (Readable.toWeb(res) as unknown as ReadableStream<Uint8Array>);\n const response = new Response(body, { status, headers }); // built before settling: a throw here lands in the catch\n res.on('close', () => agent.destroy());\n settle(() => resolve(response));\n } catch {\n res.destroy();\n fail();\n }\n },\n );\n req.on('error', (err) => {\n agent.destroy();\n settle(() => reject(err));\n });\n req.on('close', () => {\n // Closed before any response was delivered: nothing else will settle us.\n if (!settled) fail('JWKS request closed before a response');\n });\n req.end();\n });\n}\n\ntype JoseModule = typeof import('jose');\ntype KeyResolver = ReturnType<JoseModule['createLocalJWKSet']>;\n\n/**\n * The verifier's key-set cache (CONTRACT.md §12.4 rule 2, contract 1.69).\n *\n * - **Age** is measured from the last *successful* fetch (a `200` with at least\n * one key, or a `304` to a conditional request); a failed refresh — transport\n * error, any other status, a non-JWKS body, an EMPTY key set — never replaces\n * the held keys and never moves that anchor.\n * - **TTL** is the response's `Cache-Control: max-age`, 300 s when it has none,\n * and at most 300 s.\n * - **Stale-if-error**: held keys verify until exactly TTL + 300 s after the\n * anchor; from then on every token is refused until a fetch succeeds.\n * - **One window for every refresh** (TTL-due and unknown-`kid` alike): at most\n * one attempt per {@link COOLDOWN_DURATION_MS}, a failed attempt counted. An\n * unknown-`kid` refresh that fails refuses that token and changes nothing else.\n * - Concurrent callers share one in-flight fetch.\n */\nclass JwksCache {\n #resolver: KeyResolver | undefined;\n #etag: string | undefined;\n #anchorMs = 0;\n #ttlMs = JWKS_MAX_TTL_MS;\n #lastAttemptMs: number | undefined;\n #inflight: Promise<void> | undefined;\n /** Held privately: it may carry the client key, and must not be an enumerable property. */\n readonly #tls: JwksTlsOptions | undefined;\n\n constructor(\n private readonly jwksUri: string,\n private readonly jose: JoseModule,\n tls?: JwksTlsOptions,\n ) {\n this.#tls = tls;\n }\n\n /** The key resolver handed to `jwtVerify`. */\n readonly getKey = async (\n ...args: Parameters<KeyResolver>\n ): Promise<Awaited<ReturnType<KeyResolver>>> => {\n // Held keys are not trusted while the age is negative (a clock stepped back) nor past the bound.\n const usable = (): KeyResolver | undefined =>\n this.#resolver !== undefined &&\n Date.now() >= this.#anchorMs &&\n Date.now() < this.#anchorMs + this.#ttlMs + JWKS_MAX_STALE_MS\n ? this.#resolver\n : undefined;\n\n // A refresh is due when nothing is held, the held set is past its TTL, or the clock\n // moved backwards (negative age: never fresh). A verification whose held set is still\n // usable does not wait for it; one with nothing usable waits for the (single-flight,\n // self-bounded) fetch.\n const nowMs = Date.now();\n if (this.#resolver === undefined || nowMs < this.#anchorMs || nowMs >= this.#anchorMs + this.#ttlMs) {\n const refresh = this.#refreshIfAllowed();\n if (usable() === undefined) await refresh;\n }\n\n const held = usable();\n if (held === undefined) {\n throw new this.jose.errors.JOSEError('the JSON Web Key Set is unavailable');\n }\n try {\n return await held(...args);\n } catch (err) {\n if (!(err instanceof this.jose.errors.JWKSNoMatchingKey)) throw err;\n // Unknown kid: a refresh like any other, in the same window.\n await this.#refreshIfAllowed();\n const refreshed = usable();\n if (refreshed === undefined) throw err;\n return refreshed(...args);\n }\n };\n\n async #refreshIfAllowed(): Promise<void> {\n if (this.#inflight !== undefined) return this.#inflight;\n const now = Date.now();\n const sinceLast = this.#lastAttemptMs === undefined ? Infinity : now - this.#lastAttemptMs;\n if (sinceLast >= 0 && sinceLast < COOLDOWN_DURATION_MS) return; // (a backwards clock never blocks)\n this.#lastAttemptMs = now; // a failed attempt counts toward the window\n this.#inflight = this.#fetch()\n .catch(() => undefined) // a failed refresh changes nothing\n .finally(() => {\n this.#inflight = undefined;\n });\n return this.#inflight;\n }\n\n async #fetch(): Promise<void> {\n const conditional = this.#resolver !== undefined && this.#etag !== undefined;\n const headers = { accept: 'application/json', ...(conditional ? { 'if-none-match': this.#etag as string } : {}) };\n const signal = AbortSignal.timeout(TIMEOUT_DURATION_MS);\n // TLS material only matters for an https URL; the global `fetch` cannot carry it (#175).\n const res =\n this.#tls !== undefined && new URL(this.jwksUri).protocol === 'https:'\n ? await fetchWithTls(this.jwksUri, { headers, signal }, this.#tls)\n : await fetch(this.jwksUri, { redirect: 'manual', signal, headers });\n if (res.status === 304 && conditional) {\n await res.body?.cancel().catch(() => undefined);\n this.#anchorMs = Date.now();\n this.#ttlMs = ttlFromResponse(res);\n return;\n }\n if (res.status !== 200) {\n await res.body?.cancel().catch(() => undefined); // release the connection\n throw new Error('unexpected JWKS status');\n }\n const doc = (await readCappedJson(res, JWKS_MAX_BODY_BYTES)) as { keys?: unknown };\n const isJwk = (k: unknown): boolean =>\n typeof k === 'object' && k !== null && !Array.isArray(k) && typeof (k as { kty?: unknown }).kty === 'string';\n if (typeof doc !== 'object' || doc === null || !Array.isArray(doc.keys) || !doc.keys.some(isJwk)) {\n throw new Error('not a JWKS document with a key');\n }\n // Entries are taken one by one: a JWK object with a string `kty` counts even if jose cannot\n // use it (it is skipped at lookup); anything else is dropped rather than refusing the set.\n const usable = (doc.keys as unknown[]).filter(isJwk);\n const resolver = this.jose.createLocalJWKSet({ keys: usable } as Parameters<JoseModule['createLocalJWKSet']>[0]);\n this.#resolver = resolver;\n const etag = res.headers.get('etag');\n // An ETag with a control character or over 256 bytes is never stored or echoed.\n this.#etag =\n etag !== null && Buffer.byteLength(etag) <= 256 && !/[\\x00-\\x1f\\x7f]/.test(etag) ? etag : undefined;\n this.#anchorMs = Date.now();\n this.#ttlMs = ttlFromResponse(res);\n }\n}\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 * | 9 | `cnf` | (contract 1.51 fix) `proofs` defaults to `{}` — no evidence — so a token carrying `cnf` is refused unless the caller supplies matching evidence. Enforced by handing the verified claims and `proofs` to {@link verifyTokenBinding}, the same function {@link verifyCertificateBinding}, `authenticateRequest` and a hand-rolled guard share, so local verification never disagrees with itself about whether a token is a bearer token. An unbound token is unaffected whether or not `proofs` is supplied. |\n * | 10 | `typ` | (contract 1.68) a header `typ` that is present must be `at+jwt` (case-insensitive, `application/` allowed); `JWT`, `logout+jwt`, `secevent+jwt` and every `axiam-…+jwt` purpose type are refused. No `typ` is not refused by this rule. See `isAccessTokenTyp` (exported from `axiam-sdk/node`). |\n * | 11 | `purpose` | (contract 1.68) a payload carrying a `purpose` member is refused, whatever its value. |\n * | 12 | `kid` | (contract 1.68) a header with no `kid` is refused before any key lookup — there is no \"only key in the set\" fallback on this path. An unknown `kid` follows the §12.4 rule 2 re-fetch window. |\n *\n * **`proofs` and which entry point to call.** This method is the SDK's\n * documented §10 guard entry point (see {@link verifySignatureOnlyUnchecked}),\n * and until the contract 1.51 fix it applied rules 1–8 only: it had no\n * transport to ask for a certificate, so it silently treated every\n * `cnf`-bound token as an ordinary bearer credential — precisely the\n * SEC-071/SEC-080 downgrade §10.1 rule 9 exists to close, and exactly what\n * every device token `authenticateDevice()` (§6.1) mints. `proofs` is now\n * how a caller supplies that evidence: a certificate thumbprint the\n * transport verified for this connection, a DPoP key thumbprint from a\n * proof the caller has **itself** verified per §21.7, or both. Omitting it\n * (or passing `{}`) is exactly {@link verifySignatureOnlyUnchecked}'s\n * opposite number for rule 9 — refuse rather than guess — and is the\n * correct default for a caller with no transport evidence to offer; an\n * unbound token is accepted either way, which is what keeps every existing\n * bearer-only deployment working unchanged.\n *\n * Rejects with the underlying error on any failed rule; the §10 middleware\n * wraps that into an `AuthError`.\n */\n verifyAccessToken(\n token: string,\n expectations: AccessTokenExpectations,\n proofs?: PresentedProofs,\n ): 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 * `aud` or `cnf` (rule 9) check whatsoever: an expired token, a\n * not-yet-valid token, a token minted for a *different tenant* in the same\n * organization, and a certificate- or DPoP-bound token presented with no\n * evidence at all, all pass. It exists only for integrators deliberately\n * implementing their own policy on top of the signature — the `Unchecked`\n * suffix is there to make that omission obvious at the call site. Anything\n * guarding a route MUST use {@link Verifier.verifyAccessToken}, passing\n * `proofs` when it may see a certificate- or DPoP-bound token (or, better,\n * the §10 middleware built on it, which does this automatically).\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 fetched/cached lazily by {@link JwksCache}, not\n * eagerly 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, tlsOptions?: JwksTlsOptions): JwksVerifier {\n return createJwksVerifier(`${baseUrl}${JWKS_PATH}`, tlsOptions);\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 * key-set cache per verifier instance, shared by\n * `verifyAccessToken` and `verifyIdToken`.\n *\n * `tlsOptions` (Node only) is the {@link JwksTlsOptions} the key-set fetch\n * presents — pass the client's `customCa` / client identity so a private-CA\n * server's JWKS is reachable (#175). Omitted, the platform defaults apply.\n * A client identity (`cert`/`key`) given here is presented to WHATEVER origin\n * `jwksUri` names; the SDK's own callers withhold it from a `jwks_uri` on a\n * different origin than the client's base URL, a direct caller must do the same.\n */\nexport function createJwksVerifier(jwksUri: string, tlsOptions?: JwksTlsOptions): JwksVerifier {\n // Lazily-resolved singleton so repeated verifyAccessToken() calls reuse\n // one cache instead of rebuilding it per call.\n //\n // D-08/D-09 (single-flight, PERF-03): a concurrent burst against a cold\n // cache, or of unknown `kid`s, collapses to ONE network fetch: `JwksCache`\n // shares its in-flight fetch between callers and allows one attempt per\n // cooldown window. Proven by `test/node/jwks.test.ts`'s \"collapses N\n // concurrent verifyAccessToken calls ... to exactly one JWKS fetch\" test.\n let jwksPromise: Promise<JwksCache> | null = null;\n\n async function getJwks(): Promise<JwksCache['getKey']> {\n if (!jwksPromise) {\n jwksPromise = import('jose').then((jose) => new JwksCache(jwksUri, jose, tlsOptions));\n }\n return (await jwksPromise).getKey;\n }\n\n return {\n async verifyAccessToken(\n token: string,\n expectations: AccessTokenExpectations,\n proofs: PresentedProofs = {},\n ): Promise<AxiamClaims> {\n const { jwtVerify } = await import('jose');\n\n // §10.1 rules 10 and 12 (contract 1.68; N14) — read from the header\n // BEFORE any key lookup. Rule 12: a token with no `kid` is refused here,\n // because jose's remote key set would otherwise select \"the only key in\n // the set\" for it — and AXIAM's purpose tokens (MFA challenge, MFA setup,\n // WebAuthn state) carry no `kid` while being signed with the\n // access-token key (the logout token carries one from contract 1.69). Rule 10: a present `typ` must be\n // `at+jwt`. Both are access-token-path rules only; `verifyIdToken` below\n // and the logout-token path apply their own.\n assertAccessTokenHeader(token);\n\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 // §10.1 rule 11 (contract 1.68; N14): a claim set carrying `purpose` is\n // a purpose token, never an access token — whatever its value (`null`\n // included) and whatever `typ` said. Read off the verified payload\n // itself, not a claims model that might drop unknown members.\n assertNoPurposeClaim(payload);\n\n const claims = payload as unknown as AxiamClaims;\n\n // §10.1 rule 9 (contract 1.51 fix). This entry point is the SDK's\n // documented guard — its own `verifySignatureOnlyUnchecked` doc says so\n // — so it must not accept a `cnf`-bound token as an ordinary bearer\n // credential just because it was handed no evidence. `proofs` defaults\n // to `{}` (no evidence), which is exactly the \"reject\" row of rule 9's\n // table for a bound token; an unbound token is unaffected. Reuses\n // `verifyTokenBinding` rather than duplicating it, so this entry point\n // and `authenticateRequest`/a hand-rolled guard can never disagree\n // about whether a token is a bearer token.\n verifyTokenBinding(claims, proofs);\n\n return claims;\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 rules 10 and 12 (contract 1.68; N14) — the header half of\n * \"this token is an access token\": the JOSE header MUST carry a non-empty\n * `kid` (no single-key fallback), and a `typ` that is present MUST satisfy\n * {@link isAccessTokenTyp}.\n *\n * Exported so the §10 guard (`authenticateRequest`) re-asserts it on its own\n * side, as it does rule 4, without trusting a caller-supplied {@link Verifier}\n * to have applied it. Decodes the header without verifying anything else.\n *\n * @throws AuthError when the token is not a three-segment JWS with a JSON\n * header, carries no `kid`, or carries a `typ` other than `at+jwt`.\n */\nexport function assertAccessTokenHeader(token: string): void {\n let header: { kid?: unknown; typ?: unknown };\n try {\n const segments = token.split('.');\n if (segments.length !== 3) {\n throw new Error('not three segments');\n }\n const parsed: unknown = JSON.parse(Buffer.from(segments[0], 'base64url').toString('utf8'));\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n throw new Error('header is not an object');\n }\n header = parsed as { kid?: unknown; typ?: unknown };\n } catch {\n throw new AuthError('access token is not a well-formed JWS');\n }\n if (typeof header.kid !== 'string' || header.kid.length === 0) {\n throw new AuthError('access token carries no kid header (CONTRACT.md §10.1 rule 12)');\n }\n if (header.typ !== undefined && !isAccessTokenTyp(header.typ)) {\n throw new AuthError('token typ is not at+jwt: not an access token (CONTRACT.md §10.1 rule 10)');\n }\n}\n\n/**\n * CONTRACT.md §10.1 rule 11 (contract 1.68; N14): a claim set carrying a\n * `purpose` member is a purpose token (MFA challenge, MFA setup, WebAuthn\n * state), never an access token — whatever the value, `null` included, and\n * whatever `typ` said. Pass the verified payload itself, not a claims model\n * that may drop unknown members.\n *\n * @throws AuthError when `payload` has an own `purpose` member.\n */\nexport function assertNoPurposeClaim(payload: object): void {\n if (Object.prototype.hasOwnProperty.call(payload, 'purpose')) {\n throw new AuthError('token carries a purpose claim: not an access token (CONTRACT.md §10.1 rule 11)');\n }\n}\n\n/**\n * CONTRACT.md §10.1 rule 10 (contract 1.68): whether a JOSE `typ` names an\n * access token — `at+jwt` (RFC 9068 §2.1), compared ASCII case-insensitively,\n * with or without the `application/` media-type prefix (RFC 7515 §4.1.9),\n * exactly as the server compares it. A non-string `typ` is not one.\n */\nexport function isAccessTokenTyp(typ: unknown): boolean {\n if (typeof typ !== 'string') {\n return false;\n }\n const lower = typ.toLowerCase();\n return lower === 'at+jwt' || lower === 'application/at+jwt';\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 // `JwksCache` has already performed its single re-fetch-then-fail step\n // here (one refresh per cooldown window on an unmatched kid) — exactly\n // 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","// CONTRACT.md §10.1 rule 9 (contract 1.15/1.16/1.51) — deriving the ONE piece\n// of transport evidence `authenticateRequest` can gather on its own: the\n// client certificate the TLS layer verified for THIS connection, when Node\n// itself terminated TLS.\n//\n// This is deliberately the only automatic evidence source. §10.1 detail 2 is\n// explicit that the comparison input \"MUST come from the transport\" and\n// \"MUST NOT\" come from a caller-settable header — a raw `net.Socket`'s own\n// `getPeerCertificate()` is exactly the transport, nothing forwarded. DPoP\n// evidence is NOT derived here: proof verification (§21.7) is a materially\n// larger obligation the middleware does not undertake automatically, and\n// `verifyTokenBinding`'s own contract is to refuse a jkt-bound token when no\n// verified proof is supplied — which is correct, not a gap this file needs\n// to fill.\n\nimport type { PresentedProofs } from '../node/jwks.js';\nimport { certificateThumbprintS256 } from '../node/jwks.js';\n\n/**\n * The minimal shape a Node `net.Socket`/`tls.TLSSocket` needs for this\n * module to read a peer certificate off it. `encrypted` is TLSSocket's own\n * \"always true\" marker (Node's documented way to tell a TLS socket from a\n * plain one); `getPeerCertificate` is TLSSocket's method.\n */\nexport interface PeerCertificateSocket {\n /** `tls.TLSSocket`'s own \"this is a TLS socket\" marker — always `true` there, absent on a plain `net.Socket`. */\n encrypted?: boolean;\n /** `tls.TLSSocket.getPeerCertificate`. Returns the DER-encoded peer certificate, when `detailed` is `true` and one was presented. */\n getPeerCertificate?: (detailed?: boolean) => PeerCertificateLike | undefined;\n}\n\n/** The one field this module reads off `tls.TLSSocket.getPeerCertificate()`'s return value. */\nexport interface PeerCertificateLike {\n /** The DER-encoded certificate bytes, when a certificate was presented. */\n raw?: Uint8Array;\n}\n\n/**\n * Derive {@link PresentedProofs} from a request's raw socket.\n *\n * Returns `{}` (no evidence) whenever there is nothing to read: `socket` is\n * absent or not TLS-shaped, `encrypted` is not `true` (a plain `net.Socket`\n * — no TLS at all, or TLS terminated by a proxy that forwards nothing to\n * this process), or `getPeerCertificate()` returned no certificate (the\n * common case: nothing requested one, or the handshake carried none). `{}`\n * is the same shape `verifyTokenBinding`'s default parameter already means\n * \"no proofs\" — an unbound token is accepted either way, and a bound one is\n * refused, exactly CONTRACT.md §10.1 rule 9 detail 3's \"the SDK cannot see\n * any client certificate at all\" case: fail closed, never silently accept.\n *\n * Does **not** check whether the certificate chains to any particular CA —\n * possession is what a completed TLS handshake already proves (the peer\n * demonstrated the matching private key to get this far), and comparing the\n * resulting thumbprint against the token's `cnf` is `verifyTokenBinding`'s\n * job, not this function's.\n */\nexport async function certificateProofFromSocket(\n rawSocket: unknown,\n): Promise<PresentedProofs> {\n // `unknown` rather than `PeerCertificateSocket | null | undefined`: the\n // real callers (Express's `net.Socket`, Fastify's raw Node request socket)\n // are typed by @types/node with no `encrypted`/`getPeerCertificate`\n // members at all outside a `tls.TLSSocket` narrowing this module has no\n // reason to import — an all-optional interface with zero structural\n // overlap is exactly what TS's \"weak type\" check (TS2559) rejects at the\n // call site. The shape check below is the real guard either way.\n if (!rawSocket || typeof rawSocket !== 'object') {\n return {};\n }\n const socket = rawSocket as PeerCertificateSocket;\n if (socket.encrypted !== true || typeof socket.getPeerCertificate !== 'function') {\n return {};\n }\n let cert: PeerCertificateLike | undefined;\n try {\n cert = socket.getPeerCertificate(true);\n } catch {\n return {};\n }\n if (!cert?.raw || cert.raw.length === 0) {\n return {};\n }\n return { certificateThumbprint: await certificateThumbprintS256(cert.raw) };\n}\n","// Shared verify core (D-27, CONTRACT.md §10) — the ONE verification path\n// both Express and Fastify middleware call. Reuses the 17-03 local-JWKS\n// verifier (jose against the cached remote JWKS, EdDSA-only) — no\n// per-request round-trip to the AXIAM server on a cache hit, and no\n// additional TTL bookkeeping beyond jose's own `exp` check (§10 \"MUST NOT\n// cache session verification results longer than the token's remaining\n// TTL\").\n\nimport { AuthError } from '../core/index.js';\nimport {\n assertAccessTokenHeader,\n assertNoPurposeClaim,\n assertTenantClaim,\n type PresentedProofs,\n type Verifier,\n} from '../node/jwks.js';\nimport type { RevocationFeed } from '../node/revocationFeed.js';\n\n/**\n * Minimal session shape the middleware needs: a JWKS verifier (D-11) and the\n * tenant this resource server is configured for (CR-03). JWKS is org-wide,\n * not tenant-scoped (node/jwks.ts) — `tenantHeaderValue` is what lets\n * `authenticateRequest` reject a validly-signed token minted for a\n * DIFFERENT tenant in the same org (CONTRACT.md §10.1 rule 4).\n */\nexport interface VerifiableSession {\n /** Local JWKS verifier (D-11) — validates the token's EdDSA signature against the org-wide cached JWKS, offline on a cache hit. */\n jwksVerifier: Verifier;\n /**\n * The tenant this resource server is configured for (CR-03, §10.1 rule 4);\n * a validly-signed token minted for a different tenant in the same org is\n * rejected.\n *\n * @remarks\n * The claim it is compared against is the token's `tenant_id`, which is\n * always a UUID — so a resource server guarding routes MUST be configured\n * with `tenantId` (the UUID form), not `tenantSlug`. A slug-configured\n * session can never match and therefore rejects every request; that is\n * fail-closed by design, not a silent pass.\n */\n tenantHeaderValue: string;\n /**\n * CONTRACT.md §10.1 rule 5 — expected token issuer. Optional and unset by\n * default: the rule is conditional on configuration, and the SDK never\n * hardcodes an issuer. When set, a token whose `iss` differs is rejected.\n * Populated from `AxiamClientOptions.expectedIssuer`.\n */\n expectedIssuer?: string;\n /**\n * CONTRACT.md §10.1 rule 6 — expected token audience. Optional and unset by\n * default. A resource server guarding user-facing routes SHOULD set\n * `\"axiam:user\"`. Populated from `AxiamClientOptions.expectedAudience`.\n */\n expectedAudience?: string;\n /**\n * CONTRACT.md §28.5 (contract 1.48) — the URL of this resource server's RFC\n * 9728 protected-resource metadata document.\n *\n * Unset by default, and **setting it is what turns §28 on**. With it unset\n * every guard built from this session behaves byte-for-byte as it did before\n * §28 existed: no `WWW-Authenticate` header on any response, no status\n * changed, no body changed.\n *\n * With it set, the guard's 401s carry §28.4's challenge, a\n * `require_access`/`requireAccessHook` denial that named a scope and came\n * back `no_grant` carries `insufficient_scope`, and the path this URL names\n * is served without authentication so the document can start the handshake\n * it exists to start.\n *\n * **{@link VerifiableSession.expectedAudience} becomes mandatory.** Every\n * guard factory refuses the configuration at construction — before the first\n * request — when this is set and that is not, and the refusal names both. A\n * resource server that publishes \"tokens for me carry this `aud`\" and then\n * does not check `aud` is opened by a token minted for a different resource\n * server, which is the confusion RFC 8707 exists to prevent.\n *\n * Feed it from `protectedResourceMetadata(...).metadataUrl` rather than by\n * retyping the string — retyping is how the guard and the document come to\n * disagree.\n */\n resourceMetadataUrl?: string;\n /**\n * CONTRACT.md §10.4 (contract 1.44) — the optional session-revocation feed.\n *\n * Unset by default, and with it unset this guard behaves exactly as it did\n * before 1.44: a revoked session's access token verifies locally until it\n * expires, which is the §10.2 posture this narrows rather than replaces.\n *\n * It is never a control. A feed that cannot be read denies nothing, every\n * §10.1 rule runs first and still decides, and a token with no `sid` is\n * never matched against it.\n */\n revocationFeed?: RevocationFeed;\n}\n\n/** Authenticated identity injected as req.axiamUser / request.axiamUser (§10). */\nexport interface AxiamIdentity {\n /** The authenticated end user's id (the token's `sub` claim). */\n userId: string;\n /** The tenant the verified token was minted for (the token's `tenant_id` claim). */\n tenantId: string;\n /**\n * The verified token's `roles` claim (CONTRACT.md §10 interface contract,\n * §11.2 rule 11; contract 1.68): the names of the subject's global roles in\n * the tenant, as the server issued them.\n *\n * `undefined` when the token carries no `roles` claim — the application did\n * not request, or its client is not registered for, the `roles` scope — and\n * also when the claim is not a JSON array of strings. `[]` when the scope was\n * granted and the subject holds no such role. The two are kept apart on\n * purpose: one means \"ask for the scope\", the other \"the user holds none\".\n *\n * **Never filled from `scope`.** Through 1.3.x this held the `scope` claim\n * split on spaces (N15): a scope names what the *client* asked for, not\n * what the user holds. The granted scopes are {@link AxiamIdentity.scopes}.\n */\n roles?: string[];\n /**\n * The verified token's granted OAuth2 scopes: its `scope` claim split on\n * single spaces (RFC 6749 §3.3). `undefined` when the token has no `scope`\n * claim, or one that is not a string. Read by `requireScope`.\n */\n scopes?: string[];\n}\n\n/**\n * Verify `token` locally against `session`'s cached JWKS and map the\n * verified claims to the identity shape injected by both middleware\n * modules. `roles` is the token's `roles` claim and `scopes` its `scope`\n * claim; neither is derived from the other (contract 1.68, §11.2 rule 11).\n *\n * This is the SDK's **documented §10 guard entry point** for TypeScript, and\n * it applies the complete CONTRACT.md §10.1 minimum local-verification set:\n * rules 1/2/3/5/6/7 and 10–12 inside `verifyAccessToken` (EdDSA `alg` pinned\n * before key lookup, REQUIRED numeric `exp`, `nbf` when present, conditional\n * `iss`/`aud`, a named bounded clock skew; `typ` `at+jwt` when present, no\n * `purpose` claim, a REQUIRED `kid`), rule 4 — the `tenant_id` assertion — both\n * there and again here, so a caller-supplied `Verifier` implementation that\n * ignores its expectations still cannot get a cross-tenant token past the\n * middleware, and rule 9 — see `proofs` below.\n *\n * **`proofs` and rule 9.** A token carrying `cnf` is not a bearer token\n * (§10.1 rule 9): it may be used only by a presenter that proves possession\n * of the key it names. `proofs` is this function's transport evidence — a\n * certificate thumbprint the caller's TLS layer verified for this\n * connection, a DPoP key thumbprint from a proof the caller has **itself**\n * verified, or both — and it is passed straight into `verifyAccessToken`,\n * which is where rule 9 is now enforced (contract 1.51 fix; see\n * `verifyAccessToken`'s own doc in `node/jwks.ts`). There is deliberately no\n * *second* rule-9 check here: `verifyAccessToken` already reuses\n * `verifyTokenBinding` internally, and re-running that same check against\n * the same `proofs` a moment later would only be able to agree with itself —\n * the risk worth guarding against is a check run against *different* inputs\n * (for example the transport's real evidence at one call site and `{}` at\n * another), not the same evidence read twice.\n *\n * `proofs` defaults to `{}` — **no evidence** — so a `cnf`-bound token is\n * refused by default, which is the fail-closed, spec-correct behaviour for a\n * caller that has not supplied any: rule 9's table has no row where absent\n * evidence accepts a bound token. `axiamMiddleware`/`axiamPlugin` pass\n * `certificateProofFromSocket(req.socket)` automatically, so a resource\n * server whose Node process terminates TLS itself accepts a\n * certificate-bound token with no extra wiring; a deployment behind a proxy\n * that forwards nothing still refuses one, exactly as §10.1 rule 9 detail 3\n * requires. An unbound token is unaffected either way — this is the\n * positive regression rule 9 exists to protect, and its own test asserts it\n * explicitly.\n *\n * Throws `AuthError` on any verification failure (missing/invalid/expired\n * token, a token with no `exp`, a not-yet-valid `nbf`, a malformed/mismatched\n * sub/tenant_id claim, or an unsatisfiable `cnf`).\n */\nexport async function authenticateRequest(\n session: VerifiableSession,\n token: string,\n proofs: PresentedProofs = {},\n): Promise<AxiamIdentity> {\n let claims;\n try {\n // proofs flows straight into verifyAccessToken, which now applies rule 9\n // itself (contract 1.51 fix) — see the doc comment above for why this\n // stays a single check rather than a second one against the same\n // evidence.\n claims = await session.jwksVerifier.verifyAccessToken(\n token,\n {\n expectedTenantId: session.tenantHeaderValue,\n expectedIssuer: session.expectedIssuer,\n expectedAudience: session.expectedAudience,\n },\n proofs,\n );\n } catch (err) {\n throw new AuthError(err instanceof Error ? err.message : 'invalid or expired token');\n }\n\n if (!claims.sub) {\n throw new AuthError('invalid sub claim');\n }\n // CR-03 / §10.1 rule 4: JWKS is org-wide (node/jwks.ts), so signature\n // validity alone does NOT imply the token was minted for THIS resource\n // server's tenant. Re-asserted on the guard side (the verifier already did\n // it) because `VerifiableSession.jwksVerifier` is an interface a consumer\n // may implement themselves — the middleware must not delegate a\n // fail-closed control to a type it does not own.\n assertTenantClaim(claims.tenant_id, session.tenantHeaderValue);\n // §10.1 rules 10–12 (contract 1.68; N14), re-asserted for the same reason:\n // a caller-supplied Verifier that ignores them must not let an MFA\n // challenge or a WebAuthn state token through as an access token.\n assertAccessTokenHeader(token);\n assertNoPurposeClaim(claims);\n\n // §10.4 rules 4 and 6. Runs LAST: every §10.1 rule has already decided, and\n // the feed can only turn an accept into a reject. A token with no `sid`\n // names no session and is never matched — there is no fallback to `jti`,\n // which would match nothing while looking like it worked.\n const sid = (claims as { sid?: unknown }).sid;\n if (session.revocationFeed && typeof sid === 'string' && sid.length > 0) {\n if (await session.revocationFeed.isRevoked(sid)) {\n throw new AuthError(\n 'the session behind this access token has been revoked (CONTRACT.md §10.4)',\n );\n }\n }\n\n // §11.2 rule 11 (contract 1.68; N15): roles come from the `roles` claim\n // alone, and scopes from `scope` alone — the two never stand in for each\n // other. Read off the verified payload, not the typed claims model.\n const rawRoles = (claims as { roles?: unknown }).roles;\n const roles =\n Array.isArray(rawRoles) && rawRoles.every((role): role is string => typeof role === 'string')\n ? [...rawRoles]\n : undefined;\n const rawScope = (claims as { scope?: unknown }).scope;\n const scopes = typeof rawScope === 'string' ? rawScope.split(' ').filter(Boolean) : undefined;\n\n return {\n userId: claims.sub,\n tenantId: claims.tenant_id,\n ...(roles !== undefined ? { roles } : {}),\n ...(scopes !== undefined ? { scopes } : {}),\n };\n}\n","// Express middleware (D-27, CONTRACT.md §10). Express 5 handlers may be\n// async — an async middleware that rejects is automatically forwarded to\n// Express's error handling, but this middleware always resolves (never\n// rejects) since every failure path is caught and turned into a 401/403\n// JSON response itself.\n\nimport type { NextFunction, Request, RequestHandler, Response } from 'express';\nimport { AuthError, AuthzError } from '../core/index.js';\nimport {\n assertAuthzClient,\n authzDeniedBody as authzDeniedBodyShared,\n authzUnavailableBody,\n evaluateAccess,\n hasAnyRole,\n hasAnyScope,\n invalidRequestBody,\n missingAuthBody,\n resolveResourceId,\n ResourceResolutionError,\n type AuthzVerifiableSession,\n type RequireAccessOptions,\n type ResourceSpec,\n} from './authzCore.js';\nimport {\n CSRF_HEADER_NAME,\n extractCredential,\n isCsrfValid,\n isSafeMethod,\n parseCookieHeader,\n} from './cookieHeader.js';\nimport {\n challengeFor401,\n challengeFor403,\n isMetadataDocumentRequest,\n mcpGuardChallenges,\n} from './mcpCore.js';\nimport {\n beginOidcLogin,\n completeOidcLogin,\n encodeRedirectLocation,\n oidcBindingClearCookie,\n oidcBindingCookieName,\n type OidcLoginOptions,\n type OidcLoginOutcome,\n} from './oidcLoginCore.js';\nimport { certificateProofFromSocket } from './peerCertificate.js';\nimport { authenticateRequest, type AxiamIdentity, type VerifiableSession } from './verifyCore.js';\n\n/** An Express `Request` augmented with the AXIAM identity that `axiamMiddleware` injects after §10 verification. */\nexport interface AxiamRequest extends Request {\n /** The authenticated identity, present once `axiamMiddleware` (or `requireAuth`) has run; absent on an unauthenticated request. */\n axiamUser?: AxiamIdentity;\n}\n\ninterface ErrorBody {\n error: string;\n message: string;\n}\n\nfunction missingCredentialsBody(): ErrorBody {\n return { error: 'authentication_failed', message: 'missing authentication credentials' };\n}\n\nfunction invalidTokenBody(message: string): ErrorBody {\n return { error: 'authentication_failed', message };\n}\n\nfunction authzDeniedBody(message: string): ErrorBody {\n return { error: 'authorization_denied', message };\n}\n\nfunction csrfDeniedBody(): ErrorBody {\n return { error: 'authorization_denied', message: 'csrf validation failed' };\n}\n\n/**\n * `axiamMiddleware(session)` — extracts the session (cookie-first, then\n * `Authorization: Bearer` fallback), verifies it locally against the\n * cached JWKS (D-11, no per-request server round-trip on a cache hit),\n * and injects `req.axiamUser` on success. Returns 401 (AuthError) or 403\n * (AuthzError) with a standardized JSON error body on failure.\n *\n * **CSRF (cookie double-submit, CONTRACT.md §3):** when the credential was\n * sourced from the `axiam_access` COOKIE (not the `Authorization` header)\n * and the request method is state-changing (anything other than\n * GET/HEAD/OPTIONS), this middleware additionally requires the\n * `X-CSRF-Token` request header to be present and equal (constant time) to\n * the `axiam_csrf` cookie value, rejecting with 403 on mismatch/absence.\n * Bearer-header requests are CSRF-immune by construction — a cross-site\n * attacker cannot set arbitrary request headers — but a cookie\n * automatically attached by the browser is not, and in any same-site\n * deployment where `axiam_access` reaches this app, the non-`httpOnly`\n * `axiam_csrf` cookie does too. This mirrors, locally, the same\n * double-submit check the AXIAM server performs on its own endpoints (§3).\n */\nexport function axiamMiddleware(session: VerifiableSession): RequestHandler {\n // §28.5: validated and precomputed at construction, `undefined` when\n // `resourceMetadataUrl` is unset — which is what keeps a guard without §28\n // byte-for-byte identical to one from before §28 existed.\n const challenges = mcpGuardChallenges(session, 'axiamMiddleware');\n\n return async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n // §28.3 rule 2: the metadata document MUST answer without a credential,\n // and this guard is normally mounted globally — so the exemption is here,\n // explicit, and derived from the one path `resourceMetadataUrl` names.\n if (isMetadataDocumentRequest(challenges, req.method, req.originalUrl ?? req.url)) {\n next();\n return;\n }\n\n const credential = extractCredential(req.headers.cookie, req.headers.authorization);\n if (!credential) {\n // §28.4: no credential is not a bad credential, so the challenge names\n // no error code (RFC 6750 §3).\n if (challenges) res.setHeader('WWW-Authenticate', challenges.noCredential);\n res.status(401).json(missingCredentialsBody());\n return;\n }\n\n if (credential.source === 'cookie' && !isSafeMethod(req.method)) {\n const csrfHeader = req.headers[CSRF_HEADER_NAME];\n const csrfValue = Array.isArray(csrfHeader) ? csrfHeader[0] : csrfHeader;\n if (!isCsrfValid(req.headers.cookie, csrfValue)) {\n res.status(403).json(csrfDeniedBody());\n return;\n }\n }\n\n try {\n // §10.1 rule 9: the one piece of transport evidence this middleware can\n // gather on its own — the peer certificate the TLS layer verified for\n // THIS connection, when Node itself terminated TLS. `req.socket` is\n // `express`'s (Node's) raw socket; `{}` when it is not TLS-shaped or\n // carries no certificate, which is exactly \"no evidence\" and refuses a\n // cnf-bound token rather than accepting one (see verifyCore.ts).\n const proofs = await certificateProofFromSocket(req.socket);\n const identity = await authenticateRequest(session, credential.token, proofs);\n (req as AxiamRequest).axiamUser = identity;\n next();\n } catch (err) {\n if (err instanceof AuthzError) {\n // §28.5 rule 5: this 403 is not a `no_grant` scope denial, so it gains\n // no header.\n res.status(403).json(authzDeniedBody(err.message));\n return;\n }\n // §28.4: a credential was presented and rejected. Expired, not yet\n // valid, wrong tenant, wrong audience, bad signature, an unsatisfiable\n // `cnf`, a revoked `sid` — all of them are `invalid_token`,\n // indistinguishably. Every distinction a 401 draws for an\n // unauthenticated stranger is an oracle.\n if (challenges) res.setHeader('WWW-Authenticate', challenges.invalidToken);\n if (err instanceof AuthError) {\n res.status(401).json(invalidTokenBody(err.message));\n return;\n }\n res.status(401).json(invalidTokenBody('invalid or expired token'));\n }\n };\n}\n\n/**\n * `requireAuth(session)` (CONTRACT.md §11.1) — the canonical §11 name for\n * the same §10 guard `axiamMiddleware` already provides, for mounting\n * per-route (`router.get('/x', requireAuth(session), handler)`) rather than\n * globally via `app.use(axiamMiddleware(session))`. Pure sugar: it performs\n * no verification of its own beyond what `axiamMiddleware` already does.\n */\nexport function requireAuth(session: VerifiableSession): RequestHandler {\n return axiamMiddleware(session);\n}\n\n/**\n * `requireAccess(session, action, resource, opts?)` (CONTRACT.md §11) — a\n * per-route authorization guard layered strictly on top of the §10 guard.\n *\n * Throws synchronously (at route-setup time, not per-request) if\n * `session.authzClient` is not configured. Requires `req.axiamUser` to\n * already be set (by `axiamMiddleware`/`requireAuth` mounted earlier in the\n * chain) — this helper never extracts or verifies a token itself (§11.2.1),\n * so responds 401 immediately when it is absent.\n *\n * `resource` is resolved per §11.2.3's precedence: a literal string, a\n * {@link fromParam} route-parameter reference, or a `(req) => string`\n * resolver. `subjectId` on the wire is always the *authenticated request's*\n * user id (§11.2.2), never the SDK client's own service-account identity.\n * Error mapping (§11.2.5): 401 unauthenticated, 403 denied, 400 unresolvable\n * resource, 503 `authz_unavailable` on any transport/unexpected failure\n * (fail closed — never a silent allow).\n */\nexport function requireAccess(\n session: AuthzVerifiableSession,\n action: string,\n resource: ResourceSpec<Request>,\n opts?: RequireAccessOptions,\n): RequestHandler {\n const checker = assertAuthzClient(session);\n // §28.5 rule 5's challenge is built here, from this route's own `scope`\n // argument, so a scope outside RFC 6750's syntax fails at route setup rather\n // than on the first denial.\n const challenges = mcpGuardChallenges(session, 'requireAccess', opts?.scope);\n\n return async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n const axiamUser = (req as AxiamRequest).axiamUser;\n if (!axiamUser) {\n if (challenges) {\n res.setHeader(\n 'WWW-Authenticate',\n challengeFor401(challenges, req.headers.cookie, req.headers.authorization),\n );\n }\n res.status(401).json(missingAuthBody());\n return;\n }\n\n let resourceId: string;\n try {\n resourceId = resolveResourceId(req, resource, (r) => r.params as Record<string, string | undefined>);\n } catch (err) {\n const message = err instanceof ResourceResolutionError ? err.message : 'invalid resource';\n res.status(400).json(invalidRequestBody(message));\n return;\n }\n\n const outcome = await evaluateAccess(\n checker,\n action,\n resourceId,\n axiamUser.userId,\n opts?.scope,\n opts?.umaChallenge,\n );\n if (outcome.kind === 'denied') {\n opts?.logger?.debug('axiam_sdk.authz', 'access denied', { action, resourceId });\n // §20.3's UMA challenge wins where both apply: it is per-route opt-in and\n // carries a live ticket for the exact authority just refused, where\n // §28.5 rule 5's is the generic \"ask for this scope\" hint. Only one\n // `WWW-Authenticate` value is emitted either way.\n const challenge = outcome.challenge ?? challengeFor403(challenges, outcome.reasonCode);\n if (challenge) {\n // §20.3 / §28.5 rule 5: tell the caller where to obtain authority.\n // Additive — the body is the unchanged §11.2.5 shape, so a client that\n // speaks neither sees exactly the 403 it saw before. In particular\n // `insufficient_scope` appears only in the header: the body is still\n // `authorization_denied`.\n res.setHeader('WWW-Authenticate', challenge);\n }\n res.status(403).json(authzDeniedBodyShared(outcome.message));\n return;\n }\n if (outcome.kind === 'unavailable') {\n opts?.logger?.debug('axiam_sdk.authz', 'authz check unavailable', { action, resourceId });\n res.status(503).json(authzUnavailableBody(outcome.message));\n return;\n }\n next();\n };\n}\n\n/**\n * `requireRole(session, ...roles)` (CONTRACT.md §11.1, MAY; §11.2 rule 11) —\n * a local (no server round-trip) check that the verified token's **`roles`\n * claim** (`req.axiamUser.roles`) contains at least one of `roles`, by exact,\n * case-sensitive equality. Cheaper but coarser than `requireAccess`; NOT a\n * substitute for a resource-level check.\n *\n * **Request the `roles` scope (contract 1.68).** The server puts a `roles`\n * claim — the subject's global role names in the tenant — in an access token\n * only when the client requested, and is registered for, the `roles` scope.\n * Without it the token has no `roles` claim and every `requireRole` answers\n * 403: the check fails closed and never reads `scope`. Through 1.3.x this\n * helper matched OAuth2 scopes (N15); a route that relied on that should use\n * {@link requireScope}. The claim is a snapshot taken when the token was\n * minted (stale for at most one access-token lifetime); `requireAccess`\n * evaluates live and stays the authoritative check.\n *\n * `session` is taken first for signature parity with\n * `requireAuth`/`requireAccess` (every §11 helper does). The role check itself\n * reads nothing from it; §28.5 is the only thing that does, so that this\n * guard's own 401 carries the same challenge every other 401 does.\n */\nexport function requireRole(session: VerifiableSession, ...roles: string[]): RequestHandler {\n // The one thing this guard does read off the session: §28.5 rule 4 puts the\n // challenge on every 401 the guard emits, and this guard emits one.\n const challenges = mcpGuardChallenges(session, 'requireRole');\n\n return (req: Request, res: Response, next: NextFunction): void => {\n const axiamUser = (req as AxiamRequest).axiamUser;\n if (!axiamUser) {\n if (challenges) {\n res.setHeader(\n 'WWW-Authenticate',\n challengeFor401(challenges, req.headers.cookie, req.headers.authorization),\n );\n }\n res.status(401).json(missingAuthBody());\n return;\n }\n if (!hasAnyRole(axiamUser.roles, roles)) {\n // §28.5 rule 5: a role failure is not a scope failure — no header.\n res.status(403).json(authzDeniedBodyShared('missing required role'));\n return;\n }\n next();\n };\n}\n\n/**\n * `requireScope(session, ...scopes)` (CONTRACT.md §11.1, contract 1.68; §11.2\n * rule 11 (d)) — a local (no server round-trip) check that the verified\n * token's `scope` claim (`req.axiamUser.scopes`) contains at least one of\n * `scopes`, each compared as a whole entry by exact, case-sensitive equality.\n * A route that needs several stacks the helper. 401 when no identity is\n * present (mount `axiamMiddleware`/`requireAuth` first), 403 on failure and\n * when the token has no `scope` claim. A scope says what the *client* was\n * granted, not what the user holds — use {@link requireRole} or\n * `requireAccess` for that.\n */\nexport function requireScope(session: VerifiableSession, ...scopes: string[]): RequestHandler {\n const challenges = mcpGuardChallenges(session, 'requireScope');\n\n return (req: Request, res: Response, next: NextFunction): void => {\n const axiamUser = (req as AxiamRequest).axiamUser;\n if (!axiamUser) {\n if (challenges) {\n res.setHeader(\n 'WWW-Authenticate',\n challengeFor401(challenges, req.headers.cookie, req.headers.authorization),\n );\n }\n res.status(401).json(missingAuthBody());\n return;\n }\n if (!hasAnyScope(axiamUser.scopes, scopes)) {\n res.status(403).json(authzDeniedBodyShared('missing required scope'));\n return;\n }\n next();\n };\n}\n\n// ---------------------------------------------------------------------------\n// \"Login with AXIAM\" route handlers (CONTRACT.md §12)\n// ---------------------------------------------------------------------------\n\n/** Apply an {@link OidcLoginOutcome} to an Express response. */\nfunction sendOidcOutcome(res: Response, outcome: OidcLoginOutcome): void {\n // §12.8 rule 1: the binding cookie is set by the login and cleared by every\n // callback response; the core decides the value, the adapter only sends it.\n if (outcome.setCookie !== undefined) {\n res.append('Set-Cookie', outcome.setCookie);\n }\n if (outcome.kind === 'redirect') {\n // Encoded here by the rules of docs/login-glue-binding.md Decision 7; the\n // framework helper's own encoding then finds nothing left to change.\n res.redirect(encodeRedirectLocation(outcome.url));\n return;\n }\n if (outcome.kind === 'json') {\n res.status(200).json(outcome.body);\n return;\n }\n res.status(outcome.status).json(outcome.body);\n}\n\n/**\n * `oidcLoginHandlers(options)` (CONTRACT.md §12) — the two Express route\n * handlers an application needs for \"Login with AXIAM\": a `login` handler that\n * redirects the browser to AXIAM's authorization endpoint, and a `callback`\n * handler that consumes the returned `state`, exchanges the code, and\n * validates the ID token.\n *\n * @remarks\n * Both handlers are thin adapters over {@link beginOidcLogin} /\n * {@link completeOidcLogin}, which the Fastify variant\n * (`oidcLoginPlugin`) also uses — so the two frameworks cannot drift on flow\n * semantics or error mapping.\n *\n * **Browser binding (CONTRACT.md §12.8, contract 1.68).** The `login` handler\n * sets the `__Host-axiam_oidc_bind` cookie (`axiam_oidc_bind` on a plain-HTTP\n * loopback `redirectUri`) and the `callback` handler completes the sign-in only\n * for a request presenting that same cookie, so a callback link replayed into\n * another browser — login CSRF — answers the uniform 401 without exchanging the\n * code or calling `onSuccess`. Every callback response clears the cookie. Two\n * sign-ins started at once in one browser: the later one wins and the earlier\n * callback is refused. The routes must be served over HTTPS (or plain HTTP on\n * loopback in development) for the browser to keep the cookie.\n *\n * The `login` handler reads an optional `?returnTo=` query parameter and\n * stores it with the login state **only when it is a same-origin relative\n * path** (one leading `/`, not `//` or `/\\`, no backslash or control\n * character); the callback checks it again before redirecting. Anything else —\n * an absolute URL, a scheme-relative `//host` — is dropped, and the callback\n * falls back to `successRedirect` or the JSON summary. Widen the rule, for\n * example to an allowlist of your other origins, with `allowReturnTo`.\n *\n * Establishing your application's own session is the `onSuccess` hook's job:\n * the SDK validates the login and hands you the token set, the consumed entry\n * and the Express `Request` that completed it, but what a session means (a\n * signed cookie, a database row, a JWT of your own) is your decision.\n *\n * @example\n * ```ts\n * const store = new MemoryOidcStateStore();\n * const oidc = createOidcClient(session, { clientId, clientSecret });\n * const { login, callback } = oidcLoginHandlers({\n * client: oidc,\n * store,\n * redirectUri: 'https://app.example.com/auth/callback',\n * scope: 'openid profile email',\n * onSuccess: (tokens, _entry, req) => { myAppSession.establish(req, tokens.idClaims!.sub); },\n * });\n *\n * app.get('/auth/login', login);\n * app.get('/auth/callback', callback);\n * ```\n */\nexport function oidcLoginHandlers(options: OidcLoginOptions<Request>): {\n /** `GET` handler that redirects the browser to the AXIAM authorization endpoint. */\n login: RequestHandler;\n /** `GET` handler for the redirect URI: consumes `state`, exchanges `code`, validates the ID token. */\n callback: RequestHandler;\n} {\n const login: RequestHandler = async (req: Request, res: Response): Promise<void> => {\n const returnTo = typeof req.query.returnTo === 'string' ? req.query.returnTo : undefined;\n sendOidcOutcome(res, await beginOidcLogin(options, returnTo));\n };\n\n // §12.8 rule 1 (b): the callback reads the one name the login set.\n const bindingCookieName = oidcBindingCookieName(options.redirectUri);\n\n const callback: RequestHandler = async (req: Request, res: Response): Promise<void> => {\n let outcome: OidcLoginOutcome;\n try {\n const query = req.query as Record<string, unknown>;\n const bindingCookie = parseCookieHeader(req.headers.cookie)[bindingCookieName];\n outcome = await completeOidcLogin(\n options,\n {\n ...(typeof query.state === 'string' ? { state: query.state } : {}),\n ...(typeof query.code === 'string' ? { code: query.code } : {}),\n ...(typeof query.error === 'string' ? { error: query.error } : {}),\n ...(typeof query.error_description === 'string'\n ? { error_description: query.error_description }\n : {}),\n },\n { request: req, ...(bindingCookie !== undefined ? { bindingCookie } : {}) },\n );\n } catch (err) {\n // §12.8 rule 1 (d), \"and any other error\": the store or onSuccess threw.\n // The error response Express builds from `next(err)` keeps this header,\n // and the application's error handler still receives the error itself.\n if (!res.headersSent) {\n res.append('Set-Cookie', oidcBindingClearCookie(options.redirectUri));\n }\n throw err;\n }\n sendOidcOutcome(res, outcome);\n };\n\n return { login, callback };\n}\n","// Fastify middleware (D-27, CONTRACT.md §10) — registered as a\n// `preHandler` hook via a FastifyPluginAsync, mirroring express.ts's\n// verification flow through the same shared verifyCore.\n\nimport type { FastifyPluginAsync, FastifyReply, FastifyRequest } from 'fastify';\nimport { AuthError, AuthzError } from '../core/index.js';\nimport {\n assertAuthzClient,\n authzDeniedBody as authzDeniedBodyShared,\n authzUnavailableBody,\n evaluateAccess,\n hasAnyRole,\n hasAnyScope,\n invalidRequestBody,\n missingAuthBody,\n resolveResourceId,\n ResourceResolutionError,\n type AuthzVerifiableSession,\n type RequireAccessOptions,\n type ResourceSpec,\n} from './authzCore.js';\nimport {\n CSRF_HEADER_NAME,\n extractCredential,\n isCsrfValid,\n isSafeMethod,\n parseCookieHeader,\n} from './cookieHeader.js';\nimport {\n challengeFor401,\n challengeFor403,\n isMetadataDocumentRequest,\n mcpGuardChallenges,\n} from './mcpCore.js';\nimport {\n beginOidcLogin,\n completeOidcLogin,\n encodeRedirectLocation,\n oidcBindingClearCookie,\n oidcBindingCookieName,\n type OidcLoginOptions,\n type OidcLoginOutcome,\n} from './oidcLoginCore.js';\nimport { certificateProofFromSocket } from './peerCertificate.js';\nimport { authenticateRequest, type AxiamIdentity, type VerifiableSession } from './verifyCore.js';\n\n/** A Fastify `FastifyRequest` augmented with the AXIAM identity that `axiamPlugin` injects after §10 verification. */\nexport interface AxiamFastifyRequest extends FastifyRequest {\n /** The authenticated identity, present once `axiamPlugin` (or `requireAuthHook`) has run; absent on an unauthenticated request. */\n axiamUser?: AxiamIdentity;\n}\n\n/** A Fastify `preHandler`-compatible hook function (CONTRACT.md §11) — usable both via `fastify.addHook('preHandler', ...)` and per-route as `{ preHandler: hook }`. */\nexport type PreHandlerHook = (request: FastifyRequest, reply: FastifyReply) => Promise<void>;\n\ninterface ErrorBody {\n error: string;\n message: string;\n}\n\nfunction missingCredentialsBody(): ErrorBody {\n return { error: 'authentication_failed', message: 'missing authentication credentials' };\n}\n\nfunction invalidTokenBody(message: string): ErrorBody {\n return { error: 'authentication_failed', message };\n}\n\nfunction authzDeniedBody(message: string): ErrorBody {\n return { error: 'authorization_denied', message };\n}\n\nfunction csrfDeniedBody(): ErrorBody {\n return { error: 'authorization_denied', message: 'csrf validation failed' };\n}\n\n/**\n * The `preHandler` body shared by `axiamPlugin` (registered globally as a\n * hook) and `requireAuthHook` (mounted per-route) — extracts the session\n * (cookie-first, then `Authorization: Bearer` fallback), verifies it\n * locally against the cached JWKS (D-11), and injects `request.axiamUser`\n * on success. Replies 401 (AuthError) or 403 (AuthzError/CSRF) with a\n * standardized JSON error body on failure.\n *\n * **CSRF (cookie double-submit, CONTRACT.md §3):** when the credential was\n * sourced from the `axiam_access` COOKIE (not the `Authorization` header)\n * and the request method is state-changing (anything other than\n * GET/HEAD/OPTIONS), this hook additionally requires the `X-CSRF-Token`\n * request header to be present and equal (constant time) to the\n * `axiam_csrf` cookie value, replying 403 on mismatch/absence. Bearer-header\n * requests are CSRF-immune by construction — a cross-site attacker cannot\n * set arbitrary request headers — but a cookie automatically attached by\n * the browser is not, and in any same-site deployment where `axiam_access`\n * reaches this app, the non-`httpOnly` `axiam_csrf` cookie does too. This\n * mirrors, locally, the same double-submit check the AXIAM server performs\n * on its own endpoints (§3).\n */\nfunction buildAuthHook(session: VerifiableSession, operation: string): PreHandlerHook {\n // §28.5: validated and precomputed at construction, `undefined` when\n // `resourceMetadataUrl` is unset — which is what keeps a guard without §28\n // byte-for-byte identical to one from before §28 existed.\n const challenges = mcpGuardChallenges(session, operation);\n\n return async (request: FastifyRequest, reply: FastifyReply) => {\n // §28.3 rule 2: the metadata document MUST answer without a credential.\n // A Fastify `preHandler` hook applies to every route in its context\n // regardless of registration order, so there is no ordering trick that\n // would exempt the path — the exemption has to be here, and explicit.\n if (isMetadataDocumentRequest(challenges, request.method, request.url)) return;\n\n const credential = extractCredential(request.headers.cookie, request.headers.authorization);\n if (!credential) {\n // §28.4: no credential is not a bad credential, so the challenge names\n // no error code (RFC 6750 §3).\n if (challenges) void reply.header('WWW-Authenticate', challenges.noCredential);\n await reply.code(401).send(missingCredentialsBody());\n return;\n }\n\n if (credential.source === 'cookie' && !isSafeMethod(request.method)) {\n const csrfHeader = request.headers[CSRF_HEADER_NAME];\n const csrfValue = Array.isArray(csrfHeader) ? csrfHeader[0] : csrfHeader;\n if (!isCsrfValid(request.headers.cookie, csrfValue)) {\n await reply.code(403).send(csrfDeniedBody());\n return;\n }\n }\n\n try {\n // §10.1 rule 9: same evidence as the Express guard — the peer\n // certificate the TLS layer verified for THIS connection, from\n // Fastify's raw Node request. `{}` (no evidence) when it is not\n // TLS-shaped or carries no certificate.\n const proofs = await certificateProofFromSocket(request.raw.socket);\n const identity = await authenticateRequest(session, credential.token, proofs);\n (request as AxiamFastifyRequest).axiamUser = identity;\n } catch (err) {\n if (err instanceof AuthzError) {\n // §28.5 rule 5: this 403 is not a `no_grant` scope denial, so it gains\n // no header.\n await reply.code(403).send(authzDeniedBody(err.message));\n return;\n }\n // §28.4: a credential was presented and rejected. Expired, not yet\n // valid, wrong tenant, wrong audience, bad signature, an unsatisfiable\n // `cnf`, a revoked `sid` — all of them are `invalid_token`,\n // indistinguishably. Every distinction a 401 draws for an\n // unauthenticated stranger is an oracle.\n if (challenges) void reply.header('WWW-Authenticate', challenges.invalidToken);\n if (err instanceof AuthError) {\n await reply.code(401).send(invalidTokenBody(err.message));\n return;\n }\n await reply.code(401).send(invalidTokenBody('invalid or expired token'));\n }\n };\n}\n\n/**\n * `axiamPlugin(session)` — a `FastifyPluginAsync` registering the shared\n * auth `preHandler` hook globally (D-27, CONTRACT.md\n * §10). Marked with fastify's own `skip-override` plugin symbol (the same\n * mechanism the `fastify-plugin` package wraps) so the `preHandler` hook\n * applies to routes registered as siblings of this plugin rather than\n * being scoped only to its own encapsulation context — avoids adding\n * `fastify-plugin` as a dependency for a one-line escape hatch.\n */\nexport const axiamPlugin: (session: VerifiableSession) => FastifyPluginAsync = (session) => {\n // Built here rather than inside the plugin body so §28.5's configuration\n // refusal happens when `axiamPlugin(session)` is called — construction time,\n // before `register` and before the server is listening.\n const hook = buildAuthHook(session, 'axiamPlugin');\n const plugin: FastifyPluginAsync = async (fastify) => {\n fastify.addHook('preHandler', hook);\n };\n (plugin as unknown as Record<symbol, unknown>)[Symbol.for('skip-override')] = true;\n (plugin as unknown as Record<symbol, unknown>)[Symbol.for('fastify.display-name')] =\n 'axiam-plugin';\n return plugin;\n};\n\n/**\n * `requireAuthHook(session)` (CONTRACT.md §11.1) — the canonical §11 name\n * for the same §10 guard `axiamPlugin` already provides, as a plain\n * `preHandler` function usable per-route:\n * `fastify.get('/x', { preHandler: requireAuthHook(session) }, handler)`,\n * rather than registered globally via `fastify.register(axiamPlugin(session))`.\n * Pure sugar: it performs no verification of its own beyond what the shared\n * auth `preHandler` hook (also used by `axiamPlugin`) already does.\n */\nexport function requireAuthHook(session: VerifiableSession): PreHandlerHook {\n return buildAuthHook(session, 'requireAuthHook');\n}\n\n/**\n * `requireAccessHook(session, action, resource, opts?)` (CONTRACT.md §11) —\n * the Fastify `preHandler` counterpart to `requireAccess` (see that\n * function's doc for the full §11 semantics). Throws synchronously (at\n * route-setup time) if `session.authzClient` is not configured. Requires\n * `request.axiamUser` to already be set (by `axiamPlugin`/`requireAuthHook`\n * mounted earlier in the chain) — replies 401 immediately when absent.\n */\nexport function requireAccessHook(\n session: AuthzVerifiableSession,\n action: string,\n resource: ResourceSpec<FastifyRequest>,\n opts?: RequireAccessOptions,\n): PreHandlerHook {\n const checker = assertAuthzClient(session);\n // §28.5 rule 5's challenge is built here, from this route's own `scope`\n // argument, so a scope outside RFC 6750's syntax fails at route setup rather\n // than on the first denial.\n const challenges = mcpGuardChallenges(session, 'requireAccessHook', opts?.scope);\n\n return async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n const axiamUser = (request as AxiamFastifyRequest).axiamUser;\n if (!axiamUser) {\n if (challenges) {\n void reply.header(\n 'WWW-Authenticate',\n challengeFor401(challenges, request.headers.cookie, request.headers.authorization),\n );\n }\n await reply.code(401).send(missingAuthBody());\n return;\n }\n\n let resourceId: string;\n try {\n resourceId = resolveResourceId(\n request,\n resource,\n (r) => r.params as Record<string, string | undefined>,\n );\n } catch (err) {\n const message = err instanceof ResourceResolutionError ? err.message : 'invalid resource';\n await reply.code(400).send(invalidRequestBody(message));\n return;\n }\n\n const outcome = await evaluateAccess(\n checker,\n action,\n resourceId,\n axiamUser.userId,\n opts?.scope,\n opts?.umaChallenge,\n );\n if (outcome.kind === 'denied') {\n opts?.logger?.debug('axiam_sdk.authz', 'access denied', { action, resourceId });\n // §20.3's UMA challenge wins where both apply — see `requireAccess` for\n // why. Only one `WWW-Authenticate` value is emitted either way.\n const challenge = outcome.challenge ?? challengeFor403(challenges, outcome.reasonCode);\n if (challenge) {\n // §20.3 / §28.5 rule 5, additive: the body keeps the unchanged §11.2.5\n // shape, so `insufficient_scope` appears only in the header and the\n // body is still `authorization_denied`.\n void reply.header('WWW-Authenticate', challenge);\n }\n await reply.code(403).send(authzDeniedBodyShared(outcome.message));\n return;\n }\n if (outcome.kind === 'unavailable') {\n opts?.logger?.debug('axiam_sdk.authz', 'authz check unavailable', { action, resourceId });\n await reply.code(503).send(authzUnavailableBody(outcome.message));\n return;\n }\n };\n}\n\n/**\n * `requireRoleHook(session, ...roles)` (CONTRACT.md §11.1, MAY) — the\n * Fastify `preHandler` counterpart to `requireRole`; see that function's\n * doc for the full semantics (local-only check, no server round-trip). It\n * reads only the token's `roles` claim and fails closed (403) when the token\n * has none — the application must request the `roles` scope (contract 1.68,\n * §11.2 rule 11); it never reads `scope`, for which see `requireScopeHook`.\n * `session` is taken first for signature parity with\n * `requireAuthHook`/`requireAccessHook`; the role check reads nothing from it,\n * and §28.5 is the only thing that does.\n */\nexport function requireRoleHook(session: VerifiableSession, ...roles: string[]): PreHandlerHook {\n // The one thing this guard does read off the session: §28.5 rule 4 puts the\n // challenge on every 401 the guard emits, and this guard emits one.\n const challenges = mcpGuardChallenges(session, 'requireRoleHook');\n\n return async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n const axiamUser = (request as AxiamFastifyRequest).axiamUser;\n if (!axiamUser) {\n if (challenges) {\n void reply.header(\n 'WWW-Authenticate',\n challengeFor401(challenges, request.headers.cookie, request.headers.authorization),\n );\n }\n await reply.code(401).send(missingAuthBody());\n return;\n }\n if (!hasAnyRole(axiamUser.roles, roles)) {\n // §28.5 rule 5: a role failure is not a scope failure — no header.\n await reply.code(403).send(authzDeniedBodyShared('missing required role'));\n return;\n }\n };\n}\n\n/**\n * `requireScopeHook(session, ...scopes)` (CONTRACT.md §11.1, contract 1.68) —\n * the Fastify `preHandler` counterpart to `requireScope`: a local check that\n * the verified token's `scope` claim contains at least one of `scopes` (whole\n * entries, exact and case-sensitive). 401 without an identity, 403 on failure\n * and when the token has no `scope` claim.\n */\nexport function requireScopeHook(session: VerifiableSession, ...scopes: string[]): PreHandlerHook {\n const challenges = mcpGuardChallenges(session, 'requireScopeHook');\n\n return async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n const axiamUser = (request as AxiamFastifyRequest).axiamUser;\n if (!axiamUser) {\n if (challenges) {\n void reply.header(\n 'WWW-Authenticate',\n challengeFor401(challenges, request.headers.cookie, request.headers.authorization),\n );\n }\n await reply.code(401).send(missingAuthBody());\n return;\n }\n if (!hasAnyScope(axiamUser.scopes, scopes)) {\n await reply.code(403).send(authzDeniedBodyShared('missing required scope'));\n return;\n }\n };\n}\n\n// ---------------------------------------------------------------------------\n// \"Login with AXIAM\" routes (CONTRACT.md §12)\n// ---------------------------------------------------------------------------\n\n/** Apply an {@link OidcLoginOutcome} to a Fastify reply. */\nasync function sendOidcOutcome(reply: FastifyReply, outcome: OidcLoginOutcome): Promise<void> {\n // §12.8 rule 1: the binding cookie is set by the login and cleared by every\n // callback response; the core decides the value, the adapter only sends it.\n // Fastify accumulates repeated `set-cookie` headers rather than replacing them.\n if (outcome.setCookie !== undefined) {\n void reply.header('set-cookie', outcome.setCookie);\n }\n if (outcome.kind === 'redirect') {\n // 302 + Location, written directly rather than via @fastify/redirect — the\n // SDK adds no new dependency for a two-line response.\n // Fastify does not encode a header value (Express's res.redirect does), so the\n // adapter does, whatever produced the URL (docs/login-glue-binding.md).\n await reply.code(302).header('location', encodeRedirectLocation(outcome.url)).send();\n return;\n }\n if (outcome.kind === 'json') {\n await reply.code(200).send(outcome.body);\n return;\n }\n await reply.code(outcome.status).send(outcome.body);\n}\n\n/** Route paths the {@link oidcLoginPlugin} registers, relative to where it is registered. */\nexport interface OidcLoginRoutePaths {\n /** Path of the login-redirect route. Defaults to `/auth/login`. */\n loginPath?: string;\n /** Path of the callback route — must match the public URL in `redirectUri`. Defaults to `/auth/callback`. */\n callbackPath?: string;\n}\n\n/**\n * `oidcLoginPlugin(options)` (CONTRACT.md §12) — a `FastifyPluginAsync`\n * registering the two \"Login with AXIAM\" routes: a login-redirect route and\n * the callback route that consumes `state`, exchanges the code, and validates\n * the ID token.\n *\n * @remarks\n * The Fastify counterpart of Express's `oidcLoginHandlers`, built on the same\n * {@link beginOidcLogin} / {@link completeOidcLogin} core, so the two\n * frameworks cannot drift on flow semantics or error mapping. See\n * `oidcLoginHandlers` for the browser binding (`__Host-axiam_oidc_bind`,\n * CONTRACT.md §12.8), the same-origin `returnTo` rule and `allowReturnTo`, and\n * the `onSuccess` session-establishment contract, which apply identically\n * here — `onSuccess` receives the `FastifyRequest` that completed the sign-in.\n *\n * Unlike `axiamPlugin` this plugin is deliberately **encapsulated** (no\n * `skip-override` marker): it registers routes rather than a hook, so there is\n * nothing that needs to escape its own context.\n *\n * @example\n * ```ts\n * await fastify.register(oidcLoginPlugin({\n * client: oidc,\n * store: new MemoryOidcStateStore(),\n * redirectUri: 'https://app.example.com/auth/callback',\n * onSuccess: (tokens, _entry, request) => { myAppSession.establish(request, tokens.idClaims!.sub); },\n * }));\n * ```\n */\nexport const oidcLoginPlugin: (\n options: OidcLoginOptions<FastifyRequest> & OidcLoginRoutePaths,\n) => FastifyPluginAsync = (options) => {\n const loginPath = options.loginPath ?? '/auth/login';\n const callbackPath = options.callbackPath ?? '/auth/callback';\n // §12.8 rule 1 (b): the callback reads the one name the login set.\n const bindingCookieName = oidcBindingCookieName(options.redirectUri);\n\n const plugin: FastifyPluginAsync = async (fastify) => {\n fastify.get(loginPath, async (request: FastifyRequest, reply: FastifyReply) => {\n const query = request.query as Record<string, unknown>;\n const returnTo = typeof query.returnTo === 'string' ? query.returnTo : undefined;\n await sendOidcOutcome(reply, await beginOidcLogin(options, returnTo));\n });\n\n fastify.get(callbackPath, async (request: FastifyRequest, reply: FastifyReply) => {\n let outcome: OidcLoginOutcome;\n try {\n const query = request.query as Record<string, unknown>;\n const bindingCookie = parseCookieHeader(request.headers.cookie)[bindingCookieName];\n outcome = await completeOidcLogin(\n options,\n {\n ...(typeof query.state === 'string' ? { state: query.state } : {}),\n ...(typeof query.code === 'string' ? { code: query.code } : {}),\n ...(typeof query.error === 'string' ? { error: query.error } : {}),\n ...(typeof query.error_description === 'string'\n ? { error_description: query.error_description }\n : {}),\n },\n { request, ...(bindingCookie !== undefined ? { bindingCookie } : {}) },\n );\n } catch (err) {\n // §12.8 rule 1 (d), \"and any other error\": the store or onSuccess threw.\n // Fastify's error handler keeps headers already set on the reply, and\n // the application's setErrorHandler still receives the error itself.\n if (!reply.sent) {\n void reply.header('set-cookie', oidcBindingClearCookie(options.redirectUri));\n }\n throw err;\n }\n await sendOidcOutcome(reply, outcome);\n });\n };\n\n (plugin as unknown as Record<symbol, unknown>)[Symbol.for('fastify.display-name')] =\n 'axiam-oidc-login';\n return plugin;\n};\n","// A session-free transport for calls that carry a credential of their own.\n//\n// CONTRACT.md §28.12.2 rule 3 (RFC 7592 client configuration) and §32.7\n// (`SsfReceiver.poll`) both send a bearer that is NOT this SDK's session — a\n// registration access token, a receiver's client-credentials token — and both\n// say the SDK's own session must not ride along: no session cookie, no access\n// token, no CSRF header, and no §9 refresh on a `401`. The session's axios\n// instance cannot give that guarantee, because its request interceptors add\n// those things and its response interceptor refreshes, so these calls go out\n// on a fresh axios instance instead:\n//\n// * no interceptors at all (no `X-Tenant-ID`, no `X-CSRF-Token`, no\n// `Authorization` the session adopted, no refresh-on-401);\n// * no cookie jar — under Node the session's TLS material is reused through\n// `noCredentialsConfig()`'s plain (jar-free) agents, so §6's custom CA and\n// §6.1's client certificate still apply; in a browser `withCredentials` is\n// off;\n// * no redirect following (`maxRedirects: 0`) — a redirect would hand the\n// bearer to whichever host the `Location` names. **Node only:** a browser's\n// XHR/fetch follows same-origin redirects itself and offers no way to stop\n// it, which is one reason these helpers are documented as server-side;\n// * every status resolved rather than thrown (`validateStatus`), so the\n// caller maps it with the tolerant `/oauth2` decoder and decides retries\n// itself.\n\nimport axios, { type AxiosRequestConfig, type AxiosResponse } from 'axios';\nimport { NetworkError } from '../core/index.js';\nimport type { SharedSession } from './session.js';\n\n/**\n * Issue one request on a fresh, interceptor-free, jar-free, redirect-free\n * axios instance carrying this session's TLS configuration only.\n *\n * A transport failure (no response at all) becomes a {@link NetworkError}\n * whose message names the operation and the low-level error code only. The\n * axios error itself is **not** attached as `cause`: its `config` holds the\n * request headers — the bearer this call exists to protect — and the request\n * body.\n *\n * @internal\n */\nexport async function bareRequest<T>(\n session: SharedSession,\n operation: string,\n config: AxiosRequestConfig,\n): Promise<AxiosResponse<T>> {\n const defaults = session.axios.defaults;\n const instance = axios.create({\n timeout: defaults.timeout,\n // The base session's own TLS agent (custom CA / client certificate, no\n // jar). Under the Node persona this is the jar-wrapped cookie agent, which\n // `noCredentialsConfig()` below replaces with a plain one.\n ...(defaults.httpsAgent !== undefined ? { httpsAgent: defaults.httpsAgent } : {}),\n // The bare transport carries the RFC 7592 registration calls on `/oauth2/register/*`,\n // so it gets an `/oauth2/*` request's config: in the browser persona the fetch adapter\n // that omits credentials (C164-06; identical to `noCredentialsConfig()` under Node).\n ...session.oauth2RequestConfig(),\n withCredentials: false,\n maxRedirects: 0,\n validateStatus: () => true,\n });\n let response: AxiosResponse<T>;\n try {\n response = await instance.request<T>(config);\n } catch (err) {\n const code =\n err && typeof err === 'object' && 'code' in err && typeof (err as { code?: unknown }).code === 'string'\n ? ` (${(err as { code: string }).code})`\n : '';\n throw new NetworkError(`${operation}: the request failed before any response arrived${code}`);\n }\n // CONTRACT.md §12.1 rule 3: no redirect is followed and a 3xx is a NetworkError. A browser\n // `fetch` with `redirect: 'error'` rejects above; this catches an adapter that hands the\n // redirect (or an opaque-redirect, status 0) back as a response. Neither the `Location`\n // nor the request is put in the message.\n if (response.status === 0 || (response.status >= 300 && response.status < 400)) {\n throw new NetworkError(`${operation}: the server answered with a redirect, which is not followed`);\n }\n return response;\n}\n\n/**\n * Parse a `Retry-After` header (delta-seconds form only) into milliseconds, for\n * the §16 runner's floor. An HTTP-date or anything unparseable is ignored.\n *\n * @internal\n */\nexport function retryAfterMs(response: AxiosResponse): number | undefined {\n const raw = response.headers?.['retry-after'];\n const value = typeof raw === 'string' ? raw.trim() : undefined;\n if (value === undefined || !/^\\d+$/.test(value)) return undefined;\n return Number(value) * 1000;\n}\n\n/**\n * Whether §16 may retry a response with this status: `408`, `429` and every\n * `5xx`. Every other `4xx` is a decisive answer — including a bodiless `400`,\n * which §2 maps to `NetworkError` and which the shared runner would otherwise\n * retry because it retries every `NetworkError`.\n *\n * @internal\n */\nexport function statusIsRetryable(status: number): boolean {\n return status === 408 || status === 429 || status >= 500;\n}\n\n/**\n * A `NetworkError` the §16 runner may retry, carrying the server's\n * `Retry-After` as the floor it reads.\n *\n * @internal\n */\nexport function retryableNetworkError(message: string, response?: AxiosResponse): NetworkError {\n const error = new NetworkError(message);\n const floor = response ? retryAfterMs(response) : undefined;\n if (floor !== undefined) {\n Object.defineProperty(error, 'retryAfterMs', { value: floor, enumerable: false });\n }\n return error;\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 // CONTRACT.md §6.1 rule 11 / CONTRACT 1.52 N4.5 (C-12): \"A `401` on the\n // device POST itself ... is `AuthError`, with no refresh call ... even\n // when the client holds an earlier session.\" Without this entry, a client\n // that already completed a password login (`session.authenticated ===\n // true`) and then called `authenticateDevice()` into a refusal had that\n // 401 misread as an ordinary authenticated-session 401 — this IS the\n // login, so it must never itself trigger a refresh-then-retry cycle,\n // regardless of what session state came before it.\n '/api/v1/auth/device',\n '/oauth2/token',\n // CONTRACT.md §14.2 rule 5 (contract 1.62): a client that fails to\n // authenticate at the device endpoints is `401 invalid_client`, which is not\n // an expired session and which refreshing cannot fix. `/oauth2/token` (the\n // poll) was already here; the authorization endpoint now authenticates the\n // client too, so its 401 must not enter the §9 guard either.\n '/oauth2/device_authorization',\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 // CONTRACT.md §6.1 rule 11, §12.1 rule 3, §14.6 (contract 1.63): no\n // `X-CSRF-Token` on an `/oauth2/*` request — it authenticates the client\n // through the form body (or the TLS certificate), never the session.\n if (isOAuth2Endpoint(config.url, session.baseUrl)) {\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 // §6.1 rule 6 (contract 1.51): a device token has no refresh token\n // behind it. A later 401 on it is AuthError, never a refresh attempt —\n // there is nothing the §9 guard could spend, and the recovery path is\n // calling authenticateDevice() again (one TLS handshake), not this.\n const isDeviceSession = session.deviceAccessToken !== undefined;\n\n if (status === 401 && !originalRequest._retry && !isSkipRefresh && session.authenticated && !isDeviceSession) {\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 || isDeviceSession)) {\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/**\n * True for a request to an `/oauth2/*` endpoint: the request path, relative to the base\n * URL's own path, begins with `/oauth2/` (absolute or relative `url`; query ignored). A prefix\n * match, not a substring one — `/api/v1/auth/federation/oauth2/callback` is an ordinary\n * session endpoint whose `Set-Cookie` the jar must keep.\n */\nexport function isOAuth2Endpoint(url: string | undefined, baseUrl: string): boolean {\n if (!url) {\n return false;\n }\n try {\n const base = new URL(baseUrl);\n let path = new URL(url, base).pathname;\n const prefix = base.pathname.replace(/\\/+$/, '');\n if (prefix !== '' && path.startsWith(`${prefix}/`)) {\n path = path.slice(prefix.length);\n }\n return path.startsWith('/oauth2/');\n } catch {\n return false;\n }\n}\n\n/**\n * Request interceptor: once `authenticateDevice()` has adopted a token\n * (`session.deviceAccessToken`), every same-origin request carries it as\n * `Authorization: Bearer` — except to `/oauth2/*`, which gets no `Authorization`\n * header at all (§6.1 rule 11, §14.6, C162-05) — and rides the jar-free agent pair\n * `noCredentialsConfig()` builds — TLS-configured (the client certificate\n * stays on the connection), but with no cookie jar attached (CONTRACT.md\n * §6.1 rules 6-10, contract 1.51).\n *\n * The server reads the `axiam_access` cookie BEFORE the `Authorization`\n * header, so leaving the jar attached would let a cookie from an earlier\n * session on this same client silently outrank this token and the request\n * would run as that earlier session's principal — the exact hazard the\n * reference Rust SDK's own re-vendor flagged (\"what the plan did not\n * anticipate\", note 3). A session that never calls `authenticateDevice()`\n * is byte-for-byte unaffected: `deviceAccessToken` stays `undefined` and\n * this branch never runs.\n *\n * Installed by `installInterceptors` (bound to whichever `session`\n * `AxiamClient`'s constructor was actually given — the Node persona's real\n * `NodeSession`, not the transient `SharedSession` `createSession()`\n * discards after lifting its `.axios`/`.tenantHeaderValue` into it) rather\n * than inside `session.ts`'s `createSession`, so it always observes the\n * `deviceAccessToken` `authenticateDevice()` actually sets.\n */\nexport function installDeviceTokenInterceptor(axiosInstance: AxiosInstance, session: SharedSession): void {\n axiosInstance.interceptors.request.use((config) => {\n const deviceToken = session.deviceAccessToken;\n const oauth2 = isOAuth2Endpoint(config.url, session.baseUrl);\n if (session.isForeignHost(config.url) || (deviceToken === undefined && !oauth2)) {\n return config;\n }\n // An `/oauth2/*` request also gets the browser persona's fetch adapter with\n // `credentials: 'omit'` (C163-12); the other credential-free calls do not.\n const noCred = oauth2 ? session.oauth2RequestConfig() : session.noCredentialsConfig();\n Object.assign(config, noCred);\n config.headers = config.headers ?? {};\n if (oauth2) {\n // CONTRACT.md §6.1 rule 11, §12.1 rule 3 and §14.6 (contract 1.62, C162-05;\n // contract 1.63 extends it to the session cookies and `X-CSRF-Token`):\n // an `/oauth2/*` endpoint authenticates the client through the form body\n // (or the TLS certificate), so neither the adopted device credential nor\n // an `axiam_*` session cookie rides on it — the cookie stays out through\n // the jar-free agent pair above, and the CSRF interceptor adds no\n // `X-CSRF-Token` there. A credential the caller passes explicitly to\n // one call (RFC 7591/7592 registration tokens) travels on the bare\n // transport, which never reaches this interceptor.\n // An `Authorization` the caller set on this one call is left as given.\n return config;\n }\n config.headers['Authorization'] = `Bearer ${deviceToken!.expose()}`;\n // Belt and braces alongside the agent swap above: an explicit empty\n // Cookie header is what the reference Rust SDK relies on to make sure a\n // stale session cookie cannot ride beside this token even if something\n // downstream of noCredentialsConfig() still had one to offer.\n config.headers['Cookie'] = '';\n return config;\n });\n}\n\n/** Install the CSRF, reactive single-flight refresh, and §6.1 device-token interceptors. */\nexport function installInterceptors(axiosInstance: AxiosInstance, session: SharedSession): void {\n installCsrfInterceptor(axiosInstance, session);\n installRefreshInterceptor(axiosInstance, session);\n installDeviceTokenInterceptor(axiosInstance, session);\n}\n","// Bounded read-only retry policy — CONTRACT.md §16.\n//\n// This file previously held a policy of its own invention: 1000 ms base, 8 s\n// cap, partial jitter (`base + 0–20%`), and `Retry-After` *replacing* the\n// computed backoff rather than flooring it. Two problems with that, both now\n// fixed:\n//\n// * `retryAfterMs ?? backoffDelayMs(attempt)` meant a `Retry-After: 0`\n// retried immediately, defeating the backoff entirely — exactly what\n// §16.1's \"floor, never a ceiling\" forbids.\n// * It was exported and unit-tested but **never called by any production\n// path**. `checkAccess` did not route through it, so this SDK performed no\n// read-only retries at all while appearing to. A tested helper nobody calls\n// is worse than an absent one: the green tests are what stop anyone from\n// looking.\n//\n// §16 is the normative table all eleven SDKs now share. `withRetry` is wired\n// into the authz surface in `authz.ts`; the §16.7 tests assert the policy\n// through the public `checkAccess` API, not just against this helper.\n\nimport { NetworkError } from '../core/index.js';\nimport type { TelemetryDispatcher } from '../core/telemetry.js';\n\n/** Attempt cap: 1 initial + 2 retries (§16.1). */\nexport const MAX_ATTEMPTS = 3;\n/** First backoff step, in milliseconds (§16.1). */\nexport const BASE_DELAY_MS = 200;\n/** Ceiling on any single computed backoff, in milliseconds (§16.1). */\nexport const MAX_DELAY_MS = 5_000;\n\n/** Options controlling {@link withRetry}. */\nexport interface RetryOptions {\n /**\n * Only operations that change **no server state** may be retried (§16.2).\n *\n * Note this means side-effect-free, **not** \"is an HTTP GET\": AXIAM's\n * authorization check is a `POST` with a request body and is the single most\n * important operation covered by this policy.\n */\n idempotent: boolean;\n /** Canonical operation name, for the §19 `retry` event. */\n operation?: string;\n /** Set `false` to disable retrying entirely (§16.1 disable switch). */\n enabled?: boolean;\n /** §19 sink, notified before each retry wait. */\n telemetry?: TelemetryDispatcher;\n /** Injected for tests — see §16.7 (\"a test that really waits 200 ms is a test nobody runs\"). */\n sleepFn?: (ms: number) => Promise<void>;\n /** Injected for tests: returns the jitter fraction in [0, 1]. */\n randomFn?: () => number;\n /**\n * Called with the wait before a retry is announced or served; throwing refuses the retry, so\n * nothing is emitted for it and nothing more is sent. A poll inside a deadline uses it to refuse\n * a wait that would reach the deadline (CONTRACT.md §14.2 rule 4, §34.2 P10).\n */\n admit?: (delayMs: number) => void;\n}\n\ninterface RetryAfterCarrier {\n retryAfterMs?: number;\n}\n\nfunction isRetryAfterCarrier(err: unknown): err is RetryAfterCarrier {\n return typeof err === 'object' && err !== null && 'retryAfterMs' in err;\n}\n\nfunction defaultSleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * The un-jittered backoff for a 1-based attempt: `min(cap, base * 2^(n-1))`.\n * Attempt 1 → 200 ms, attempt 2 → 400 ms.\n */\nexport function backoffMs(attempt: number): number {\n return Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** (attempt - 1));\n}\n\n/**\n * The actual wait: **full jitter** over `[0, backoff]`, then raised to any\n * server-supplied `Retry-After` (§16.1).\n *\n * Full jitter, not `backoff ± 10%`. Partial jitter keeps every client's retries\n * clustered around the same instant, which is the thundering herd retries are\n * supposed to prevent rather than cause.\n *\n * `Retry-After` is a **floor, never a ceiling**: the server is saying when it\n * will be ready, so retrying sooner is not permitted — and a `Retry-After: 0`\n * cannot shorten the wait below what jitter chose.\n */\nexport function delayMs(attempt: number, retryAfterMs: number | undefined, fraction: number): number {\n const jittered = backoffMs(attempt) * Math.min(Math.max(fraction, 0), 1);\n return retryAfterMs === undefined ? jittered : Math.max(jittered, retryAfterMs);\n}\n\n/**\n * Runs `fn` under the §16 policy.\n *\n * `fn` receives the 1-based attempt number so it can label its §19\n * `requestStart`/`requestEnd` pair. That is not cosmetic: §19.2 rule 5 requires\n * one pair **per attempt** with the attempt distinguishing them, so a caller\n * can count real wire calls. Emitting every pair as attempt 1 would make a\n * retried call indistinguishable from a single slow one — the exact blindness\n * §16.5 exists to remove.\n *\n * `fn` MUST be side-effect-free. This helper — like every retry helper — cannot\n * tell the difference, so routing a mutation through it would silently\n * duplicate a side effect, or replay a single-use credential (an authorization\n * code, a device code at redemption, a rotating refresh token) into a hard\n * `invalid_grant`.\n *\n * Only `NetworkError` is retried. The §2 taxonomy folds `408`/`429`/`5xx`/\n * transport into that one type, so this implements the whole §16.3 table:\n * `AuthError` and `AuthzError` are decisive answers, not transport failures.\n */\nexport async function withRetry<T>(\n fn: (attempt: number) => Promise<T>,\n options: RetryOptions,\n): Promise<T> {\n const retryable = options.idempotent && options.enabled !== false;\n const maxAttempts = retryable ? MAX_ATTEMPTS : 1;\n const sleep = options.sleepFn ?? defaultSleep;\n const random = options.randomFn ?? Math.random;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n try {\n return await fn(attempt);\n } catch (err) {\n const isLastAttempt = attempt === maxAttempts;\n if (!retryable || !(err instanceof NetworkError) || isLastAttempt) {\n throw err;\n }\n const retryAfterMs = isRetryAfterCarrier(err) ? err.retryAfterMs : undefined;\n const delay = delayMs(attempt, retryAfterMs, random());\n options.admit?.(delay);\n // §16.5 — without this event a retried-then-succeeded call is invisible:\n // a slow success with no signal that the server is failing.\n options.telemetry?.emit({\n type: 'retry',\n operation: options.operation ?? 'unknown',\n attempt,\n delayMs: delay,\n reason: err instanceof Error ? err.message : String(err),\n });\n await sleep(delay);\n }\n }\n\n // Unreachable: the loop above always returns or throws.\n throw new NetworkError('retry loop exhausted without a result');\n}\n","// 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, type AxiosRequestConfig } from 'axios';\nimport type { AxiamClientOptions, ClientIdentity, RefreshGuard, Sensitive } from '../core/index.js';\nimport {\n CERT_PEM_MARKER,\n createRefreshGuard,\n DecisionMemo,\n DEFAULT_CONNECT_TIMEOUT_MS,\n DEFAULT_REQUEST_TIMEOUT_MS,\n resolveClientIdentity,\n TelemetryDispatcher,\n TelemetryReporter,\n} from '../core/index.js';\n\nconst PEM_MARKER = CERT_PEM_MARKER;\n\n/**\n * The single session object every AXIAM transport (REST here, gRPC/AMQP in\n * 17-03/17-04, middleware in 17-05) attaches to. Constructed once per\n * `AxiamClient` instance.\n */\nexport class SharedSession {\n /** The underlying axios instance this session's requests are issued through, pre-configured with `baseUrl`, credential forwarding, and (Node) an optional custom-CA `httpsAgent`. */\n readonly axios: AxiosInstance;\n /** The AXIAM server base URL this session was constructed with (`AxiamClientOptions.baseUrl`). */\n readonly baseUrl: string;\n /** The resolved tenant identifier (`tenantSlug` or `tenantId`) injected as the `X-Tenant-ID` header on every same-origin request (§5.2). */\n readonly tenantHeaderValue: string;\n /** Configured tenant UUID (`AxiamClientOptions.tenantId`), if the client was built with the UUID form. */\n readonly tenantId: string | undefined;\n /** Configured tenant slug (`AxiamClientOptions.tenantSlug`), if the client was built with the slug form. */\n readonly tenantSlug: string | undefined;\n /** Configured organization UUID (`AxiamClientOptions.orgId`), if supplied (§5). */\n readonly orgId: string | undefined;\n /** Configured organization slug (`AxiamClientOptions.orgSlug`), if supplied (§5). */\n readonly orgSlug: string | undefined;\n /** Expected `iss` for locally-verified access tokens (§10.1 rule 5), if configured; `undefined` means no issuer check. */\n readonly expectedIssuer: string | undefined;\n /** Expected `aud` for locally-verified access tokens (§10.1 rule 6), if configured; `undefined` means no audience check. */\n readonly expectedAudience: string | undefined;\n /**\n * True when this session was constructed with a §6.1 mTLS client identity\n * (`clientCert` + `clientKey`), and therefore presents a client certificate\n * on every request it makes.\n *\n * Read by the §12 OIDC helpers to decide whether CONTRACT.md §21.3 rule 2\n * applies: an `mtls_endpoint_aliases` entry is preferred only on a call that\n * is actually going over mutual TLS, and a session without an identity must\n * keep using the top-level endpoints.\n */\n readonly presentsClientCertificate: boolean;\n /**\n * Resolved tenant UUID used to build the `refresh` body (`RefreshRequest`\n * requires the UUID form, not a slug). Seeded from `orgId`/`tenantId` config\n * when the UUID was supplied, then updated from the access-token `tenant_id`\n * claim after each successful login/refresh (Node persona only — the browser\n * cannot read the httpOnly access-token cookie).\n */\n resolvedTenantId: string | undefined;\n /**\n * Resolved organization UUID used to build the `refresh` body. Seeded from\n * `orgId` config, then updated from the access-token `org_id` claim after a\n * successful login (Node persona). Mirrors the Rust SDK's `resolved_org_id`.\n */\n resolvedOrgId: string | undefined;\n /**\n * The tenant the signed-in principal's record *lives* in — CONTRACT.md\n * §5.2.2 — as reported by the login response.\n *\n * Distinct from `resolvedTenantId`, which is the tenant being acted on: the\n * two diverge for an organization-level principal that has selected another\n * one. Read by `opaqueEnrollmentForSelf`, which must seal a §23 record\n * against the account's own tenant rather than whichever one this client is\n * currently pointed at. `undefined` until a login completes.\n */\n resolvedPrincipalTenantId: string | undefined;\n /** Mutable CSRF token store — populated by the request/response interceptors (D-05). */\n csrfToken: string | undefined;\n /** Set true once a successful login/verifyMfa has completed. */\n authenticated = false;\n /**\n * §17 decision memo (contract 1.51: moved here from `AxiamClient` so every\n * handle sharing this session — the base client and any\n * `actingTenant(id)`/`clearActingTenant()` clone of it — shares one memo\n * rather than each getting an empty one of its own). Disabled unless\n * `decisionMemoTtlMs` was configured.\n */\n readonly decisionMemo: DecisionMemo;\n /**\n * §19 telemetry dispatcher (moved here alongside `decisionMemo`, same\n * reason). Empty unless a hook was installed.\n */\n readonly telemetry: TelemetryReporter;\n /** §16.1 disable switch (moved here alongside `decisionMemo`). Defaults to enabled. */\n readonly retryEnabled: boolean;\n /**\n * §18 shutdown flag (moved here from `AxiamClient`, contract 1.51): a\n * handle and every clone of it sharing this session close together, exactly\n * as the Rust reference's `Arc<AxiamClientInner>` closes every handle over\n * it. Set once by `AxiamClient.close()`; read by `ensureOpen()`.\n */\n closed = false;\n /**\n * Whether {@link installInterceptors} has already run for this session's\n * axios instance (contract 1.51). Guards `AxiamClient.actingTenant()` /\n * `.clearActingTenant()`, which construct a second `AxiamClient` handle\n * over this same session: without this flag that second construction would\n * install the CSRF/refresh interceptors a second time, double-running them\n * on every request. Checked and set only by `rest/client.ts`.\n *\n * @internal\n */\n interceptorsInstalled = false;\n /**\n * CONTRACT.md §5.2 / §5.2.3 (contract 1.51) — what the last completed login\n * reported about the principal's reach, when it reported anything at all.\n *\n * `undefined` until a session-establishing response has carried a user\n * object, and reset to `undefined` by `logout()` and by\n * `authenticateDevice()` (§6.1: a device token is a service-account\n * credential with no `LoginUserInfo` behind it). It is `undefined` on\n * purpose rather than a defaulted `false` — \"the server did not say\"\n * must not gate `AxiamClient.actingTenant()` as though the server had\n * said \"not organization-level\" (§5.2 rule 1: a client holding no login\n * result has nothing to gate on, so it sends the header and lets the\n * server's `403` decide).\n *\n * Shared across every handle over this session, not per-handle — the\n * principal did not change because a caller asked for a different acting\n * tenant.\n */\n principalScope:\n | {\n /** What the login response's `organizationLevel` reported. */\n organizationLevel: boolean;\n /** What the login response's `reachableTenantIds` reported, if present. `undefined` means unrestricted. */\n reachableTenantIds?: string[];\n }\n | undefined;\n /**\n * CONTRACT.md §6.1 rules 6–10 (contract 1.51) — the access token\n * `authenticateDevice()` adopted, when this session's credential is a\n * device/mTLS one rather than a cookie session.\n *\n * `undefined` is the state every session starts in and the only one\n * before contract 1.51: nothing about REST authentication changes for a\n * client that never calls `authenticateDevice()`. Once set, the request\n * interceptor installed in `createSession` sends it as\n * `Authorization: Bearer <token>` and switches this request to the\n * jar-free agent pair `noCredentialsConfig()` builds — the server reads\n * the `axiam_access` cookie **before** the `Authorization` header (rule 3\n * of the \"what the plan did not anticipate\" note), so a cookie left over\n * from an earlier session would otherwise silently outrank this token and\n * the request would run as that earlier session's principal. There is no\n * refresh token behind a device token (rule 6), so `installRefreshInterceptor`\n * checks this field too and never attempts one.\n *\n * Cleared by `logout()`, and by a subsequent `login()`/`verifyMfa()` that\n * establishes an ordinary cookie session on the same client.\n */\n deviceAccessToken: Sensitive<string> | undefined;\n /**\n * Per-instance single-flight refresh guard (CR-02, D-13). Shared across\n * this session's REST and gRPC transports (rest/interceptors.ts,\n * grpc/callWithRefresh.ts both call `session.refreshGuard(...)`), but\n * NEVER shared with a different SharedSession/NodeSession instance.\n *\n * @internal SDK-internal transport wiring, not intended to be invoked\n * directly by SDK consumers — refreshes are driven automatically by the\n * response interceptor (rest) or `callWithRefresh` (grpc).\n */\n readonly refreshGuard: RefreshGuard;\n\n constructor(options: AxiamClientOptions, axiosInstance: AxiosInstance, tenantHeaderValue: string) {\n this.axios = axiosInstance;\n this.baseUrl = options.baseUrl;\n this.tenantHeaderValue = tenantHeaderValue;\n this.tenantId = options.tenantId;\n this.tenantSlug = options.tenantSlug;\n this.orgId = options.orgId;\n this.orgSlug = options.orgSlug;\n this.expectedIssuer = options.expectedIssuer;\n this.expectedAudience = options.expectedAudience;\n // Both halves, because §6.1 is all-or-nothing: `resolveClientIdentity`\n // rejects one without the other before this line is reached.\n this.presentsClientCertificate =\n options.clientCert !== undefined && options.clientKey !== undefined;\n registerTlsOptions(this, options);\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 // §17.1 rule 1: off unless the caller asked for it.\n this.decisionMemo = new DecisionMemo(options.decisionMemoTtlMs ?? 0);\n this.telemetry = new TelemetryReporter(new TelemetryDispatcher(options.telemetryHook));\n // §19.2 rule 6: a clamped setting is reported, not swallowed. Emitted once,\n // here, because construction is the only moment an operator can act on it.\n this.decisionMemo.reportClamp(options.decisionMemoTtlMs ?? 0, this.telemetry.dispatcher);\n this.retryEnabled = options.retryEnabled ?? true;\n }\n\n /**\n * 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 an origin (scheme, host and port) 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 // Origin, not host: a same-host URL on another scheme (`http://` against\n // an `https://` base) is a different origin and must not receive the\n // tenant header or the CSRF token in cleartext.\n const target = new URL(url, this.baseUrl);\n return target.origin !== new URL(this.baseUrl).origin;\n } catch {\n return true;\n }\n }\n\n /**\n * Axios config for a call that MUST NOT carry this session's own credential\n * — no jar cookie, no `Authorization` header — even when the session is\n * otherwise authenticated (CONTRACT.md §24.1, contract 1.45: the\n * `setup/register/*` pair takes a setup token as its only credential, and\n * an SDK MUST NOT attach a second one).\n *\n * The browser persona has no jar of its own to bypass: cookies ride solely\n * because of `withCredentials`, so turning it off for this one request is\n * the whole fix — the platform manages the rest, and this SDK never sets an\n * `Authorization` header on an `AxiamClient` call in the first place.\n * `NodeSession` overrides this: `withCredentials` has no effect on\n * axios's Node http adapter, whose cookie behaviour comes from the agent\n * attached to the instance, not from per-request config.\n */\n noCredentialsConfig(): AxiosRequestConfig {\n return { withCredentials: false };\n }\n\n /**\n * Axios config for a request to an `/oauth2/*` endpoint (CONTRACT.md §12.1\n * rule 3, §14.6; C163-12): {@link noCredentialsConfig} and, in the browser\n * persona, the fetch adapter with `credentials: 'omit'`.\n *\n * `withCredentials: false` on axios's default XHR adapter is not enough: that\n * adapter sends a same-origin cookie regardless, so an app served from the\n * AXIAM origin would still present `axiam_*` on a token or device request.\n * The fetch adapter derives its `credentials` from `withCredentials: false`\n * (`'omit'`); `fetchOptions.credentials` is set as well for adapters that\n * read it.\n *\n * `fetchOptions.redirect: 'error'` is the browser persona's half of CONTRACT.md §12.1\n * rule 3 (\"No redirect is followed\", C165-26). On the main client's `/oauth2/*` requests\n * it makes `fetch` reject, which every caller maps to a `NetworkError` that carries\n * neither the `Location` nor the request. Where `maxRedirects: 0` is set (the bare\n * transport, `bareRequest`), axios's fetch adapter substitutes `redirect: 'manual'`\n * (`lib/adapters/fetch.js`), so `'error'` is overridden there: the browser hands back an\n * opaque-redirect (status 0), and `bareRequest` maps status 0 or any `3xx` to a\n * `NetworkError` without the `Location` (`bareTransport.ts`).\n * `NodeSession` overrides this to {@link noCredentialsConfig}: its jar-free\n * agent pair is what keeps the cookies off there, and the fetch adapter\n * would bypass that pair.\n */\n oauth2RequestConfig(): AxiosRequestConfig {\n return { ...this.noCredentialsConfig(), adapter: 'fetch', fetchOptions: { credentials: 'omit', redirect: 'error' } };\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 * The options an `https.Agent` (or `HttpsCookieAgent`) is constructed with for `tls`.\n *\n * Node's `ca` option REPLACES the process trust store (bundled roots, OpenSSL's under\n * `--use-openssl-ca`, `NODE_EXTRA_CA_CERTS`), but CONTRACT.md §6 makes `customCa` an ADDED anchor. So\n * when a CA is configured the agent gets a secure context that starts from that store, has the CA\n * added to it, and carries the client identity (§6.1). Server verification stays at its default;\n * there is no way to switch it off through this function (#176).\n */\nexport function agentTlsOptions(tls: NodeTlsOptions | undefined): Record<string, unknown> {\n if (tls === undefined) return {};\n if (tls.ca === undefined) {\n return { ...(tls.cert !== undefined ? { cert: tls.cert } : {}), ...(tls.key !== undefined ? { key: tls.key } : {}) };\n }\n const tlsMod = loadNodeBuiltin<typeof import('node:tls')>('node:tls');\n const secureContext = tlsMod.createSecureContext({\n ...(tls.cert !== undefined ? { cert: tls.cert } : {}),\n ...(tls.key !== undefined ? { key: tls.key } : {}),\n });\n // `addCACert` is not in the public typings; it is what `ca` itself calls after clearing the store.\n (secureContext as unknown as { context: { addCACert(pem: string): void } }).context.addCACert(tls.ca);\n return { secureContext };\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 */\n/**\n * Load a Node builtin without ever statically referencing it — this file is\n * shared with the browser-safe `.`/`/rest` entries, so it must not import\n * `node:https`/`node:http` at the top level, yet the Node persona needs one\n * synchronously (session construction, and {@link SharedSession.noCredentialsConfig}).\n *\n * `process.getBuiltinModule` (Node >= 20.16 / >= 22.3) loads a builtin with no\n * module system involved — no `import`, no `require`, nothing for a bundler to\n * rewrite. A bare `require('node:...')` satisfies the \"no static import\"\n * constraint but not the synchronous-under-ESM one: tsup rewrites it into a\n * shim that throws `Dynamic require of \"...\" is not supported`, so under\n * genuine Node ESM (`axiam-sdk/node`'s `import` condition) it would fail\n * before the module ever loaded. Reached off `process`, which every caller has\n * already capability-guarded, so a browser bundle never evaluates this.\n */\nfunction loadNodeBuiltin<T>(id: 'node:https' | 'node:http' | 'node:tls'): T {\n const getBuiltinModule = (\n process as unknown as { getBuiltinModule?: (moduleId: string) => unknown }\n ).getBuiltinModule;\n if (typeof getBuiltinModule === 'function') {\n return getBuiltinModule.call(process, id) as T;\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(id) as T;\n } catch {\n throw new Error(\n `this call requires Node's ${id} 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\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 return loadNodeBuiltin<typeof import('node:https')>('node:https');\n}\n\n/**\n * The TLS material each session was configured with, kept OUT of the session's\n * own (public) fields because it holds the client private key (§6.1 rule 3 /\n * §7). Read only through {@link nodeTlsOptionsOf}, by the Node JWKS verifiers.\n */\nconst sessionTlsOptions = new WeakMap<SharedSession, NodeTlsOptions>();\n\nfunction registerTlsOptions(session: SharedSession, options: AxiamClientOptions): void {\n if (options.customCa === undefined && options.clientCert === undefined) return;\n try {\n const tls = resolveNodeTlsOptions(options);\n if (tls !== undefined) sessionTlsOptions.set(session, tls);\n } catch {\n // Invalid material is rejected by `createSession` / `createNodeSession`,\n // which validate before constructing; a hand-built session simply has none.\n }\n}\n\n/**\n * The TLS material `session` was configured with (`customCa`, §6.1 identity),\n * for the JWKS fetch that must trust the same CA as its REST calls (#175).\n * `undefined` when the session has none.\n *\n * The client identity (`cert`/`key`) is included ONLY when `targetUrl` has the\n * same origin as the session's base URL (or none is given): a `jwks_uri` on\n * another host (§12.3 rule 6) gets `customCa` trust alone, so the identity is\n * never presented to a server the client was not configured to authenticate to.\n *\n * Not exported from the package barrel: the result holds the private key.\n */\nexport function nodeTlsOptionsOf(session: SharedSession, targetUrl?: string): NodeTlsOptions | undefined {\n const tls = sessionTlsOptions.get(session);\n if (tls === undefined || targetUrl === undefined) return tls;\n let sameOrigin = false;\n try {\n sameOrigin = new URL(targetUrl).origin === new URL(session.baseUrl).origin;\n } catch {\n sameOrigin = false;\n }\n if (sameOrigin) return tls;\n return tls.ca !== undefined ? { ca: tls.ca } : undefined;\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\n/**\n * A pair of plain (non-jar) Node agents, TLS-configured from the same\n * material {@link resolveNodeTlsOptions} produces, for `NodeSession`'s\n * {@link SharedSession.noCredentialsConfig}. Deliberately **not** the\n * jar-wrapped `HttpCookieAgent`/`HttpsCookieAgent` `wrapAxios` builds\n * (`src/node/cookieJar.ts`): that agent injects this session's cookies into\n * every request it carries regardless of axios per-request config (it acts at\n * the raw `http.ClientRequest` layer — see `create_cookie_agent.js`'s\n * `addRequest` override), so a call that must not carry them needs a\n * different agent object entirely, not a config flag.\n *\n * Built once, lazily, and cached by the caller — `https.Agent`/`http.Agent`\n * pool connections, and there is no reason for the one call a client makes\n * with no session to open a fresh socket every time.\n */\nexport function buildPlainNodeAgents(tls: NodeTlsOptions | undefined): {\n httpAgent: unknown;\n httpsAgent: unknown;\n} {\n const http = loadNodeBuiltin<typeof import('node:http')>('node:http');\n const https = loadNodeHttps();\n return {\n httpAgent: new http.Agent(),\n httpsAgent: new https.Agent(agentTlsOptions(tls)),\n };\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(agentTlsOptions(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 // The §6.1 device-token interceptor (contract 1.51) is installed by\n // `installInterceptors` (rest/interceptors.ts) instead of here, alongside\n // CSRF/refresh — NOT here, deliberately. This function's `session` is\n // discarded by the Node persona once its `.axios`/`.tenantHeaderValue` are\n // lifted into a wrapping `NodeSession` (see `createNodeSession`); an\n // interceptor closing over it would keep reading a `deviceAccessToken`\n // that `authenticateDevice()` actually sets on the *NodeSession*, and\n // never see it. `installInterceptors` runs against whichever session\n // `AxiamClient`'s constructor was actually given, which is always the\n // right one.\n return session;\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';\nimport type { ProviderNonce } from './oidcTypes.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\n/**\n * A fresh nonce pair for native sign-in with a provider ID token\n * (CONTRACT.md §37.4) — **pure local computation, no network I/O**.\n *\n * `raw` is 32 CSPRNG bytes, base64url without padding, wrapped in\n * {@link Sensitive}; `hashed` is the lower-case hexadecimal SHA-256 of the\n * bytes of `raw` as sent. Give `hashed` to the provider's SDK as *its* nonce\n * and `raw` to `loginWithProviderIdToken`. Nothing is stored.\n */\nexport function nativeNonce(): ProviderNonce {\n const raw = randomUrlSafeToken(CSPRNG_BYTES);\n return { raw: new Sensitive(raw), hashed: createHash('sha256').update(raw, 'utf8').digest('hex') };\n}\n","// OIDC / SSO relying-party helpers — CONTRACT.md §12 (contract 1.38).\n//\n// The thirteen canonical §12 operations, under the exact §12.2 TypeScript\n// names: oidcDiscover, oidcBegin, oidcExchange, oidcRefresh,\n// loginClientCredentials, introspect, revoke, ssoStart, ssoComplete, and — as\n// of contract 1.38 — ssoProviders, ssoStartOauth2, ssoCompleteOauth2,\n// ssoCompleteHandoff.\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 (§1 refresh); oidcRefresh: per-token map;\n// * §12.4 signature verification → node/jwks.ts's verifier;\n// * §7/§12.5 redaction → core/sensitive.ts.\n\nimport { createHash, randomBytes, timingSafeEqual, type KeyObject } from 'node:crypto';\nimport type { AxiosRequestConfig, AxiosResponse } from 'axios';\nimport {\n AuthError,\n AxiamError,\n isOAuth2ErrorBody,\n mapHttpStatusToError,\n NetworkError,\n OAuthProtocolError,\n oauth2ErrorFromBody,\n sanitizeAxiosError,\n Sensitive,\n} from '../core/index.js';\nimport { ValidationError } from '../management/errors.js';\nimport { retryAfterMs, retryableNetworkError, statusIsRetryable } from '../rest/bareTransport.js';\nimport { isOAuth2Endpoint } from '../rest/interceptors.js';\nimport { withRetry } from '../rest/retry.js';\nimport { nodeTlsOptionsOf, type SharedSession } from '../rest/session.js';\nimport { createJwksVerifier, type JwksVerifier } from './jwks.js';\nimport { resolveClockSkewSec, 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 LoginWithProviderIdTokenOptions,\n OidcBeginParams,\n OidcConfiguration,\n OidcExchangeParams,\n MtlsEndpointAliases,\n OidcRefreshParams,\n OidcStartResponseWire,\n OidcTokenSet,\n RevokeParams,\n SsoCompleteParams,\n SsoCompleteResult,\n SsoLoginSuccessResponseWire,\n SsoStartParams,\n SsoStartResult,\n FederationProvider,\n FederationProviderList,\n OAuth2StartResponseWire,\n PublicFederationProvidersResponseWire,\n SsoCompleteHandoffParams,\n SsoCompleteOauth2Params,\n SsoProvidersParams,\n SsoStartOauth2Params,\n TokenResponseWire,\n DeviceAuthorization,\n DeviceAuthorizationResponseWire,\n DeviceAuthorizeParams,\n DeviceLoginParams,\n DevicePollParams,\n ExchangedToken,\n LogoutUrlParams,\n TokenExchangeParams,\n TokenExchangeResponseWire,\n VerifiedLogoutToken,\n RequestedPermission,\n RequestingPartyToken,\n ResourceSet,\n ResourceSetWire,\n RptResponseWire,\n UmaChallenge,\n UmaExchangeTicketParams,\n OidcParParams,\n PushedAuthorizationRequest,\n PushedAuthorizationResponseWire,\n CibaAwaitParams,\n CibaClock,\n CibaInitiateParams,\n CibaInitiateResponse,\n CibaPingHeaders,\n CibaPollParams,\n CibaSigningAlg,\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/** Path of the public provider-listing endpoint (contract 1.38). */\nexport const SSO_PROVIDERS_PATH = '/api/v1/auth/federation/providers';\n\n/** Path of the plain-OAuth2 federation step-1 endpoint (contract 1.38). */\nexport const SSO_OAUTH2_START_PATH = '/api/v1/auth/federation/oauth2/start';\n\n/** Path of the plain-OAuth2 federation step-2 (callback) endpoint (contract 1.38). */\nexport const SSO_OAUTH2_CALLBACK_PATH = '/api/v1/auth/federation/oauth2/callback';\n\n/** Path of the handoff-code redemption endpoint (contract 1.38). */\nexport const SSO_HANDOFF_PATH = '/api/v1/auth/federation/handoff';\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/** `grant_type` of the device access-token request (RFC 8628 §3.4). */\nexport const DEVICE_CODE_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:device_code';\n\n/**\n * Polling interval used when the authorization response omits `interval`\n * (RFC 8628 §3.2, §14.2 rule 2). An SDK MUST NOT hard-code a faster floor.\n */\nexport const DEFAULT_POLL_INTERVAL_SECS = 5;\n\n/**\n * Seconds added to the polling interval on each `slow_down` (§14.2 rule 1).\n * The increase is permanent and cumulative.\n */\nexport const SLOW_DOWN_INCREMENT_SECS = 5;\n\n/** `grant_type` of an RFC 8693 exchange. */\nexport const TOKEN_EXCHANGE_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange';\n\n/**\n * The `actor_token_type` this SDK sends, and the `subject_token_type` a caller\n * names for the same-domain exchange of §15.1. There is no default: the type is\n * a required member of {@link TokenExchangeParams}.\n */\nexport const ACCESS_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token';\n\n/**\n * A JWT from a trusted external issuer — the cross-domain exchange of §15.7.\n *\n * @remarks\n * Pass it as {@link TokenExchangeParams.subjectTokenType} to exchange a partner\n * IdP's token. AXIAM also accepts {@link ACCESS_TOKEN_TYPE} for an external\n * issuer, and refuses refresh and ID token types **by name**.\n */\nexport const JWT_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:jwt';\n\n/** `grant_type` of the UMA ticket grant (UMA 2.0 §3.3.1, CONTRACT.md §20.1). */\nexport const UMA_TICKET_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:uma-ticket';\n\n/** The scope that makes an access token a Protection API Token (§20.2 rule 1). */\nexport const UMA_PROTECTION_SCOPE = 'uma_protection';\n\n/** The only `claim_token_format` AXIAM v1 accepts (§20.2 rule 2). */\nexport const UMA_CLAIM_TOKEN_FORMAT = 'urn:ietf:params:oauth:token-type:access_token';\n\n/**\n * Parse a `WWW-Authenticate: UMA …` header value (CONTRACT.md §20.3).\n *\n * @remarks\n * **This deliberately does not exchange the ticket.** Parsing a challenge and\n * acting on it are separate decisions: the `as_uri` names an authorization\n * server this client has not necessarily chosen to trust, and auto-exchanging\n * would send the requesting party's `claimToken` to whatever host answered the\n * 403. The caller decides.\n *\n * @returns the parsed challenge, or `undefined` when the header is not a UMA\n * challenge.\n */\nexport function umaParseChallenge(header: string): UmaChallenge | undefined {\n const trimmed = header.trim();\n if (!trimmed.startsWith('UMA')) return undefined;\n const rest = trimmed.slice(3);\n // \"UMA\" alone is a valid, if useless, challenge; anything else must be\n // separated by whitespace so `UMAX realm=\"…\"` is not read as UMA.\n if (rest.length > 0 && !/^\\s/.test(rest)) return undefined;\n\n const challenge: UmaChallenge = {};\n for (const part of rest.split(',')) {\n const eq = part.indexOf('=');\n if (eq === -1) continue;\n const key = part.slice(0, eq).trim();\n const value = part.slice(eq + 1).trim().replace(/^\"|\"$/g, '');\n if (key === 'realm') challenge.realm = value;\n else if (key === 'as_uri') challenge.asUri = value;\n else if (key === 'ticket') challenge.ticket = new Sensitive(value);\n }\n return challenge;\n}\n\n/**\n * Format a `WWW-Authenticate: UMA` header value (§20.3, emit half).\n *\n * The resource-server side: having obtained a ticket from `umaRequestTicket`,\n * tell the caller where to redeem it.\n */\nexport function umaChallengeHeader(\n realm: string,\n asUri: string,\n ticket: Sensitive<string> | string,\n): string {\n return `UMA realm=\"${realm}\", as_uri=\"${asUri}\", ticket=\"${exposeSecret(ticket)}\"`;\n}\n\n/** Map the camelCase {@link ResourceSet} onto the snake_case wire shape. */\nfunction toResourceSetWire(resource: ResourceSet): ResourceSetWire {\n return {\n name: resource.name,\n ...(resource.type !== undefined ? { type: resource.type } : {}),\n // Always sent, even when empty: an update replaces the scope list, and\n // omitting the key would leave the server's copy untouched (§20.2 rule 8).\n resource_scopes: resource.resourceScopes ?? [],\n };\n}\n\n/** Map the wire shape back onto {@link ResourceSet}. */\nfunction fromResourceSetWire(wire: ResourceSetWire): ResourceSet {\n return {\n ...(wire._id != null ? { id: wire._id } : {}),\n name: wire.name,\n ...(wire.type != null ? { type: wire.type } : {}),\n resourceScopes: wire.resource_scopes ?? [],\n };\n}\n\n/**\n * The `events` member that distinguishes a logout token from an ID token\n * (OIDC Back-Channel Logout 1.0 §2.4).\n */\nexport const BACKCHANNEL_LOGOUT_EVENT = 'http://schemas.openid.net/event/backchannel-logout';\n\n/**\n * Maximum age accepted for a logout token's `iat`, in seconds. AXIAM issues\n * them with a 120 s lifetime; this bound is the same order and stops a token\n * captured from a mis-configured RP being replayed days later.\n */\nexport const MAX_LOGOUT_TOKEN_AGE_SECS = 300;\n\n/** The claim shape of a back-channel logout token (§12.7.3). */\ninterface LogoutTokenClaims {\n iss?: string;\n aud?: string;\n iat?: number;\n exp?: number;\n jti?: string;\n sid?: string;\n sub?: string;\n events?: Record<string, unknown>;\n /** Never legitimately present — see `verifyLogoutToken`. */\n nonce?: string;\n}\n\n/**\n * The §14.2 polling schedule: the interval, and the deadline it stops at.\n *\n * @remarks\n * Exported so the arithmetic §14.2 rules 1, 2 and 4 describe can be tested\n * exhaustively and instantly. Driving it through a mock HTTP server would\n * test the transport rather than the rule, and would take a real half-minute\n * to assert one `slow_down`.\n *\n * @internal\n */\nexport class PollSchedule {\n #intervalSecs: number;\n #remainingSecs: number;\n /** A `Retry-After` still to be served by the next wait (§14.2 rule 9, contract 1.64). */\n #retryAfterSecs = 0;\n\n constructor(intervalSecs: number, expiresInSecs: number) {\n this.#intervalSecs = intervalSecs > 0 ? intervalSecs : DEFAULT_POLL_INTERVAL_SECS;\n this.#remainingSecs = expiresInSecs;\n }\n\n /** The current inter-poll delay, in seconds. */\n get intervalSecs(): number {\n return this.#intervalSecs;\n }\n\n /**\n * The delay before the next poll, in seconds: the interval, or the pending\n * `Retry-After` when that is longer (a minimum, §14.2 rule 9).\n */\n get waitSecs(): number {\n return Math.max(this.#intervalSecs, this.#retryAfterSecs);\n }\n\n /**\n * Record a `429 rate_limit_exceeded` (§14.2 rule 9, contract 1.64): the next\n * wait lasts at least `retryAfterSecs` and stands in for one interval. The\n * interval itself is **not** raised — only the `400 slow_down` does that.\n */\n rateLimited(retryAfterSecs: number | undefined): void {\n this.#retryAfterSecs = retryAfterSecs !== undefined && retryAfterSecs > 0 ? retryAfterSecs : 0;\n }\n\n /** Apply one `slow_down` (§14.2 rule 1): **cumulative, never reset.** */\n slowDown(): void {\n this.#intervalSecs += SLOW_DOWN_INCREMENT_SECS;\n }\n\n /**\n * Consume one interval's worth of the grant's remaining life.\n *\n * @returns `false` when the deadline has been reached, at which point the\n * caller MUST stop (§14.2 rule 4) — the deadline is authoritative even if\n * the server is still answering `authorization_pending`.\n */\n tick(): boolean {\n // A pending `Retry-After` is served once, in place of the interval; past\n // the deadline it is capped there (§14.2 rule 9), which ends the loop.\n const waitSecs = this.waitSecs;\n this.#retryAfterSecs = 0;\n if (waitSecs >= this.#remainingSecs) {\n this.#remainingSecs = 0;\n return false;\n }\n this.#remainingSecs -= waitSecs;\n return true;\n }\n}\n\n/**\n * The `Retry-After` of a `429 rate_limit_exceeded` poll, in milliseconds, kept\n * beside the error rather than on it so the public error type is unchanged.\n */\nconst POLL_RETRY_AFTER_MS = new WeakMap<OAuthProtocolError, number>();\n\n/**\n * The §14.2 rule 9 reading of a device poll's `429` (contract 1.64, amended:\n * the status decides, not the body): an `OAuthProtocolError` with\n * `error == \"rate_limit_exceeded\"` whatever the body names — a bodiless `429`\n * from a proxy, or one saying `slow_down` as a server before 1.1.2 sent it,\n * included — with its `Retry-After` recorded in {@link POLL_RETRY_AFTER_MS}.\n * `undefined` for any other status, which keeps §2's mapping.\n */\nfunction pollRateLimit(err: unknown): OAuthProtocolError | undefined {\n if (axiosStatus(err) !== 429) return undefined;\n const body = axiosBody(err);\n const description =\n body !== null && typeof body === 'object' && typeof (body as { error_description?: unknown }).error_description === 'string'\n ? (body as { error_description: string }).error_description\n : '';\n const response = (err as { response?: AxiosResponse }).response;\n const retryAfter = response ? retryAfterMs(response) : undefined;\n const limited = new OAuthProtocolError('rate_limit_exceeded', description, retryAfter);\n if (retryAfter !== undefined) POLL_RETRY_AFTER_MS.set(limited, retryAfter);\n return limited;\n}\n\n/** Await `ms` milliseconds. Extracted so tests can stub the timer. */\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\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/** The query parameter / pushed field that names the sign-in provider (§12.1 \"`idp_hint`\", contract 1.65). */\nconst IDP_HINT_PARAM = 'axiam_idp_hint';\n\n/** The longest `idp_hint`, in UTF-8 bytes (§12.1 \"`idp_hint`\" rule 2). */\nconst IDP_HINT_MAX_BYTES = 256;\n\n/** The grant type of native sign-in with a provider ID token (CONTRACT.md §37). */\nexport const PROVIDER_ID_TOKEN_GRANT_TYPE = 'urn:axiam:params:oauth:grant-type:provider-id-token';\n\n/**\n * Refuse an `idp_hint` that is empty or over {@link IDP_HINT_MAX_BYTES} bytes\n * (§12.1 \"`idp_hint`\" rule 2) — and nothing else: no trimming, case-folding,\n * UUID parsing or lookup.\n */\nfunction checkIdpHint(operation: string, hint: string): void {\n if (hint === '') {\n throw new ValidationError(operation, 400, `${operation}: idpHint must not be empty (CONTRACT.md §12.1)`, [\n { field: 'idpHint', message: 'must not be empty' },\n ]);\n }\n if (Buffer.byteLength(hint, 'utf8') > IDP_HINT_MAX_BYTES) {\n throw new ValidationError(\n operation,\n 400,\n `${operation}: idpHint must be at most ${IDP_HINT_MAX_BYTES} bytes (CONTRACT.md §12.1)`,\n [{ field: 'idpHint', message: `must be at most ${IDP_HINT_MAX_BYTES} bytes` }],\n );\n }\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/**\n * The single-flight key of an `oidcRefresh` call: a SHA-256 digest of the resolved tenant UUID and the\n * refresh token. The raw token is never a map key.\n */\nfunction refreshFlightKey(refreshToken: Sensitive<string> | string, resolvedTenantId: string): string {\n return createHash('sha256')\n .update(resolvedTenantId.toLowerCase())\n .update('\\0')\n .update(exposeSecret(refreshToken))\n .digest('hex');\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 */\n/** The non-empty `axiam_idp_hint` an `oidcBegin` URL carries, or `undefined` (D-N36). */\nfunction beginUrlIdpHint(url: string): string | undefined {\n try {\n const value = new URL(url).searchParams.get(IDP_HINT_PARAM);\n return value === null || value === '' ? undefined : value;\n } catch {\n return undefined;\n }\n}\n\n/**\n * §12.1 rule 3 / §37.2 rule 12 (C165-14): an `/oauth2/*` POST never follows a redirect — a 307/308\n * would re-send the form, and its credentials, to the `Location` target. The `3xx` is a\n * `NetworkError` that names the status only (no `Location`, no axios cause: its config holds the form).\n */\nfunction redirectRefused(operation: string, status: number): NetworkError {\n return new NetworkError(`${operation}: the server answered HTTP ${status}; a redirect is never followed (CONTRACT.md §12.1 rule 3)`);\n}\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 && status >= 300 && status < 400) {\n return redirectRefused(fallbackMessage, status);\n }\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 * Map an error from the **uma-ticket grant**, where `access_denied` arrives as\n * HTTP **403** (UMA 2.0 §3.3.6) rather than the 400 every other OAuth2 error\n * uses.\n *\n * @remarks\n * §20.4 requires dispatching on the `error` field rather than the status, so\n * that the code reaches the caller whichever status carries it. This is kept\n * local to the ticket grant on purpose: {@link mapHttpStatusToError}'s §2 rows\n * apply the OAuth2 mapping to 400/401 only, and widening that globally would\n * change how every OAuth2 endpoint's 403 is reported — a cross-cutting change\n * this grant does not need and did not ask for. An ordinary REST 403 keeps\n * mapping to `AuthzError`.\n */\nfunction mapUmaGrantError(err: unknown, url: string, fallbackMessage: string): AxiamError {\n if (err instanceof AxiamError) {\n return err;\n }\n const body = axiosBody(err);\n if (axiosStatus(err) === 403 && isOAuth2ErrorBody(body)) {\n return new OAuthProtocolError(body.error, body.error_description);\n }\n return mapOidcError(err, url, fallbackMessage);\n}\n\n/**\n * Refuse an `mtls_endpoint_aliases` entry that cannot carry a client\n * certificate (CONTRACT.md §21.3.1 vector C, contract 1.43).\n *\n * Falling back to the top-level endpoint looks like the safe answer and is the\n * dangerous one: the caller asked to authenticate with a certificate, the\n * operator published something unusable, and sending the certificate to the\n * front-channel host authenticates nothing while appearing to work.\n *\n * Two defects, each a refusal on its own:\n *\n * * **Not an absolute URL.** A relative alias resolves against nothing the\n * client holds, and the base that might seem obvious — the issuer's host —\n * is precisely the host the alias exists to name a different one from.\n * * **A scheme weaker than the endpoint it replaces.** An alias substitutes\n * for exactly one top-level endpoint, so that is what it is compared\n * against. `https` → `http` is a downgrade; `http` → `http` is a\n * development deployment, which AXIAM's own `build_mtls_aliases` supports\n * and this suite's harness is.\n *\n * @throws AuthError — not `NetworkError`, and the difference is not cosmetic.\n * Nothing failed in transport: the server published a document this client\n * cannot use, which is the same taxonomy as a document advertising no endpoint\n * at all (see `oidcDeviceAuthorize`). It also matters operationally, because\n * §16.3 retries `NetworkError` and only `NetworkError` — the other choice would\n * have attempted a permanent, deterministic misconfiguration three times and\n * reported it as a transient one.\n */\nexport function assertUsableMtlsAlias(alias: string, replaces: string | undefined): void {\n let parsed: URL;\n try {\n parsed = new URL(alias);\n } catch {\n throw new AuthError(\n `mtls_endpoint_aliases publishes ${JSON.stringify(alias)}, which is not an absolute URL. ` +\n 'Refusing rather than falling back to the top-level endpoint: this call presents a ' +\n 'client certificate, and sending it to the front-channel host would authenticate ' +\n 'nothing while appearing to work.',\n );\n }\n let replacedIsTls = false;\n if (replaces !== undefined) {\n try {\n replacedIsTls = new URL(replaces).protocol === 'https:';\n } catch {\n replacedIsTls = false;\n }\n }\n if (replacedIsTls && parsed.protocol !== 'https:') {\n throw new AuthError(\n `mtls_endpoint_aliases publishes ${JSON.stringify(alias)}, whose scheme is ` +\n `${JSON.stringify(parsed.protocol)}, in place of an https endpoint. That is a ` +\n 'downgrade, and mutual TLS over cleartext is a contradiction; refusing rather than ' +\n 'falling back to the top-level endpoint.',\n );\n }\n}\n\n// ---------------------------------------------------------------------------\n// §33 CIBA — module-level definitions (contract 1.58)\n// ---------------------------------------------------------------------------\n\n/** `grant_type` of the CIBA token request (CIBA Core §10.1). */\nexport const CIBA_GRANT_TYPE = 'urn:openid:params:grant-type:ciba';\n\n/** The interval used when the initiate response carries none (§33.7 rule 2). */\nexport const DEFAULT_CIBA_INTERVAL_SECS = 5;\n\n/** Seconds added to the interval per `slow_down`, permanently and cumulatively (§33.7 rule 3). */\nexport const CIBA_SLOW_DOWN_INCREMENT_SECS = 5;\n\n/** The lifetime of a signed request this SDK mints: five minutes, inside the server's sixty-minute bound on `exp − nbf` (§33.2). */\nexport const SIGNED_REQUEST_LIFETIME_SECS = 300;\n\nconst CIBA_SIGNING_ALGS: ReadonlySet<string> = new Set(['PS256', 'ES256', 'EdDSA']);\n\n/**\n * The `NetworkError`s `cibaAwait` may wait out (§33.7 rule 5): a transport\n * failure, or a `408` / `429` / `5xx` that survived §16's retries inside\n * `cibaPoll`. A bodiless `400` is a `NetworkError` too (§2), but a decisive\n * one, and is not in here.\n */\nconst TRANSIENT_POLL_FAILURES = new WeakSet<NetworkError>();\n\nfunction transient(error: NetworkError): NetworkError {\n TRANSIENT_POLL_FAILURES.add(error);\n return error;\n}\n\n/** The real clock: `Date.now` and `setTimeout`. */\nconst SYSTEM_CIBA_CLOCK: CibaClock = { now: () => Date.now(), sleep };\n\n/** The deadline a polling loop hands the poll under it: a clock instant and the clock it is read on. */\ninterface PollDeadline {\n deadline: number;\n clock: CibaClock;\n}\n\n/**\n * The §16 retry of a poll inside a loop's deadline (§14.2 rule 4, §34.2 P10; C164-36): `admit`\n * refuses a wait — the jittered backoff floored at `Retry-After`, as `withRetry` computed it —\n * that would reach the deadline, before the retry is announced to telemetry or sent, by raising\n * the typed `expired_token`; `sleepFn` serves an admitted wait on the loop's clock.\n */\nfunction deadlineBoundedRetry(\n bound: PollDeadline,\n what: string,\n): { admit: (ms: number) => void; sleepFn: (ms: number) => Promise<void> } {\n return {\n admit: (ms) => {\n if (bound.clock.now() + ms >= bound.deadline) {\n throw new OAuthProtocolError(\n 'expired_token',\n `the ${what} expired before it was decided (client-side deadline from expires_in; CONTRACT.md §14.2 rule 4, §34.2 P10)`,\n );\n }\n },\n sleepFn: (ms) => bound.clock.sleep(ms),\n };\n}\n\n/**\n * Whether `err` is the `access_denied` answer — at a CIBA (or device) poll,\n * the user refused (§33.4). Distinct from {@link isExpiredToken}.\n */\nexport function isAccessDenied(err: unknown): err is OAuthProtocolError {\n return err instanceof OAuthProtocolError && err.error === 'access_denied';\n}\n\n/**\n * Whether `err` is the `expired_token` answer — nobody decided in time. Raised\n * by the server, and locally by `cibaAwait` when it reaches the request's\n * deadline (§33.4, §33.7 rule 4).\n */\nexport function isExpiredToken(err: unknown): err is OAuthProtocolError {\n return err instanceof OAuthProtocolError && err.error === 'expired_token';\n}\n\nfunction cibaRefusal(operation: string, field: string, message: string): ValidationError {\n return new ValidationError(operation, 400, `${operation}: ${field}: ${message} (CONTRACT.md §33)`, [\n { field, message },\n ]);\n}\n\n/** What a {@link CibaRequestSigner} renders as: the algorithm and `kid`, never the key. */\nexport interface CibaSignerDescription {\n /** The algorithm the signer signs under. */\n alg: CibaSigningAlg;\n /** The `kid` it puts in the JWS header, if any. */\n kid?: string;\n}\n\n/** The signing key a {@link CibaRequestSigner} accepts: a PKCS#8 PEM, or a private `KeyObject` / `CryptoKey`. */\nexport type CibaSigningKey = Sensitive<string> | KeyObject | CryptoKey;\n\nconst NODE_INSPECT_CUSTOM = Symbol.for('nodejs.util.inspect.custom');\n\n/**\n * The key and algorithm for CIBA's signed request form (§33.2, CIBA Core\n * §7.1.1). Both are the caller's: there is no default for either, and the SDK\n * signs under exactly the algorithm given — the one the client registered as\n * `backchannel_authentication_request_signing_alg`.\n *\n * @remarks\n * Signing uses `jose` (PS256, ES256 and EdDSA). The key is held privately and\n * appears in no rendering: `String()`, `JSON.stringify` and `util.inspect` show\n * the algorithm and `kid` only.\n */\nexport class CibaRequestSigner {\n readonly #alg: CibaSigningAlg;\n readonly #key: Sensitive<KeyObject | CryptoKey>;\n readonly #kid: string | undefined;\n\n private constructor(alg: CibaSigningAlg, key: KeyObject | CryptoKey, kid: string | undefined) {\n this.#alg = alg;\n this.#key = new Sensitive(key);\n this.#kid = kid;\n }\n\n /**\n * A signer from a private key and the algorithm it signs under.\n *\n * @param alg `PS256`, `ES256` or `EdDSA` — required, never defaulted.\n * @param key a PKCS#8 PEM (wrapped in `Sensitive`), or a private `KeyObject` / `CryptoKey`.\n * @param kid the `kid` to put in the JWS header, if the client's JWKS names one.\n * @throws ValidationError (local, before any request) when `alg` is not one\n * of the three, or the key is empty, not a private key, or one that cannot\n * sign under `alg` — proved by signing a probe.\n */\n static async create(alg: CibaSigningAlg, key: CibaSigningKey, kid?: string): Promise<CibaRequestSigner> {\n const refuse = (): ValidationError =>\n cibaRefusal(\n 'ciba_initiate',\n 'signing_key',\n 'the key is not a private key that signs under the given algorithm (PS256, ES256 or EdDSA)',\n );\n if (!CIBA_SIGNING_ALGS.has(alg)) throw refuse();\n const jose = await import('jose');\n let material: KeyObject | CryptoKey;\n try {\n if (key instanceof Sensitive) {\n const pem = key.expose();\n if (typeof pem !== 'string' || pem.trim() === '') throw new Error('empty');\n material = (await jose.importPKCS8(pem, alg)) as KeyObject | CryptoKey;\n } else if (key && typeof key === 'object') {\n material = key;\n } else {\n throw new Error('no key');\n }\n // A key that parses is not yet a key for this algorithm: prove it signs.\n await new jose.SignJWT({ probe: true }).setProtectedHeader({ alg }).sign(material);\n } catch {\n throw refuse();\n }\n return new CibaRequestSigner(alg, material, kid);\n }\n\n /** The algorithm this signer uses. */\n get alg(): CibaSigningAlg {\n return this.#alg;\n }\n\n /** The `kid` it puts in the header, if any. */\n get kid(): string | undefined {\n return this.#kid;\n }\n\n /** @internal — sign `claims` as a compact JWS under this signer's algorithm. */\n async sign(claims: Record<string, unknown>): Promise<Sensitive<string>> {\n const jose = await import('jose');\n const header: { alg: string; kid?: string } = { alg: this.#alg };\n if (this.#kid !== undefined) header.kid = this.#kid;\n return new Sensitive(await new jose.SignJWT(claims).setProtectedHeader(header).sign(this.#key.expose()));\n }\n\n /** `CibaRequestSigner(<alg>)` — never the key. */\n toString(): string {\n return `CibaRequestSigner(${this.#alg})`;\n }\n\n /** `{ alg, kid }` — never the key. */\n toJSON(): CibaSignerDescription {\n return { alg: this.#alg, ...(this.#kid !== undefined ? { kid: this.#kid } : {}) };\n }\n\n /** The same as {@link toJSON}, for `console.log` / `util.inspect`. */\n [NODE_INSPECT_CUSTOM](): string {\n return `CibaRequestSigner ${JSON.stringify(this.toJSON())}`;\n }\n}\n\n/** The plain form's authentication-request members, exactly those set (§33.2). */\nfunction cibaMembers(params: CibaInitiateParams): Array<[string, string]> {\n const out: Array<[string, string]> = [['scope', params.scope]];\n if (params.loginHint !== undefined) out.push(['login_hint', params.loginHint]);\n if (params.idTokenHint !== undefined) out.push(['id_token_hint', params.idTokenHint]);\n if (params.bindingMessage !== undefined) out.push(['binding_message', params.bindingMessage]);\n if (params.requestedExpiry !== undefined) out.push(['requested_expiry', String(params.requestedExpiry)]);\n if (params.acrValues !== undefined) out.push(['acr_values', params.acrValues]);\n if (params.resource !== undefined) out.push(['resource', params.resource]);\n if (params.delivery?.mode === 'ping') {\n out.push(['client_notification_token', params.delivery.clientNotificationToken.expose()]);\n }\n return out;\n}\n\n/** Parse a response body axios left as text; `undefined` when it is not JSON. */\nfunction jsonBody(data: unknown): unknown {\n if (typeof data !== 'string') return data;\n try {\n return JSON.parse(data);\n } catch {\n return undefined;\n }\n}\n\n/** Map a non-2xx `/oauth2/*` answer: `error` at any status is an `OAuthProtocolError` (§33.4); otherwise §2. */\nfunction cibaError(operation: string, response: AxiosResponse): AxiamError {\n if (response.status >= 300 && response.status < 400) return redirectRefused(operation, response.status);\n return (\n oauth2ErrorFromBody(jsonBody(response.data), response.status === 429 ? retryAfterMs(response) : undefined) ??\n mapHttpStatusToError(response.status, `${operation}: HTTP ${response.status}`)\n );\n}\n\n/** The `Authorization` header values of a ping, in any accepted header shape. */\nfunction authorizationValues(headers: CibaPingHeaders): string[] {\n const out: string[] = [];\n const isAuth = (name: unknown): boolean => typeof name === 'string' && name.toLowerCase() === 'authorization';\n if (Array.isArray(headers) && headers.every((h) => typeof h === 'string')) {\n // Node's rawHeaders: [name, value, name, value, …].\n const flat = headers as readonly string[];\n for (let i = 0; i + 1 < flat.length; i += 2) if (isAuth(flat[i])) out.push(flat[i + 1]!);\n return out;\n }\n if (headers !== null && typeof headers === 'object' && Symbol.iterator in headers) {\n for (const entry of headers as Iterable<readonly [string, string]>) {\n if (Array.isArray(entry) && isAuth(entry[0])) out.push(String(entry[1]));\n }\n return out;\n }\n for (const [name, value] of Object.entries(headers as Record<string, string | readonly string[] | undefined>)) {\n if (!isAuth(name) || value === undefined) continue;\n if (Array.isArray(value)) out.push(...(value as readonly string[]).map(String));\n else out.push(String(value));\n }\n return out;\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 /**\n * In-flight `oidcRefresh` calls, one per refresh token (§9 rule 2: a burst is the callers of ONE\n * token). Keyed by {@link refreshFlightKey}, a SHA-256 digest, never the raw token. A key's slot is\n * removed once its flight has settled.\n */\n readonly #pendingRefresh = new Map<string, Promise<OidcTokenSet>>();\n\n /** @internal Test hook: the number of occupied single-flight slots. */\n _pendingRefreshSlots(): number {\n return this.#pendingRefresh.size;\n }\n\n constructor(session: SharedSession, options: OidcClientOptions) {\n // A non-finite skew is a configuration fault: refuse it here, where the\n // error names the option, rather than at the first token it would have\n // let through unexpired (see `resolveClockSkewSec`).\n if (options.clockSkewSec !== undefined) {\n resolveClockSkewSec(options.clockSkewSec);\n }\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 and, when\n * `idpHint` is set, the one `axiam_idp_hint` (contract 1.65).\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 * @throws ValidationError when `idpHint` is empty or over 256 UTF-8 bytes;\n * no URL is built.\n */\n oidcBegin(params: OidcBeginParams): AuthorizationRequest {\n if (params.idpHint !== undefined) checkIdpHint('oidcBegin', params.idpHint);\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 // §12.1 \"`idp_hint`\" rule 3: the input is the single source. A same-named\n // extra is dropped when it is set, and passes through (once) when it is not.\n if (key === IDP_HINT_PARAM && params.idpHint !== undefined) continue;\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 if (params.idpHint !== undefined) query.set(IDP_HINT_PARAM, params.idpHint);\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}, single-flight per refresh token (§9).\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), and they do not share a lock: the single-flight here is keyed per\n * refresh token, so refreshes of different tokens run concurrently.\n *\n * Concurrent `oidcRefresh` calls presenting the SAME refresh token (and\n * tenant) collapse into one HTTP request and all receive the same token set\n * — §9 rule 2's result sharing. A different token gets its own request and\n * its own result.\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 // Only a caller presenting the SAME refresh token (and tenant) joins; a different token gets its\n // own wire call and its own result (§9 rules 2 and 6d).\n // The tenant is the RESOLVED one (§12.3 rule 4: the explicit argument, else the client default), so\n // an explicit tenant equal to the default and an omitted one share a flight: a second wire call\n // with the same rotating token would be a replay. A tenant that cannot be resolved rejects as before.\n // Resolved and canonicalised (lower-case) ONCE; that one value keys the flight AND goes on the wire,\n // so a change of the client's defaults in between cannot give the key one tenant and the request another.\n let tenantId: string;\n let key: string;\n try {\n tenantId = this.#resolveTenantId(params.tenantId).toLowerCase();\n key = refreshFlightKey(params.refreshToken, tenantId);\n } catch (err) {\n return Promise.reject(err);\n }\n const existing = this.#pendingRefresh.get(key);\n if (existing) {\n return existing;\n }\n const pending = this.#refreshFlight({ ...params, tenantId });\n this.#pendingRefresh.set(key, pending); // published strictly before it can be vacated\n const clear = (): void => {\n // Identity-checked: never vacate a different, still-live flight's slot.\n if (this.#pendingRefresh.get(key) === pending) {\n this.#pendingRefresh.delete(key);\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 // §37 loginWithProviderIdToken\n // -------------------------------------------------------------------------\n\n /**\n * `POST /oauth2/token` with\n * `grant_type=urn:axiam:params:oauth:grant-type:provider-id-token`\n * (CONTRACT.md §37, contract 1.65) — sign a native-app user in with the ID\n * token a Google, Apple or Facebook Limited Login SDK produced.\n *\n * @param provider - The provider's UUID or its `provider_slug`, sent verbatim:\n * never trimmed, case-folded, resolved or looked up. A provider *kind* name\n * (`google`) is not accepted here unless the operator also chose it as the\n * slug (§37.2 rule 2).\n * @param idToken - The provider's ID token (a credential; wrapped or bare).\n * @param nonce - The **raw** nonce, byte for byte: the provider's SDK was\n * given `SHA-256(raw)` as hexadecimal (`nativeNonce()` produces the\n * pair). Never hashed, replaced or generated here (§37.2 rule 3).\n * @param options - `scopes`, `resource`, `tenantId`, `configuration`.\n *\n * @remarks\n * **Never retried** — not on a status, a `429` or a transport failure: the\n * provider's token is single-use across the deployment (§37.2 rule 10). An\n * `invalid_grant` is the server's one generic answer to every refusal of the\n * token and is neither retried nor refined; the recovery is a **fresh**\n * provider token with a **fresh** nonce. A transport failure after the\n * request left is indeterminate and surfaces as `NetworkError`.\n *\n * No `openid` or other scope is added: omit `scopes` and the response carries\n * no `id_token`. This is not token exchange (§15) and never falls back to it\n * or to a browser flow. A public client sends `client_id` alone; a client\n * configured with a `clientSecret` sends it in the body.\n *\n * The result is the ordinary {@link OidcTokenSet}; an `id_token`, when\n * present, is validated under §12.4 with the raw `nonce` as the expected\n * nonce. As with `deviceLogin`, the token set is **returned and not\n * adopted** as this client's credential (§37.2 rule 9).\n *\n * Neither the ID token nor the raw nonce is logged, put in an error, or kept\n * after the call returns; hold the raw nonce only for the length of the\n * attempt.\n *\n * @throws ValidationError (local, no request) for an empty `provider`,\n * `idToken` or `nonce`.\n * @throws AuthError (local, no request) for a slug-only client (§12.3 rule 4).\n * @throws OAuthProtocolError for a body carrying `error`, at any status.\n * @throws NetworkError for a transport failure or a body-less `5xx`.\n *\n * @example\n * ```ts\n * const { raw, hashed } = nativeNonce();\n * const idToken = await providerSdk.signIn({ nonce: hashed });\n * const tokens = await oidc.loginWithProviderIdToken('corp-google', idToken, raw, {\n * scopes: ['openid', 'profile'],\n * });\n * ```\n */\n async loginWithProviderIdToken(\n provider: string,\n idToken: Sensitive<string> | string,\n nonce: Sensitive<string> | string,\n options: LoginWithProviderIdTokenOptions = {},\n ): Promise<OidcTokenSet> {\n const operation = 'loginWithProviderIdToken';\n const refuse = (field: string): ValidationError =>\n new ValidationError(operation, 400, `${operation}: ${field} must not be empty (CONTRACT.md §37.2 rule 4)`, [\n { field, message: 'must not be empty' },\n ]);\n const idTokenValue = typeof idToken === 'string' ? idToken : idToken.expose();\n const nonceValue = typeof nonce === 'string' ? nonce : nonce.expose();\n if (provider === '') throw refuse('provider');\n if (idTokenValue === '') throw refuse('idToken');\n if (nonceValue === '') throw refuse('nonce');\n // §37.1: a slug-only client is refused before any wire call — discovery included.\n this.#resolveTenantId(options.tenantId);\n\n const configuration = options.configuration ?? (await this.oidcDiscover());\n const form = new URLSearchParams();\n form.set('grant_type', PROVIDER_ID_TOKEN_GRANT_TYPE);\n form.set('client_id', this.#options.clientId);\n form.set('provider', provider);\n form.set('id_token', idTokenValue);\n form.set('nonce', nonceValue);\n // §37.2 rule 7: only what the caller named — no `openid`, never an empty `scope=`.\n if (options.scopes !== undefined && options.scopes.length > 0) {\n form.set('scope', options.scopes.join(' '));\n }\n if (options.resource !== undefined) {\n form.set('resource', options.resource);\n }\n this.#appendClientSecret(form);\n\n const url = this.#endpointUrl(this.#requiredEndpoint(configuration, 'token_endpoint'), options.tenantId);\n // One request, every status resolved so the `error` member decides (§37.3), and a\n // transport failure carrying no axios cause (its `config` holds this form).\n const response = await this.#postCibaForm(url, form, operation);\n if (response.status < 200 || response.status >= 300) {\n throw cibaError(operation, response);\n }\n // §12.4 with the RAW nonce (§37.2 rule 8): AXIAM's ID token carries it as sent.\n return this.#toTokenSet(response.data as TokenResponseWire, configuration, nonceValue);\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(this.#requiredEndpoint(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(this.#requiredEndpoint(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 this.#forgetPreviousPrincipal();\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 // 10. ssoProviders (contract 1.38)\n // -------------------------------------------------------------------------\n\n /**\n * `GET /api/v1/auth/federation/providers` (§12.1) — which \"Sign in with X\"\n * buttons to render for a workspace.\n *\n * @remarks\n * The identifiers travel as **query** parameters; this is a `GET` and sends\n * no body. The neighbouring start operations take the same four in a JSON\n * body, and the two are one copy-paste apart, which is why there is a test\n * asserting the location.\n *\n * **An empty list is a success.** An unknown organization, a known one with\n * nothing configured, and a request naming no workspace at all all answer\n * `200` with an empty `providers` array (§12.1 note 9). This method returns\n * every one of them as an ordinary result and synthesises no not-found: the\n * endpoint is deliberately shaped so it cannot be used to enumerate\n * organization or tenant slugs, and an SDK that reintroduced the\n * distinction would reintroduce the oracle. A caller learns it named the\n * workspace wrongly at the start operations, where every failure is a\n * uniform `401`.\n *\n * For the same reason this does **not** refuse client-side when no\n * organization resolves, unlike {@link ssoStart} and\n * {@link ssoStartOauth2}, which do.\n */\n async ssoProviders(params: SsoProvidersParams = {}): Promise<FederationProviderList> {\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 const query = new URLSearchParams();\n if (orgId) {\n query.set('org_id', orgId);\n } else if (orgSlug) {\n query.set('org_slug', orgSlug);\n }\n if (tenantId) {\n query.set('tenant_id', tenantId);\n } else if (tenantSlug) {\n query.set('tenant_slug', tenantSlug);\n }\n\n const search = query.toString();\n const url = search ? `${SSO_PROVIDERS_PATH}?${search}` : SSO_PROVIDERS_PATH;\n let response: AxiosResponse<PublicFederationProvidersResponseWire>;\n try {\n response = await this.#session.axios.get<PublicFederationProvidersResponseWire>(url);\n } catch (err) {\n throw mapOidcError(err, url, 'ssoProviders request failed');\n }\n\n return {\n providers: (response.data.providers ?? []).map(\n (wire): FederationProvider => ({\n id: wire.id,\n providerKind: wire.provider_kind,\n displayName: wire.display_name,\n protocol: wire.protocol,\n hasBundledMark: wire.has_bundled_mark,\n inherited: wire.inherited,\n ...(wire.button_icon ? { buttonIcon: wire.button_icon } : {}),\n }),\n ),\n };\n }\n\n // -------------------------------------------------------------------------\n // 11. ssoStartOauth2 (contract 1.38)\n // -------------------------------------------------------------------------\n\n /**\n * `POST /api/v1/auth/federation/oauth2/start` (§12.1) — step 1 of a login\n * through a **plain-OAuth2** upstream (GitHub, Facebook, `generic_oauth2`).\n *\n * @remarks\n * Call this, rather than {@link ssoStart}, exactly when the provider's\n * `protocol` is `OAuth2` (§12.1 note 10). The server refuses a mismatch\n * with `400` rather than accepting it silently, so a client that assumes\n * OIDC fails on every GitHub button.\n *\n * PKCE is mandatory on this path — it is the only replay protection left\n * once there is no `nonce` — and is generated and stored **server-side**.\n * Nothing about it appears in this request or its response (§12.1 note 11),\n * and this method computes no verifier.\n *\n * @throws AuthError client-side, without a wire call, when tenant or org\n * context cannot be resolved. On the wire, a **`400`** can mean the\n * `redirectUri` is not on an origin the deployment accepts (§12.1 rule\n * 12a) and surfaces as `NetworkError` — §2's `400` row, this taxonomy's\n * configuration/programming-error member, as distinct from the\n * `AuthError` a `401` gets. It is not retried; the same origin will be\n * refused again.\n */\n async ssoStartOauth2(params: SsoStartOauth2Params): 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 'ssoStartOauth2 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 'ssoStartOauth2 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 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<OAuth2StartResponseWire>(\n SSO_OAUTH2_START_PATH,\n body,\n 'ssoStartOauth2 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 // 12. ssoCompleteOauth2 (contract 1.38)\n // -------------------------------------------------------------------------\n\n /**\n * `POST /api/v1/auth/federation/oauth2/callback` (§12.1) — step 2 of a\n * plain-OAuth2 login.\n *\n * @remarks\n * The session arrives as **`Set-Cookie`** (§12.1 note 6), so this call must\n * go through the §4 cookie jar exactly as {@link ssoComplete} must.\n *\n * §12.4 does not apply: an `OAuth2` provider issues no ID token, so there\n * is nothing to validate. The server authenticated the user by calling a\n * configured userinfo endpoint with the access token it had just received —\n * configuration and transport trust rather than cryptographic trust (§12.1\n * note 11).\n */\n async ssoCompleteOauth2(params: SsoCompleteOauth2Params): Promise<SsoCompleteResult> {\n return this.#completeFederationSession(\n SSO_OAUTH2_CALLBACK_PATH,\n { state: params.state, code: params.code },\n 'ssoCompleteOauth2 request failed',\n );\n }\n\n // -------------------------------------------------------------------------\n // 13. ssoCompleteHandoff (contract 1.38)\n // -------------------------------------------------------------------------\n\n /**\n * `POST /api/v1/auth/federation/handoff` (§12.1) — redeem the single-use\n * code the SAML and Apple flows deliver.\n *\n * @remarks\n * Those two protocols return **cross-site**, so the server cannot set\n * `SameSite=Strict` session cookies on that response. It instead redirects\n * the browser to the SPA's callback URL with an `axiam_handoff` query\n * parameter ({@link HANDOFF_QUERY_PARAM}); this call posts that code back\n * same-origin, and *this* response is the one carrying the cookies (§12.1\n * note 12).\n *\n * **The code is gone either way.** It is valid for\n * {@link HANDOFF_CODE_TTL_SECS} seconds and redeemable **once**. Redeem it\n * from the same origin, immediately, and never retry a failed redemption: a\n * `401` is terminal, and this method makes exactly one wire call so that it\n * cannot become a retry by accident. Unknown, expired and already-redeemed\n * all answer the same `401`, deliberately — telling them apart is not\n * something a caller gets to do.\n */\n async ssoCompleteHandoff(params: SsoCompleteHandoffParams): Promise<SsoCompleteResult> {\n return this.#completeFederationSession(\n SSO_HANDOFF_PATH,\n { code: params.code },\n 'ssoCompleteHandoff request failed',\n );\n }\n\n // -------------------------------------------------------------------------\n // §14 Device Authorization Grant (RFC 8628)\n // -------------------------------------------------------------------------\n\n /**\n * `POST /oauth2/device_authorization` (CONTRACT.md §14.1) — start the grant\n * and obtain the code pair.\n *\n * @remarks\n * **The client authenticates as it does at every other token request\n * (contract 1.62, §14.1 rule 2).** A client built with a `clientSecret` sends\n * it as `client_secret` in the **form body** — never as `Authorization:\n * Basic`, whatever the client is registered for (§12.1 rule 3 stands for\n * this route, and the maintainer's 2026-10-16 \"same rules\" reading fixes the\n * form body) — and a client with a §6.1 client certificate presents it on the\n * connection, through the `mtls_endpoint_aliases` entry when discovery\n * publishes one (§21.3). **A public client sends no credential at all** and\n * is never refused client-side, so a device that cannot hold a secret still\n * works. The SDK sends a credential only when its caller configured one: it\n * never borrows one from another configuration. `private_key_jwt` client\n * authentication is not implemented by this SDK.\n *\n * A `401` with `{\"error\":\"invalid_client\"}` is an {@link OAuthProtocolError}\n * (§14.2 rule 5), is made once, and does not enter the §9 refresh guard.\n */\n async deviceAuthorize(params: DeviceAuthorizeParams = {}): Promise<DeviceAuthorization> {\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const endpoint = this.#optionalEndpoint(configuration, 'device_authorization_endpoint');\n if (!endpoint) {\n throw new AuthError(\n \"the authorization server's discovery document advertises no \" +\n 'device_authorization_endpoint: this server does not support the device grant ' +\n '(CONTRACT.md §14.1)',\n );\n }\n\n const form = new URLSearchParams();\n form.set('client_id', this.#options.clientId);\n // §14.1 rule 2: a configured secret rides in the form body; a public\n // client's form carries none.\n this.#appendClientSecret(form);\n if (params.scope !== undefined) {\n form.set('scope', Array.isArray(params.scope) ? params.scope.join(' ') : params.scope);\n }\n\n const url = this.#endpointUrl(endpoint, params.tenantId);\n const { data } = await this.#postForm<DeviceAuthorizationResponseWire>(\n url,\n form,\n 'device authorization request failed',\n );\n\n return {\n deviceCode: new Sensitive(data.device_code),\n userCode: data.user_code,\n verificationUri: data.verification_uri,\n ...(data.verification_uri_complete != null\n ? { verificationUriComplete: data.verification_uri_complete }\n : {}),\n expiresIn: data.expires_in,\n // §14.2 rule 2: the interval comes from the response; only its absence\n // falls back to the RFC default. A server-sent 0 is treated as absent —\n // polling with no delay is never what the server meant.\n interval: data.interval != null && data.interval > 0 ? data.interval : DEFAULT_POLL_INTERVAL_SECS,\n };\n }\n\n // -------------------------------------------------------------------------\n // §26 Pushed Authorization Requests (RFC 9126)\n // -------------------------------------------------------------------------\n\n /**\n * `POST /oauth2/par` (CONTRACT.md §26.1) — push the authorization request\n * over the back channel and get an opaque handle to redirect with.\n *\n * @remarks\n * PAR moves the authorization request off the browser. Instead of putting\n * `scope`, `redirect_uri`, `state` and the PKCE challenge into a URL the user\n * agent carries, the client POSTs them straight to AXIAM over an\n * authenticated channel and puts an opaque `request_uri` in the redirect.\n * What travels through the browser is then a random string that cannot be\n * edited into meaning something else.\n *\n * **Required for a FAPI 2.0 client** — `profile: \"fapi2\"` refuses a\n * registration that does not set `require_par`, so such a client cannot\n * authorize any other way (§21.1).\n *\n * This is a §12 extension, not a replacement: `oidcExchange` afterwards is\n * unchanged, and carries the same `codeVerifier` and `redirectUri`\n * ({@link PushedAuthorizationRequest.codeVerifier} is the one `oidcBegin`\n * produced — §26.2 rule 6).\n *\n * @example\n * ```ts\n * const configuration = await oidc.oidcDiscover();\n * const begun = oidc.oidcBegin({ configuration, redirectUri, scope: 'openid profile' });\n * const pushed = await oidc.oidcPar({ request: begun, redirectUri, scope: 'openid profile' });\n *\n * redirect(pushed.authorizationUrl); // client_id + request_uri, nothing else\n * // …later, on the callback:\n * const tokens = await oidc.oidcExchange({\n * code, redirectUri, nonce: pushed.nonce, codeVerifier: pushed.codeVerifier,\n * });\n * ```\n */\n async oidcPar(params: OidcParParams): Promise<PushedAuthorizationRequest> {\n if (params.idpHint !== undefined) checkIdpHint('oidcPar', params.idpHint);\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const endpoint = this.#optionalEndpoint(configuration, 'pushed_authorization_request_endpoint');\n if (!endpoint) {\n throw new AuthError(\n \"the authorization server's discovery document advertises no \" +\n 'pushed_authorization_request_endpoint: this server does not support RFC 9126 ' +\n '(CONTRACT.md §26.1)',\n );\n }\n\n // §26.2 rule 1: everything below was computed by `oidcBegin`. There is no\n // second generator here, and there must not be — two sources for `state`\n // or the PKCE pair are two things that can disagree.\n const request = params.request;\n const form = new URLSearchParams();\n form.set('client_id', this.#options.clientId);\n form.set('response_type', 'code');\n form.set('redirect_uri', params.redirectUri);\n form.set('scope', normalizeScope(params.scope));\n form.set('state', request.state);\n form.set('nonce', request.nonce);\n form.set('code_challenge', computeCodeChallenge(exposeSecret(request.codeVerifier)));\n form.set('code_challenge_method', CODE_CHALLENGE_METHOD_S256);\n // RFC 9449 §10.1 — bind the authorization code to the client's DPoP key at\n // authorization time rather than only at the token request, so a stolen\n // code cannot be redeemed with a different key. Caller-supplied: this SDK\n // verifies proofs (§21.7.2) but generates none, so it holds no key whose\n // thumbprint it could compute. Emitted only when set — §12.1 forbids\n // sending an empty value for an absent optional field.\n if (params.dpopJkt !== undefined) {\n form.set('dpop_jkt', params.dpopJkt);\n }\n // §26.2 rule 8 (contract 1.65): the provider hint rides the pushed body, once,\n // and only when set. It is never added to the redirect URL built below.\n // D-N36 (C165-11): when the argument is unset, the hint the begin URL carries is pushed;\n // the argument wins when both are set. Never twice, never a second source.\n const pushedHint = params.idpHint ?? beginUrlIdpHint(request.url);\n if (pushedHint !== undefined) {\n checkIdpHint('oidcPar', pushedHint);\n form.set(IDP_HINT_PARAM, pushedHint);\n }\n // NOT pushed, and never to be added: `request_uri`. RFC 9126 §2.1 makes it\n // the one authorization parameter a client MUST NOT push, and openapi.json\n // models it on the request schema only so the server can refuse it. A\n // client able to send it is a client able to chain one pushed request into\n // another, which is the attack the refusal exists to stop.\n this.#appendClientSecret(form);\n\n const url = this.#endpointUrl(endpoint, params.tenantId);\n // Deliberately NOT routed through the §16 retry helper: this is a POST that\n // creates server state, so it falls outside §16.2's read-only eligibility\n // exactly as `oidcExchange` does. The safe recovery from a transport\n // failure is a fresh push, which costs one round trip and cannot\n // double-consume anything (§26.2 rule 4).\n const { data } = await this.#postForm<PushedAuthorizationResponseWire>(\n url,\n form,\n 'pushed authorization request failed',\n );\n\n // §26.2 rule 2: exactly two query parameters. Not `response_type`, not\n // `redirect_uri`, not `scope`, not `state`, not the PKCE pair — the server\n // REFUSES a request carrying both a `request_uri` and any inline\n // authorization parameter rather than merging them, because merging is\n // where parameter confusion lives: an attacker supplies the inline value\n // they want and lets the pushed copy satisfy whichever check reads the\n // other one. Re-adding them \"for compatibility\" restores the attack.\n const target = new URL(configuration.authorization_endpoint);\n const query = new URLSearchParams();\n query.set('client_id', this.#options.clientId);\n query.set('request_uri', data.request_uri);\n target.search = query.toString().replace(/\\+/g, '%20');\n\n return {\n authorizationUrl: target.toString(),\n requestUri: new Sensitive(data.request_uri),\n expiresIn: data.expires_in,\n state: request.state,\n nonce: request.nonce,\n codeVerifier: request.codeVerifier,\n };\n }\n\n /**\n * `POST /oauth2/token` with the device-code grant (CONTRACT.md §14.1) —\n * **one** poll attempt.\n *\n * @remarks\n * The raw single call, so an application driving its own loop (a UI\n * rendering a countdown, say) can. The five RFC 8628 §3.5 answers surface as\n * {@link OAuthProtocolError} — `authorization_pending` and `slow_down`\n * included — so a hand-rolled loop dispatches on the same answers\n * {@link deviceLogin} does. Most callers want {@link deviceLogin}.\n *\n * Client authentication is the one {@link deviceAuthorize} describes\n * (contract 1.62, §14.1 rule 2): a configured `clientSecret` is sent as\n * `client_secret` in the form body, never as `Authorization: Basic`; a public\n * client sends none; `client_id` is sent on **every** poll (§14.1 rule 3). A\n * `401 invalid_client` surfaces as {@link OAuthProtocolError}, is not retried\n * and does not enter the §9 refresh guard (§14.2 rule 5). Any `429`\n * is an {@link OAuthProtocolError} with `error == 'rate_limit_exceeded'` too\n * (rule 9, whatever its body names) — never `slow_down`; {@link deviceLogin}\n * waits it out. Its `Retry-After` is not exposed, so a hand-rolled loop\n * should wait at least one interval on it without raising the interval, or\n * use {@link deviceLogin}. This SDK ships no\n * DPoP proof generator, so it cannot drive a client registered for DPoP; it\n * surfaces that client's refusal as the same `invalid_client`.\n */\n async devicePoll(params: DevicePollParams): Promise<OidcTokenSet> {\n return this.#devicePoll(params, undefined);\n }\n\n /** {@link devicePoll}; `bound` is the loop's deadline, which a §16 retry inside the poll must not pass. */\n async #devicePoll(params: DevicePollParams, bound: PollDeadline | undefined): Promise<OidcTokenSet> {\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const form = new URLSearchParams();\n form.set('grant_type', DEVICE_CODE_GRANT_TYPE);\n form.set('device_code', exposeSecret(params.deviceCode));\n form.set('client_id', this.#options.clientId);\n // §14.1 rule 2, as at deviceAuthorize and every other token request.\n this.#appendClientSecret(form);\n\n const url = this.#endpointUrl(this.#requiredEndpoint(configuration, 'token_endpoint'), params.tenantId);\n const wire = await this.#postDevicePoll(url, form, bound);\n // No nonce: the device grant has no authorization request to carry one,\n // and §12.4 rule 6 applies to the authorization-code flow.\n return this.#toTokenSet(wire, configuration, undefined);\n }\n\n /**\n * The composed §14.3 helper: start the grant, hand the caller the user code,\n * poll to completion.\n *\n * @remarks\n * `onUserCode` is awaited **before the first poll** — §14.3 rule 2 requires\n * the caller to have had the chance to display the code before polling\n * begins. The SDK never prints it.\n *\n * Per §14.3 rule 4 (contract 1.7 errata) this SDK **returns** the token set;\n * whether it is adopted is the same MAY as `loginClientCredentials`.\n *\n * Polling follows §14.2: the interval comes from the response; `slow_down`\n * adds 5 s **permanently**; `authorization_pending` loops; `access_denied`\n * and `expired_token` raise distinct errors; polling stops at `expires_in`\n * even if the server has not yet said `expired_token`. A 5xx or transport\n * failure mid-poll is **not** terminal (rule 6) — the loop absorbs it and\n * tries again, bounded by the same deadline, because a server restart must\n * not lose a grant the user has already approved: that bound holds for the\n * §16 retry inside a poll too, whose waits are served on the loop's clock and\n * never reach the deadline (`Retry-After` included; the typed `expired_token`\n * is raised at once, C164-36). A `429\n * rate_limit_exceeded` (rule 9, contract 1.64) is not terminal either: the\n * loop waits `Retry-After` as a minimum (capped at the `expires_in`\n * deadline), counts the wait as one interval, does **not** raise the\n * interval, and polls again.\n */\n async deviceLogin(params: DeviceLoginParams): Promise<OidcTokenSet> {\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const clock = params.clock ?? SYSTEM_CIBA_CLOCK;\n const authorization = await this.deviceAuthorize({\n ...(params.scope !== undefined ? { scope: params.scope } : {}),\n ...(params.tenantId !== undefined ? { tenantId: params.tenantId } : {}),\n configuration,\n });\n // §14.2 rule 4 (C164-05): the deadline is a point on the clock, taken when the\n // authorization arrives, so the time `onUserCode` and every poll take count\n // against it and not only the sleeps do.\n const deadline = clock.now() + authorization.expiresIn * 1000;\n\n // §14.3 rule 2 — before any polling.\n await params.onUserCode(authorization);\n\n const schedule = new PollSchedule(authorization.interval, authorization.expiresIn);\n\n for (;;) {\n // Read before `tick()`, which serves a pending `Retry-After`.\n const waitSecs = schedule.waitSecs;\n // §14.2 rule 4: the deadline is authoritative. Checking before sleeping\n // keeps the SDK from issuing a request that can only be refused, and\n // reports it under the same `expired_token` code the server would have\n // used — so a caller's branch does not care which side noticed first.\n if (!schedule.tick() || clock.now() + waitSecs * 1000 >= deadline) {\n throw new OAuthProtocolError(\n 'expired_token',\n 'the device authorization expired before the user completed it ' +\n '(client-side deadline from expires_in; CONTRACT.md §14.2 rule 4)',\n );\n }\n\n await clock.sleep(waitSecs * 1000);\n\n try {\n return await this.#devicePoll(\n {\n deviceCode: authorization.deviceCode,\n ...(params.tenantId !== undefined ? { tenantId: params.tenantId } : {}),\n configuration,\n },\n { deadline, clock },\n );\n } catch (err) {\n if (err instanceof OAuthProtocolError) {\n if (err.error === 'authorization_pending') {\n continue;\n }\n if (err.error === 'slow_down') {\n // Only the `400` gets here: a `429` is `rate_limit_exceeded` below,\n // whatever its body names (§14.2 rule 9, amended).\n schedule.slowDown(); // §14.2 rule 1: cumulative, never reset.\n continue;\n }\n if (err.error === 'rate_limit_exceeded') {\n // §14.2 rule 9 (contract 1.64): wait `Retry-After` as a minimum,\n // count it as one interval, leave the interval alone, poll again.\n const pollWaitMs = POLL_RETRY_AFTER_MS.get(err);\n schedule.rateLimited(pollWaitMs === undefined ? undefined : pollWaitMs / 1000);\n continue;\n }\n throw err; // expired_token / access_denied / invalid_grant\n }\n // §14.2 rule 6: transport and 5xx failures are not among the five\n // protocol answers and are not terminal — a 5xx whatever its body\n // (contract 1.64, amended): `500 {\"error\":\"server_error\"}` maps to\n // `NetworkError` by status, before the body is read.\n if (err instanceof NetworkError) {\n continue;\n }\n throw err;\n }\n }\n }\n\n // -------------------------------------------------------------------------\n // §15 Token Exchange (RFC 8693)\n // -------------------------------------------------------------------------\n\n /**\n * `POST /oauth2/token` with the RFC 8693 grant (CONTRACT.md §15.1) —\n * exchange a token for a **narrower** one.\n *\n * @remarks\n * The exchanging client authenticates (`client_secret_post`): unlike §14's\n * device, this is a confidential service.\n *\n * What this method deliberately does **not** do:\n *\n * - **No default `actorToken`** (§15.2 rule 1). Passing none asks for\n * *impersonation*; the SDK will not quietly reuse the client's own session\n * token as the actor and turn that into a delegation.\n * - **No substitute for an actor token that was refused** (§15.2 rule 9). The\n * actor token must have been issued to this client — the usual one is its\n * own `client_credentials` token, `loginClientCredentials()`, which the\n * caller obtains and passes. Any other is answered `400 invalid_request`\n * (`actor_token was not issued to the exchanging client`), surfaced\n * unchanged: not retried, not dropped, not replaced.\n * - **No retry or downgrade on `unauthorized_client`** (rule 2) — a\n * registration fact an operator must fix.\n * - **No auto-narrowing on `invalid_scope`** (rule 3). The server refuses\n * instead of silently narrowing precisely so the caller finds out here.\n * - **No adoption** (rule 5). The returned token is handed onward in one\n * outbound call; adopting it would silently re-privilege every subsequent\n * call this client makes.\n *\n * A cross-tenant subject token answers `invalid_grant`, identically to an\n * expired one. The SDK does not try to tell them apart (§15.3): the server\n * collapses them because distinguishing them is a tenant-enumeration signal.\n *\n * @throws AuthError when no `clientSecret` is configured — client-side, with\n * no wire call.\n */\n async tokenExchange(params: TokenExchangeParams): Promise<ExchangedToken> {\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const form = new URLSearchParams();\n form.set('grant_type', TOKEN_EXCHANGE_GRANT_TYPE);\n form.set('subject_token', exposeSecret(params.subjectToken));\n // Whatever the caller named, verbatim. The subject token is NEVER decoded\n // to pick this (§15.7): which kind of token the caller holds is the\n // caller's to know, and a guess here is the difference between a request\n // that is refused and one that is silently reinterpreted.\n form.set('subject_token_type', params.subjectTokenType);\n if (params.actorToken !== undefined) {\n form.set('actor_token', exposeSecret(params.actorToken));\n // Sent exactly when `actor_token` is: RFC 8693 §2.1 requires the pair,\n // and the type alone is a malformed request.\n form.set('actor_token_type', ACCESS_TOKEN_TYPE);\n }\n if (params.scopes !== undefined) {\n form.set('scope', params.scopes.join(' '));\n }\n if (params.audience !== undefined) {\n form.set('audience', params.audience);\n }\n if (params.resource !== undefined) {\n form.set('resource', params.resource);\n }\n form.set('client_id', this.#options.clientId);\n form.set('client_secret', this.#requireClientSecret('tokenExchange'));\n\n const url = this.#endpointUrl(this.#requiredEndpoint(configuration, 'token_endpoint'), params.tenantId);\n const { data } = await this.#postForm<TokenExchangeResponseWire>(\n url,\n form,\n 'token exchange request failed',\n );\n\n return {\n accessToken: new Sensitive(data.access_token),\n issuedTokenType: data.issued_token_type,\n tokenType: data.token_type,\n expiresIn: data.expires_in,\n ...(data.scope != null ? { scope: data.scope } : {}),\n };\n }\n\n // -------------------------------------------------------------------------\n // §20 UMA 2.0 — Protection API and ticket grant\n // -------------------------------------------------------------------------\n\n /**\n * `POST /uma2/rreg/resource_set` — register a resource set (CONTRACT.md §20.1).\n *\n * @remarks\n * The `pat` is an explicit parameter, not this client's session. A Protection\n * API Token must be a **client-credentials** token, because a ticket binds to\n * the `client_id` that minted it — and this client's session is usually a\n * *user* session, which names no client to bind to (§20.2 rule 1).\n */\n async umaRegisterResource(\n pat: Sensitive<string> | string,\n resource: ResourceSet,\n ): Promise<ResourceSet> {\n const wire = await this.#umaProtection<ResourceSetWire>(\n 'post',\n '/uma2/rreg/resource_set',\n pat,\n toResourceSetWire(resource),\n );\n return fromResourceSetWire(wire);\n }\n\n /** `GET /uma2/rreg/resource_set/{id}` — read a resource set (§20.1). */\n async umaReadResource(pat: Sensitive<string> | string, id: string): Promise<ResourceSet> {\n const wire = await this.#umaProtection<ResourceSetWire>(\n 'get',\n `/uma2/rreg/resource_set/${encodeURIComponent(id)}`,\n pat,\n );\n return fromResourceSetWire(wire);\n }\n\n /**\n * `PUT /uma2/rreg/resource_set/{id}` — replace a resource set (§20.1).\n *\n * @remarks\n * **The scope list is replaced, not merged** (§20.2 rule 8). Whatever\n * `resource.resourceScopes` holds becomes the complete declared set; omitting\n * a scope removes it, which is how a resource server drops an authority. This\n * method performs no read-before-write.\n */\n async umaUpdateResource(\n pat: Sensitive<string> | string,\n id: string,\n resource: ResourceSet,\n ): Promise<ResourceSet> {\n const wire = await this.#umaProtection<ResourceSetWire>(\n 'put',\n `/uma2/rreg/resource_set/${encodeURIComponent(id)}`,\n pat,\n toResourceSetWire(resource),\n );\n return fromResourceSetWire(wire);\n }\n\n /** `DELETE /uma2/rreg/resource_set/{id}` — deregister (§20.1). */\n async umaDeleteResource(pat: Sensitive<string> | string, id: string): Promise<void> {\n await this.#umaProtection<void>(\n 'delete',\n `/uma2/rreg/resource_set/${encodeURIComponent(id)}`,\n pat,\n );\n }\n\n /**\n * `GET /uma2/rreg/resource_set` — list the ids **this client** registered\n * (§20.1).\n *\n * @remarks\n * Not the tenant's whole resource tree: a protection scope does not entitle a\n * caller to enumerate it.\n */\n async umaListResources(pat: Sensitive<string> | string): Promise<string[]> {\n return this.#umaProtection<string[]>('get', '/uma2/rreg/resource_set', pat);\n }\n\n /**\n * `POST /uma2/perm` — mint a permission ticket (§20.1).\n *\n * @remarks\n * Scope names are validated **here**, against each resource's declared set.\n * Asking for an undeclared scope is a `400`, not a denial — the two are\n * different failures, and this SDK surfaces the distinction the server draws\n * rather than flattening it.\n */\n async umaRequestTicket(\n pat: Sensitive<string> | string,\n permissions: RequestedPermission[],\n ): Promise<Sensitive<string>> {\n const wire = await this.#umaProtection<{ ticket: string }>(\n 'post',\n '/uma2/perm',\n pat,\n permissions.map((p) => ({\n resource_id: p.resourceId,\n resource_scopes: p.resourceScopes,\n })),\n );\n return new Sensitive(wire.ticket);\n }\n\n /**\n * `POST /oauth2/token` with the uma-ticket grant (§20.1) — exchange a ticket\n * for an RPT.\n *\n * @remarks\n * **This method never retries.** It issues exactly one request and is outside\n * the §16 retry policy — not on `5xx`, not on timeout, not on any transport\n * failure (§20.2 rule 6). The ticket is consumed *before* the request is\n * evaluated, so a failed exchange has already spent it: a retry cannot\n * succeed, and under concurrency it is precisely the concurrent redemption a\n * server whose storage engine this SDK cannot attest may admit twice\n * (ilpanich/axiam#302). On failure, request a **new** ticket.\n *\n * What it deliberately does not do:\n *\n * - **No default `claimToken`** (rule 2) — it is required. Defaulting it to\n * the resource server's own PAT would mint an RPT for the resource server\n * instead of for the user.\n * - **No auto-narrowing on `access_denied`** (rule 3). A partial grant is\n * refused whole; whether two-of-three permissions is useful is the\n * application's judgement, not this SDK's.\n * - **No adoption** (rule 4). The RPT is the *requesting party's* token.\n * Adopting it would re-privilege every later call this client makes as that\n * user.\n *\n * The four ticket refusals — unknown, expired, already used, wrong client —\n * all answer `invalid_grant` with one message. This SDK does not try to tell\n * them apart (§20.4): the server collapses them so a caller cannot probe for\n * live ticket handles.\n *\n * @throws AuthError when no `clientSecret` is configured — client-side, with\n * no wire call.\n */\n async umaExchangeTicket(params: UmaExchangeTicketParams): Promise<RequestingPartyToken> {\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const form = new URLSearchParams();\n form.set('grant_type', UMA_TICKET_GRANT_TYPE);\n form.set('ticket', exposeSecret(params.ticket));\n form.set('claim_token', exposeSecret(params.claimToken));\n form.set('claim_token_format', UMA_CLAIM_TOKEN_FORMAT);\n form.set('client_id', this.#options.clientId);\n form.set('client_secret', this.#requireClientSecret('umaExchangeTicket'));\n\n const url = this.#endpointUrl(this.#requiredEndpoint(configuration, 'token_endpoint'), params.tenantId);\n // One POST, no retry wrapper. See the rule-6 note above — this is the §16\n // exception, and it is load-bearing rather than stylistic.\n let data: RptResponseWire;\n try {\n const config: AxiosRequestConfig = {\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n maxRedirects: 0,\n };\n const response = await this.#session.axios.post<RptResponseWire>(\n url,\n form.toString(),\n config,\n );\n data = response.data;\n } catch (err) {\n throw mapUmaGrantError(err, url, 'uma ticket exchange request failed');\n }\n\n return {\n accessToken: new Sensitive(data.access_token),\n tokenType: data.token_type,\n expiresIn: data.expires_in,\n };\n }\n\n /** Shared PAT-authenticated Protection API request. */\n async #umaProtection<T>(\n method: 'get' | 'post' | 'put' | 'delete',\n path: string,\n pat: Sensitive<string> | string,\n body?: unknown,\n ): Promise<T> {\n const config: AxiosRequestConfig = {\n headers: { Authorization: `Bearer ${exposeSecret(pat)}` },\n };\n try {\n const response =\n method === 'get' || method === 'delete'\n ? await this.#session.axios[method]<T>(path, config)\n : await this.#session.axios[method]<T>(path, body, config);\n return response.data;\n } catch (err) {\n throw mapOidcError(err, path, 'UMA protection API request failed');\n }\n }\n\n // -------------------------------------------------------------------------\n // §12.7 Logout helpers\n // -------------------------------------------------------------------------\n\n /**\n * Build the RP-initiated logout URL to redirect the user agent to\n * (CONTRACT.md §12.7.2).\n *\n * @remarks\n * Performs **no network I/O** beyond the discovery fetch the SDK caches\n * anyway, and does **not** clear this client's own session: whether the\n * local session ends is the application's decision — a backend holding a\n * service-account session must not lose it because a *user* logged out.\n *\n * `end_session_endpoint` is read from discovery and never synthesised from\n * the issuer (rule 1). Code that concatenates works against AXIAM and breaks\n * against every other OP the same application is pointed at.\n *\n * `postLogoutRedirectUri` is passed through **unvalidated against any local\n * list** (rule 3): the allow-list lives in the client's server-side\n * registration, and a client-side copy would drift and reject a URI an\n * operator had just registered.\n */\n async logoutUrl(params: LogoutUrlParams): Promise<string> {\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const endpoint = configuration.end_session_endpoint;\n if (!endpoint) {\n throw new AuthError(\n \"the authorization server's discovery document advertises no \" +\n 'end_session_endpoint: this server does not support RP-initiated logout ' +\n '(CONTRACT.md §12.7.2 rule 1)',\n );\n }\n\n const url = new URL(endpoint);\n url.searchParams.set('id_token_hint', exposeSecret(params.idToken));\n if (params.postLogoutRedirectUri !== undefined) {\n url.searchParams.set('post_logout_redirect_uri', params.postLogoutRedirectUri);\n }\n if (params.state !== undefined) {\n url.searchParams.set('state', params.state);\n }\n return url.toString();\n }\n\n /**\n * Verify a back-channel logout token the OP POSTed to this application's\n * `backchannel_logout_uri` (CONTRACT.md §12.7.3).\n *\n * @remarks\n * Every check exists because skipping it has a name:\n *\n * 1. **Signature**, through the same §12.4 JWKS verifier the ID-token path\n * uses — no second key-fetching path. The key is selected **by `kid`**\n * (contract 1.69): the server signs every logout token with the header\n * `{\"alg\":\"EdDSA\",\"typ\":\"logout+jwt\",\"kid\":\"<kid>\"}`. A token with no\n * `kid` is refused as `unknown_kid` (no single-key fallback, no trying\n * every key), and an unknown `kid` causes at most one JWKS re-fetch per\n * cooldown window and is then refused as `unknown_kid`. §10.1 rules 10\n * and 11 (`typ` `at+jwt`, no `purpose`) apply to the access-token path\n * only, not here.\n * 2. **`iss`/`aud`**: a token minted for another RP is not accepted here.\n * 3. **`events` carries the back-channel-logout key.** This is what\n * distinguishes a logout token from an ID token; skipping it means\n * accepting a replayed ID token as a logout instruction.\n * 4. **`nonce` is absent.** Back-Channel Logout 1.0 §2.4 forbids it, and its\n * presence is the documented signature of an ID token being replayed.\n * Rejected, not ignored.\n * 5. **At least one of `sid`/`sub`** — a token naming neither identifies\n * nothing.\n * 6. **`exp` in the future, `iat` recent.**\n *\n * @returns `sid`, `sub` and `jti` — never a bare boolean, because the RP has\n * to know *which* session to end.\n */\n async verifyLogoutToken(\n token: string,\n configuration?: OidcConfiguration,\n ): Promise<VerifiedLogoutToken> {\n const config = configuration ?? (await this.oidcDiscover());\n const { decodeProtectedHeader } = await import('jose');\n\n // Same alg/kid discipline as §12.4 rules 1-2 (§12.7.3 rule 1), applied\n // before any key lookup: a token with no `kid` gets no \"the only key\"\n // fallback and is refused as `unknown_kid`.\n let header: { alg?: string; kid?: string };\n try {\n header = decodeProtectedHeader(token);\n } catch {\n throw new AuthError('logout token is not a well-formed JWS');\n }\n if (header.alg !== 'EdDSA') {\n throw new AuthError(`logout token alg must be EdDSA, got ${String(header.alg)}`);\n }\n if (!header.kid) {\n throw new AuthError('logout token carries no kid header (unknown_kid)', 'unknown_kid');\n }\n\n let claims: LogoutTokenClaims;\n try {\n claims = (await this.#verifierFor(config.jwks_uri).verifySignatureOnlyUnchecked(\n token,\n )) as unknown as LogoutTokenClaims;\n } catch (err) {\n // The JWKS cache has already refreshed at most once for this `kid` (one\n // attempt per cooldown window); an unmatched `kid` is then `unknown_kid`.\n if (typeof err === 'object' && err !== null && (err as { code?: unknown }).code === 'ERR_JWKS_NO_MATCHING_KEY') {\n throw new AuthError('no JWKS key matches the logout token kid (unknown_kid)', 'unknown_kid');\n }\n throw err;\n }\n\n if (claims.iss !== config.issuer) {\n throw new AuthError('logout token issuer does not match the discovery document');\n }\n if (claims.aud !== this.#options.clientId) {\n throw new AuthError('logout token audience does not match this client_id');\n }\n\n // Without this check the whole method is an elaborate way to accept an ID\n // token.\n const event = claims.events?.[BACKCHANNEL_LOGOUT_EVENT];\n if (event === undefined || typeof event !== 'object' || event === null || Array.isArray(event)) {\n throw new AuthError(\n 'not a logout token: the events claim does not carry ' +\n 'http://schemas.openid.net/event/backchannel-logout',\n );\n }\n\n if (claims.nonce !== undefined) {\n throw new AuthError(\n 'logout token carries a nonce, which Back-Channel Logout 1.0 §2.4 forbids: ' +\n 'this is an ID token being replayed as a logout token',\n );\n }\n\n if (claims.sid === undefined && claims.sub === undefined) {\n throw new AuthError('logout token names neither sid nor sub, so it identifies no session');\n }\n\n const nowSec = Math.floor(Date.now() / 1000);\n const skew = this.#options.clockSkewSec ?? 0;\n if (typeof claims.exp !== 'number' || claims.exp + skew < nowSec) {\n throw new AuthError('logout token has expired');\n }\n if (typeof claims.iat !== 'number' || claims.iat - skew > nowSec) {\n throw new AuthError('logout token was issued in the future');\n }\n if (nowSec - claims.iat > MAX_LOGOUT_TOKEN_AGE_SECS + skew) {\n throw new AuthError('logout token is too old to be a live delivery');\n }\n\n if (typeof claims.jti !== 'string' || claims.jti === '') {\n throw new AuthError('logout token carries no jti, so the RP cannot dedup redeliveries');\n }\n\n return {\n ...(claims.sid !== undefined ? { sid: claims.sid } : {}),\n ...(claims.sub !== undefined ? { sub: claims.sub } : {}),\n jti: claims.jti,\n };\n }\n\n // -------------------------------------------------------------------------\n // internals\n // -------------------------------------------------------------------------\n\n /**\n * One `oidcRefresh` wire call: the unit the per-token single-flight map shares. It deliberately holds\n * NO session-wide lock across the call (§9 rules 5 and 7, contract clarification): flights of\n * different refresh tokens run independently and concurrently, and the §1 cookie-session refresh\n * (the session's own `refreshGuard`) neither waits for nor fails them. The per-key map in\n * {@link OidcClient.oidcRefresh} is the guard; a refresh token namespace is not the session cookie's.\n */\n async #refreshFlight(params: OidcRefreshParams & { tenantId: string }): 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 const wire = await this.#postToken(configuration, form, params.tenantId);\n // No nonce: rule 6 does not apply to a refresh-issued ID token.\n return this.#toTokenSet(wire, configuration, undefined);\n }\n\n // -------------------------------------------------------------------------\n // §33 CIBA — client-initiated backchannel authentication (contract 1.58)\n //\n // On this handle because §33.6 puts them beside `oidcExchange` and\n // `deviceAuthorize`. The client always authenticates — by its\n // `clientSecret` (client_secret_post) or, for a `tls_client_auth` client,\n // by the session's §6.1 client certificate (`client_id` only); a client\n // with neither is refused locally. `private_key_jwt` client authentication\n // is not implemented by this SDK (§21.8 is informative).\n // -------------------------------------------------------------------------\n\n /**\n * `POST /oauth2/bc-authorize` (CIBA Core §7, CONTRACT.md §33.1) — ask AXIAM\n * to authenticate a user **on another device**.\n *\n * @remarks\n * Form-encoded; `tenant_id` in the query, never the body; the endpoint is\n * discovery's `backchannel_authentication_endpoint`, or its\n * `mtls_endpoint_aliases` entry on an mTLS call. Exactly the members set are\n * sent — or, with `signer`, only client authentication and `request`, a JWS\n * carrying every member (`requested_expiry` as a number) plus `iss` =\n * `clientId`, `aud` = discovery `issuer`, `iat` = `nbf` = now, `exp` = now +\n * 300 s and a fresh 128-bit `jti`.\n *\n * **Never retried** — not on a transport error, a `5xx` or a `429` (§33.7\n * rule 1): every accepted call stores a request and may notify a person. On\n * a lost answer, let it expire and ask again deliberately.\n *\n * **A success proves nothing about the user** (§33.3 rule 4): AXIAM answers\n * a hint naming nobody, a locked user and a real one identically.\n *\n * @throws AuthError (local) when the client has no credential, or the\n * server advertises no CIBA endpoint.\n * @throws ValidationError (local) for both or neither hint, or a ping-mode\n * request without a non-empty `clientNotificationToken`.\n * @throws OAuthProtocolError for a body carrying `error`, at any status —\n * `invalid_binding_message` with its description, a `429`\n * `rate_limit_exceeded`; otherwise §2 (`503` is `NetworkError`).\n */\n async cibaInitiate(params: CibaInitiateParams): Promise<CibaInitiateResponse> {\n const operation = 'ciba_initiate';\n const auth = this.#cibaClientAuth(operation);\n const hasLogin = typeof params.loginHint === 'string';\n const hasIdToken = typeof params.idTokenHint === 'string';\n if (hasLogin === hasIdToken) {\n throw cibaRefusal(operation, 'login_hint', 'set exactly one of loginHint and idTokenHint');\n }\n if (params.delivery?.mode === 'ping') {\n const token = params.delivery.clientNotificationToken;\n if (!(token instanceof Sensitive) || typeof token.expose() !== 'string' || token.expose() === '') {\n throw cibaRefusal(\n operation,\n 'client_notification_token',\n 'a ping-mode request needs a non-empty clientNotificationToken: without one AXIAM has nothing to ping with',\n );\n }\n }\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const endpoint = this.#optionalEndpoint(configuration, 'backchannel_authentication_endpoint');\n if (!endpoint) {\n throw new AuthError(\n \"the authorization server's discovery document advertises no backchannel_authentication_endpoint: \" +\n 'this server does not support CIBA (CONTRACT.md §33.1)',\n );\n }\n const url = this.#endpointUrl(endpoint, params.tenantId);\n\n const form = new URLSearchParams();\n form.set('client_id', auth.clientId);\n if (auth.clientSecret !== undefined) form.set('client_secret', auth.clientSecret);\n if (params.signer) {\n const nowSec = Math.floor(Date.now() / 1000);\n const claims: Record<string, unknown> = {};\n for (const [k, v] of cibaMembers(params)) claims[k] = v;\n if (params.requestedExpiry !== undefined) claims.requested_expiry = params.requestedExpiry;\n claims.iss = auth.clientId;\n claims.aud = configuration.issuer;\n claims.iat = nowSec;\n claims.nbf = nowSec;\n claims.exp = nowSec + SIGNED_REQUEST_LIFETIME_SECS;\n claims.jti = randomBytes(16).toString('hex');\n const request = await params.signer.sign(claims);\n form.set('request', request.expose());\n } else {\n for (const [k, v] of cibaMembers(params)) form.set(k, v);\n }\n\n // One request, whatever happens to it (§33.7 rule 1).\n const response = await this.#postCibaForm(url, form, operation);\n if (response.status < 200 || response.status >= 300) throw cibaError(operation, response);\n const data = jsonBody(response.data) as { auth_req_id?: unknown; expires_in?: unknown; interval?: unknown } | undefined;\n if (!data || typeof data.auth_req_id !== 'string' || typeof data.expires_in !== 'number') {\n throw new NetworkError('ciba_initiate: the response is not a CibaInitiateResponse');\n }\n return {\n authReqId: new Sensitive(data.auth_req_id),\n expiresIn: data.expires_in,\n interval: typeof data.interval === 'number' && data.interval > 0 ? data.interval : DEFAULT_CIBA_INTERVAL_SECS,\n receivedAt: Date.now(),\n };\n }\n\n /**\n * `POST /oauth2/token` with `grant_type=urn:openid:params:grant-type:ciba`\n * (CIBA Core §10.1, CONTRACT.md §33.1) — **one** token request.\n *\n * @remarks\n * The answers of §33.3 rule 6 surface as {@link OAuthProtocolError}:\n * `authorization_pending` and `slow_down` (non-terminal), `access_denied` and\n * `expired_token` (terminal and distinct — {@link isAccessDenied},\n * {@link isExpiredToken}), `invalid_grant`, `rate_limit_exceeded`. None of\n * them is retried. A transport failure, `408`, bodiless `429` or `5xx` —\n * **whatever its body**, `500 {\"error\":\"server_error\"}` included (§34.2 P8)\n * — is retried per §16 within the call; no other `4xx` is.\n *\n * A `200` is the §12 token set; its ID token is validated as for every other\n * grant (no nonce). **Store the returned tokens before anything else**: a\n * request is redeemed once, and a second `cibaPoll` for it is\n * `invalid_grant` (§33.7 rule 7). The tokens are returned, never adopted as\n * this client's credential.\n */\n async cibaPoll(params: CibaPollParams): Promise<OidcTokenSet> {\n return this.#cibaPoll(params, undefined);\n }\n\n /** {@link cibaPoll}; `bound` is `cibaAwait`'s deadline, which a §16 retry inside the poll must not pass. */\n async #cibaPoll(params: CibaPollParams, bound: PollDeadline | undefined): Promise<OidcTokenSet> {\n const operation = 'ciba_poll';\n const auth = this.#cibaClientAuth(operation);\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const url = this.#endpointUrl(this.#requiredEndpoint(configuration, 'token_endpoint'), params.tenantId);\n const form = new URLSearchParams();\n form.set('grant_type', CIBA_GRANT_TYPE);\n form.set('auth_req_id', params.authReqId.expose());\n form.set('client_id', auth.clientId);\n if (auth.clientSecret !== undefined) form.set('client_secret', auth.clientSecret);\n\n const outcome = await withRetry<{ wire?: TokenResponseWire; error?: AxiamError }>(\n async () => {\n const response = await this.#postCibaForm(url, form, operation);\n if (response.status >= 200 && response.status < 300) {\n // §33.7 rule 7: consume the 200 before anything else — and a body\n // that does not parse is not retried, since the server may already\n // have redeemed the request.\n const wire = jsonBody(response.data) as TokenResponseWire | undefined;\n if (!wire || typeof wire.access_token !== 'string') {\n return { error: new NetworkError('ciba_poll: the response is not a TokenResponse') };\n }\n return { wire };\n }\n // §33.7 rule 5, §34.2 P8: a 5xx is transient whatever its body —\n // AXIAM's own token endpoint answers `500 {\"error\":\"server_error\"}` —\n // so it is retried under §16 before any `error` member is read.\n if (response.status >= 500) {\n throw transient(retryableNetworkError(`${operation}: HTTP ${response.status}`, response));\n }\n if (response.status >= 300 && response.status < 400) {\n return { error: redirectRefused(operation, response.status) };\n }\n const protocol = oauth2ErrorFromBody(\n jsonBody(response.data),\n response.status === 429 ? retryAfterMs(response) : undefined,\n );\n if (protocol) return { error: protocol }; // decisive, never retried\n if (statusIsRetryable(response.status)) {\n throw transient(retryableNetworkError(`${operation}: HTTP ${response.status}`, response));\n }\n return { error: mapHttpStatusToError(response.status, `${operation}: HTTP ${response.status}`) };\n },\n {\n idempotent: true,\n operation,\n enabled: this.#session.retryEnabled,\n telemetry: this.#session.telemetry.dispatcher,\n ...(bound !== undefined ? deadlineBoundedRetry(bound, 'CIBA request') : {}),\n },\n );\n if (outcome.error) throw outcome.error;\n return this.#toTokenSet(outcome.wire as TokenResponseWire, configuration, undefined);\n }\n\n /**\n * Poll for `initiated`'s outcome until it is decided or expires (§33.1,\n * §33.7). Surfaces nothing to the user — AXIAM notified them.\n *\n * @remarks\n * - The first poll waits one `interval` (the response's, or 5 s); polling\n * earlier only earns `slow_down` and a longer wait.\n * - `slow_down` adds 5 s to the interval, cumulatively and permanently;\n * `authorization_pending` never lowers it.\n * - `rate_limit_exceeded`, and a transport failure or `5xx` that outlived\n * §16's retries inside {@link cibaPoll}, are not terminal: the loop waits\n * the interval and polls again.\n * - Polling stops at `receivedAt + expiresIn`, even if the server has not\n * said `expired_token`: when the next wait would reach the deadline, the\n * same `expired_token` is raised locally, without a request. A §16 retry\n * inside {@link cibaPoll} is bounded the same way (§34.2 P10): a wait that\n * would reach the deadline is not served and nothing is sent after it.\n * - `access_denied`, `expired_token`, `invalid_grant` and any other answer\n * end the loop.\n *\n * Returns the token set without adopting it as this client's credential —\n * the posture of `deviceLogin` and `loginClientCredentials`.\n *\n * **Ping mode:** do not loop. Answer the ping (`cibaHandlePing`) with `204`,\n * then call {@link cibaPoll} once — and once more at `interval` if that\n * answered `authorization_pending` or `slow_down`. Fall back to this loop\n * once half of `expiresIn` has passed without a ping: a ping is delivered at\n * least once, never exactly once, and may not arrive at all (§33.7 rule 6).\n */\n async cibaAwait(initiated: CibaInitiateResponse, params: CibaAwaitParams = {}): Promise<OidcTokenSet> {\n const clock = params.clock ?? SYSTEM_CIBA_CLOCK;\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const deadline = initiated.receivedAt + initiated.expiresIn * 1000;\n let interval = initiated.interval > 0 ? initiated.interval : DEFAULT_CIBA_INTERVAL_SECS;\n for (;;) {\n const waitMs = interval * 1000;\n if (clock.now() + waitMs >= deadline) {\n throw new OAuthProtocolError(\n 'expired_token',\n 'the CIBA request expired before it was decided (client-side deadline from expires_in; CONTRACT.md §33.7 rule 4)',\n );\n }\n await clock.sleep(waitMs);\n try {\n return await this.#cibaPoll(\n {\n authReqId: initiated.authReqId,\n configuration,\n ...(params.tenantId !== undefined ? { tenantId: params.tenantId } : {}),\n },\n { deadline, clock },\n );\n } catch (err) {\n if (err instanceof OAuthProtocolError) {\n if (err.error === 'authorization_pending' || err.error === 'rate_limit_exceeded') continue;\n if (err.error === 'slow_down') {\n interval += CIBA_SLOW_DOWN_INCREMENT_SECS; // cumulative, never reset\n continue;\n }\n throw err;\n }\n if (err instanceof NetworkError && TRANSIENT_POLL_FAILURES.has(err)) continue;\n throw err;\n }\n }\n }\n\n /**\n * Check a ping AXIAM delivered to your notification endpoint and return the\n * `auth_req_id` it names (CIBA Core §10.2, CONTRACT.md §33.1). **No I/O.**\n *\n * @param headers the request's headers — prefer Node's `req.rawHeaders`,\n * which keeps a duplicated `Authorization` that `req.headers` drops.\n * @param body the raw body (`string` / `Uint8Array`) or an already-parsed object.\n * @param expectedToken the `clientNotificationToken` you sent with the request.\n *\n * @remarks\n * 1. Exactly one `Authorization` header, `Bearer` (any case), one space, and\n * the token — compared in constant time (`crypto.timingSafeEqual`).\n * Otherwise `AuthError`, whose message names no value.\n * 2. A JSON object with a non-empty string `auth_req_id`; any other member\n * is ignored. Otherwise a local `ValidationError`.\n *\n * It neither answers the HTTP request nor calls the token endpoint: answer\n * `204` as soon as this returns, **then** {@link cibaPoll} — AXIAM retries a\n * ping that is not answered quickly, and the ping says only that the\n * request was decided, never how. Nor does it check that the `auth_req_id`\n * is one you issued: the token endpoint answers `invalid_grant` for any\n * other.\n */\n cibaHandlePing(\n headers: CibaPingHeaders,\n body: string | Uint8Array | Record<string, unknown>,\n expectedToken: Sensitive<string>,\n ): Sensitive<string> {\n const refused = (): AuthError =>\n new AuthError('ciba ping refused: the Authorization header is not the expected bearer (CONTRACT.md §33.1)');\n const values = authorizationValues(headers);\n if (values.length !== 1) throw refused();\n const value = values[0]!;\n const space = value.indexOf(' ');\n if (space < 0) throw refused();\n const scheme = value.slice(0, space);\n const token = value.slice(space + 1);\n if (scheme.toLowerCase() !== 'bearer' || token === '') throw refused();\n const expected = expectedToken instanceof Sensitive ? expectedToken.expose() : undefined;\n if (typeof expected !== 'string' || expected === '') throw refused();\n if (!constantTimeEqual(token, expected)) throw refused();\n\n let parsed: unknown = body;\n if (typeof body === 'string' || body instanceof Uint8Array) {\n try {\n parsed = JSON.parse(typeof body === 'string' ? body : Buffer.from(body).toString('utf8'));\n } catch {\n throw cibaRefusal('ciba_handle_ping', 'body', 'the ping body is not JSON');\n }\n }\n const id =\n parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>).auth_req_id\n : undefined;\n if (typeof id !== 'string' || id === '') {\n throw cibaRefusal('ciba_handle_ping', 'auth_req_id', 'the ping body carries no non-empty auth_req_id string');\n }\n return new Sensitive(id);\n }\n\n /** The client's credential for the CIBA calls (§33.1): never anonymous. */\n #cibaClientAuth(operation: string): { clientId: string; clientSecret?: string } {\n const secret = this.#options.clientSecret;\n if (secret !== undefined) {\n return { clientId: this.#options.clientId, clientSecret: exposeSecret(secret) };\n }\n if (this.#session.presentsClientCertificate) {\n // tls_client_auth: the certificate is the credential; client_id only.\n return { clientId: this.#options.clientId };\n }\n throw new AuthError(\n `${operation} requires client authentication: a CIBA client is never public — construct the OidcClient ` +\n 'with a clientSecret, or the session with a §6.1 client certificate (CONTRACT.md §33.1)',\n );\n }\n\n /**\n * POST a CIBA form through the session transport (§5 `X-Tenant-ID`, §6 TLS)\n * with every status resolved, so the CIBA error mapping — `error` at any\n * status, §33.4 — decides, and a `401` never enters the §9 guard. A transport\n * failure becomes a `NetworkError` that carries no axios cause: its `config`\n * holds the form, and the form holds the client secret.\n */\n async #postCibaForm(url: string, form: URLSearchParams, operation: string): Promise<AxiosResponse<unknown>> {\n try {\n return await this.#session.axios.post<unknown>(url, form.toString(), {\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n validateStatus: () => true,\n maxRedirects: 0,\n });\n } catch (err) {\n const code =\n err && typeof err === 'object' && typeof (err as { code?: unknown }).code === 'string'\n ? ` (${(err as { code: string }).code})`\n : '';\n throw transient(new NetworkError(`${operation}: the request failed before any response arrived${code}`));\n }\n }\n\n /**\n * One device-poll attempt under §16 (CONTRACT.md §14.2 rule 6, §16.2; C164-25): a `5xx` or\n * a transport failure is retried **inside** the poll (three requests in all, the `Retry-After`\n * a floor) before it surfaces as a `NetworkError`; the loop then takes its next interval. A\n * `429` is never retried here — it is rule 9's wait, the loop's — nor is any answer the\n * server decided (`400`, `401`).\n */\n async #postDevicePoll(\n url: string,\n form: URLSearchParams,\n bound: PollDeadline | undefined,\n ): Promise<TokenResponseWire> {\n const operation = 'device_poll';\n const outcome = await withRetry<{ wire?: TokenResponseWire; error?: AxiamError }>(\n async () => {\n try {\n const response = await this.#session.axios.post<TokenResponseWire>(url, form.toString(), {\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n maxRedirects: 0,\n });\n return { wire: response.data };\n } catch (err) {\n // Already an SDK error (the response interceptor mapped it): a decided answer.\n if (err instanceof AxiamError) return { error: err };\n const status = axiosStatus(err);\n const response = (err as { response?: AxiosResponse }).response;\n if (status === undefined) {\n throw new NetworkError(`${operation}: the request failed before any response arrived`, sanitizeAxiosError(err));\n }\n if (status >= 500) {\n throw retryableNetworkError(`${operation}: HTTP ${status}`, response);\n }\n return { error: pollRateLimit(err) ?? mapOidcError(err, url, 'token request failed') };\n }\n },\n {\n idempotent: true,\n operation,\n enabled: this.#session.retryEnabled,\n telemetry: this.#session.telemetry.dispatcher,\n ...(bound !== undefined ? deadlineBoundedRetry(bound, 'device authorization') : {}),\n },\n );\n if (outcome.error) throw outcome.error;\n return outcome.wire!;\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(this.#requiredEndpoint(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, nodeTlsOptionsOf(this.#session, jwksUri));\n this.#verifiers.set(jwksUri, verifier);\n return verifier;\n }\n\n /**\n * The RFC 8705 §5 alias for `name`, or `undefined` when this call is not\n * going over mutual TLS or the document publishes no aliases (CONTRACT.md\n * §21.3 rule 2).\n *\n * Three things this deliberately does NOT do, each of them a documented way\n * to get rule 2 wrong:\n *\n * * It never treats an absent `mtls_endpoint_aliases` as an error. Absence\n * means \"no separate mTLS host\", not \"mTLS unsupported\" — a deployment\n * running `client_auth = optional` on one listener serves both\n * populations at the conventional endpoints and correctly publishes\n * nothing.\n * * It is keyed by {@link MtlsEndpointAliases}, so only the seven aliasable\n * endpoints can reach it. `authorization_endpoint`,\n * `end_session_endpoint` and `jwks_uri` are unrepresentable here rather\n * than merely unused: they are front-channel or public, and an mTLS host\n * would raise a certificate-chooser dialog in the user's browser.\n * * It never touches `issuer`, which is an identifier and not an endpoint.\n * §10.1 rule 3 still compares a token's `iss` to `configuration.issuer`\n * by exact string, including for a token minted at an alias endpoint.\n *\n * An alias that IS present and cannot carry a certificate throws\n * (§21.3.1 vector C, contract 1.43) — see {@link assertUsableMtlsAlias}.\n */\n #aliasFor(\n configuration: OidcConfiguration,\n name: keyof MtlsEndpointAliases,\n replaces: string | undefined,\n ): string | undefined {\n if (!this.#session.presentsClientCertificate) {\n // A client with no certificate does not read the member at all — not\n // even to validate it. A deployment whose aliases are malformed must not\n // break the clients that never use them.\n return undefined;\n }\n const alias = configuration.mtls_endpoint_aliases?.[name];\n if (alias === undefined) {\n return undefined;\n }\n assertUsableMtlsAlias(alias, replaces);\n return alias;\n }\n\n /** An always-advertised endpoint, preferring its §21.3 rule 2 mTLS alias. */\n #requiredEndpoint(\n configuration: OidcConfiguration,\n name: 'token_endpoint' | 'userinfo_endpoint' | 'revocation_endpoint' | 'introspection_endpoint',\n ): string {\n return this.#aliasFor(configuration, name, configuration[name]) ?? configuration[name];\n }\n\n /**\n * A conditionally-advertised endpoint, preferring its §21.3 rule 2 mTLS\n * alias. `undefined` still means \"this server does not support the feature\" —\n * the caller raises that, and never concatenates a URL onto the issuer.\n */\n #optionalEndpoint(\n configuration: OidcConfiguration,\n name:\n | 'device_authorization_endpoint'\n | 'pushed_authorization_request_endpoint'\n | 'backchannel_authentication_endpoint',\n ): string | undefined {\n return this.#aliasFor(configuration, name, configuration[name]) ?? configuration[name];\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 // CONTRACT 1.52 N4.4 (C-12): client-credentials adoption is one of the\n // session-establishing calls that REPLACES a previously-adopted device\n // credential. Without this, a client that had called\n // authenticateDevice() and then adopted client-credentials kept riding\n // the stale device token on every later same-origin request —\n // installDeviceTokenInterceptor sends it unconditionally whenever\n // `deviceAccessToken` is set, regardless of what new credential was\n // just adopted here.\n this.#session.deviceAccessToken = undefined;\n // CONTRACT 1.52 N5.5 (C-12): client-credentials adoption carries no\n // LoginUserInfo, so it resets the §5.2 acting-tenant gate to unknown —\n // the same as a WebAuthn authentication, an SSO completion, or a device\n // login. Without this, a session that had recorded an earlier login's\n // (possibly non-organization-level) principalScope kept gating\n // actingTenant() on that STALE report after adopting an unrelated\n // service-account credential, instead of letting the server's 403\n // decide as N5.5 requires.\n this.#session.principalScope = undefined;\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) || isOAuth2Endpoint(url, this.#session.baseUrl)) {\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 // §12.1 rule 3 (C165-14): never follow a redirect from an `/oauth2/*` POST.\n maxRedirects: 0,\n };\n try {\n return await this.#session.axios.post<T>(url, form.toString(), config);\n } catch (err) {\n // §2 / §14.2 rule 9 (C164-23): a `429` carrying an `error` member from one of the OAuth2\n // form endpoints (token, device authorization, introspection, revocation, PAR, exchange)\n // is that OAuth2 error (AXIAM's own is `{\"error\":\"rate_limit_exceeded\"}`, with no\n // description), not a bare `NetworkError`. Gated by the call site, not `mapOidcError`, which\n // also maps discovery, the federation routes and UMA, where a `429` stays a `NetworkError`\n // (C164-31). A 5xx stays one whatever its body (§14.2 rule 6).\n if (axiosStatus(err) === 429) {\n const raw = (err as { response?: AxiosResponse }).response;\n const protocol = oauth2ErrorFromBody(axiosBody(err), raw ? retryAfterMs(raw) : undefined);\n if (protocol) throw protocol;\n }\n throw mapOidcError(err, url, fallbackMessage);\n }\n }\n\n /**\n * The shared body of the federation POSTs that establish a session: one\n * wire call, then the same post-login sync `login()`/`verifyMfa()` perform\n * (§4, §3) — reading the freshly-set `axiam_csrf`/`axiam_access` cookies out\n * of the jar.\n */\n /**\n * CONTRACT.md §5.2 rule 1 (C-12 question 5): a federation sign-in completes a\n * new session, possibly as a different principal, and its response carries no\n * LoginUserInfo. Forget what the previous login reported, so `actingTenant()`\n * does not gate on a stale principal and sends the header for the server to\n * decide, and drop the §17 memo, whose entries answered for that principal.\n * Called only after the server accepted the completion; a refused one\n * establishes no session and changes nothing.\n */\n #forgetPreviousPrincipal(): void {\n this.#session.principalScope = undefined;\n this.#session.decisionMemo.clear();\n // CONTRACT 1.52 N4.4 (C-12): an SSO/federation completion is one of the\n // session-establishing calls that REPLACES a previously-adopted device\n // credential. Without this, a client that had called\n // authenticateDevice() and then completed a federation sign-in kept\n // riding the stale device token on every later request —\n // installDeviceTokenInterceptor sends it unconditionally whenever\n // `deviceAccessToken` is set, regardless of what new session was just\n // established.\n // CONTRACT 1.52 N4.4 (C-12): an SSO/federation completion is one of the\n // session-establishing calls that REPLACES a previously-adopted device\n // credential. Without this, a client that had called\n // authenticateDevice() and then completed a federation sign-in kept\n // riding the stale device token on every later request —\n // installDeviceTokenInterceptor sends it unconditionally whenever\n // `deviceAccessToken` is set, regardless of what new session was just\n // established.\n this.#session.deviceAccessToken = undefined;\n }\n\n async #completeFederationSession(\n url: string,\n body: Record<string, string>,\n fallbackMessage: string,\n ): Promise<SsoCompleteResult> {\n const response = await this.#postJson<SsoLoginSuccessResponseWire>(url, body, fallbackMessage);\n\n this.#session.authenticated = true;\n this.#forgetPreviousPrincipal();\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 /** 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\n/**\n * Constant-time string comparison for `cibaHandlePing` (§33.1 rule 1):\n * `crypto.timingSafeEqual` over the UTF-8 bytes. A length mismatch is\n * answered `false` after comparing the presented value with itself, so the\n * time taken does not depend on where the two first differ.\n */\nfunction constantTimeEqual(token: string, expectedToken: string): boolean {\n const presented = Buffer.from(token, 'utf8');\n const expected = Buffer.from(expectedToken, 'utf8');\n if (presented.length !== expected.length) {\n timingSafeEqual(presented, presented);\n return false;\n }\n return timingSafeEqual(presented, expected);\n}\n","// CONTRACT.md §10.4 — the optional session-revocation feed poller (contract\n// 1.44; AXIAM threats T-39 and T-143).\n//\n// WHAT THIS NARROWS, AND WHAT IT IS NOT\n//\n// An AXIAM access token is self-contained and valid for up to fifteen minutes,\n// and the §10 guard verifies it locally. A logout, a role removal or an\n// account disable therefore does not reach a token already in a caller's hands\n// until it expires — §10.2 records that, and the documented answer has been\n// \"route the decision through gRPC introspection instead\", which is correct and\n// costs a round trip PER REQUEST.\n//\n// A deployment may publish `GET /oauth2/revocations`: the base64url-unpadded\n// SHA-256 of every session id revoked within the last access-token lifetime. A\n// guard that polls it rejects a revoked session within ONE POLL INTERVAL\n// instead, for one cacheable fetch per interval.\n//\n// It is NOT A CONTROL, and every rule below follows from that:\n//\n// * Default off. Nothing polls unless a caller attaches one.\n// * Never on the request path. `isRevoked` answers from the cached set and,\n// at most, starts a refresh whose result the NEXT caller sees.\n// * Never fail closed. An unreachable feed, a non-200, a body that does not\n// parse, an `alg` this build does not know — every one behaves exactly as\n// no feed at all. Not as an empty list: an empty list asserts that nothing\n// has been revoked, which is a guard silently honouring no revocations\n// while appearing to honour them.\n// * It only ever rejects. Every §10.1 rule runs first and still decides.\n// * A token with no `sid` is never matched. There is no session behind a\n// client-credentials token, an RPT or a token exchange, and hashing `jti`\n// instead would match nothing while looking like it worked.\n\nimport { createHash } from 'node:crypto';\n\n/**\n * The only digest the feed publishes, and the only one this poller accepts.\n *\n * A document naming anything else is treated as unusable — exactly as an\n * unreachable feed is — rather than as a list of entries that happen not to\n * match. Silently matching nothing is how a guard ends up reporting that it\n * honours revocations while honouring none.\n */\nconst SUPPORTED_ALG = 'SHA-256';\n\n/** The shortest interval a caller may configure (§10.4 rule 2), in ms. */\nexport const MIN_POLL_INTERVAL_MS = 15_000;\n\n/** The default interval, and the one §10.4 recommends, in ms. */\nexport const DEFAULT_POLL_INTERVAL_MS = 30_000;\n\n/**\n * The largest number of entries kept in the cache (§10.4 rule 2).\n *\n * The server bounds the document by its own revocation rate over one token\n * lifetime, so this is defence against a server that stops doing so — a cache\n * with no ceiling is an allocation an unauthenticated endpoint controls.\n * Overflow drops the WHOLE set rather than truncating it: a truncated set is a\n * guard that admits some revoked sessions and reports none, which is worse\n * than one that admits all of them and says the feed is unusable.\n */\nexport const MAX_ENTRIES = 100_000;\n\n/** Options for {@link RevocationFeed}. */\nexport interface RevocationFeedOptions {\n /** Poll interval in milliseconds. Clamped to {@link MIN_POLL_INTERVAL_MS}. */\n pollIntervalMs?: number;\n /** Injected for tests. Defaults to `globalThis.fetch`. */\n fetchImpl?: typeof fetch;\n /** Injected for tests. Defaults to `Date.now`. */\n now?: () => number;\n}\n\n/**\n * A poller for one deployment's revocation feed.\n *\n * Share one instance across the guards that should poll once between them,\n * rather than once each.\n */\nexport class RevocationFeed {\n readonly #feedUrl: string;\n readonly #pollIntervalMs: number;\n readonly #fetchImpl: typeof fetch;\n readonly #now: () => number;\n\n /**\n * `undefined` means \"never successfully fetched\", which is NOT the same as\n * an empty set — and is why this is not a bare `Set`.\n */\n #entries: Set<string> | undefined;\n #lastAttempt: number | undefined;\n /** Collapses a burst of stale-cache callers into one fetch. */\n #inFlight: Promise<void> | undefined;\n\n constructor(baseUrl: string, options: RevocationFeedOptions = {}) {\n this.#feedUrl = new URL('/oauth2/revocations', baseUrl).toString();\n this.#pollIntervalMs = Math.max(\n options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS,\n MIN_POLL_INTERVAL_MS,\n );\n this.#fetchImpl = options.fetchImpl ?? globalThis.fetch.bind(globalThis);\n this.#now = options.now ?? Date.now;\n }\n\n /**\n * The feed entry for a `sid`, as the server computes it.\n *\n * Base64url without padding over the claim's EXACT string — never a parsed\n * and re-rendered UUID, or the answer depends on this SDK's parser rather\n * than on the feed.\n */\n static entryFor(sid: string): string {\n return createHash('sha256').update(sid, 'utf8').digest('base64url');\n }\n\n /**\n * Has this session been revoked, as far as this poller knows?\n *\n * `false` whenever the answer is not a confident yes — a feed never fetched,\n * unreachable, malformed, or simply not listing this session. The caller\n * admits the request in all of those cases, which is §10.4 rule 3 and is the\n * whole reason the feature is safe to turn on.\n *\n * Never blocks on the network beyond the first call: once the cache is warm,\n * a stale cache starts a refresh and this answers from what it currently\n * has.\n */\n async isRevoked(sid: string): Promise<boolean> {\n await this.#refreshIfStale();\n return this.#entries?.has(RevocationFeed.entryFor(sid)) ?? false;\n }\n\n /** Fetch now, whatever the interval says. For tests, and for warming. */\n async refresh(): Promise<void> {\n this.#inFlight ??= this.#doRefresh().finally(() => {\n this.#inFlight = undefined;\n });\n await this.#inFlight;\n }\n\n async #refreshIfStale(): Promise<void> {\n const last = this.#lastAttempt;\n if (last !== undefined && this.#now() - last < this.#pollIntervalMs) {\n return;\n }\n await this.refresh();\n }\n\n async #doRefresh(): Promise<void> {\n this.#lastAttempt = this.#now();\n const fetched = await this.#fetchOnce();\n if (fetched !== undefined) {\n this.#entries = fetched;\n }\n // On failure the previous set is deliberately left in place: a blip must\n // not un-revoke a session the guard already knows about.\n }\n\n /**\n * One fetch. `undefined` for every kind of failure, which the caller treats\n * identically — see the file header on why \"unusable\" must not collapse into\n * \"empty\".\n */\n async #fetchOnce(): Promise<Set<string> | undefined> {\n try {\n const response = await this.#fetchImpl(this.#feedUrl, { method: 'GET' });\n if (!response.ok) {\n return undefined;\n }\n const document: unknown = await response.json();\n if (typeof document !== 'object' || document === null) {\n return undefined;\n }\n const { alg, revoked } = document as { alg?: unknown; revoked?: unknown };\n if (alg !== SUPPORTED_ALG) {\n return undefined;\n }\n if (!Array.isArray(revoked) || revoked.length > MAX_ENTRIES) {\n return undefined;\n }\n return new Set(revoked.filter((e): e is string => typeof e === 'string'));\n } catch {\n return undefined;\n }\n }\n}\n","// Public types for the OIDC / SSO relying-party helpers (CONTRACT.md §12.1).\n//\n// Naming convention used throughout — deliberate, and worth copying verbatim\n// into the other SDKs so the eight implementations stay legible as one family:\n//\n// * Types that ARE a protocol document keep their wire spelling in\n// snake_case: `OidcConfiguration` (the OIDC Discovery 1.0 metadata\n// document) and `IdTokenClaims` (JWT claims). A caller cross-references\n// these field names against OIDC Core / RFC 8414, so renaming them would\n// be a lossy translation. `AxiamClaims` in node/jwks.ts already sets this\n// precedent.\n// * Types that are an SDK-shaped RESULT use the repo's camelCase public-API\n// convention (as `LoginResult` does): `OidcTokenSet`, `IntrospectionResult`,\n// `AuthorizationRequest`, `SsoStartResult`, `SsoCompleteResult`. These are\n// not verbatim wire objects — they carry `Sensitive<T>`-wrapped fields and\n// derived data (`idClaims`) that the wire body does not have.\n//\n// The five §12.5 secret fields — `access_token`, `refresh_token`, `id_token`,\n// `client_secret`, `code_verifier` — are `Sensitive<string>` wherever they\n// appear below. `state` and `nonce` are NOT secrets (§12.3 rule 2) and are\n// plain strings.\n\nimport type { Sensitive } from '../core/index.js';\nimport type { IdTokenClaims } from './oidcIdToken.js';\n\n// ---------------------------------------------------------------------------\n// Discovery\n// ---------------------------------------------------------------------------\n\n/**\n * RFC 8705 §5 `mtls_endpoint_aliases` — the seven endpoints re-based on the\n * host that performs the mutual-TLS handshake (wire schema\n * `MtlsEndpointAliases`, contract 1.40; the seventh, CIBA's\n * `backchannel_authentication_endpoint`, contract 1.58).\n *\n * @remarks\n * A TLS listener decides whether to request a client certificate during the\n * handshake, before it has seen any HTTP, so \"ask for a certificate on\n * `/oauth2/token` but not on `/oauth2/authorize`\" is not something one listener\n * can do. A deployment wanting both runs two, and this object is how the second\n * one is named.\n *\n * Only these seven are ever aliased. `authorization_endpoint` and\n * `end_session_endpoint` are front-channel and `jwks_uri` is public, so\n * CONTRACT.md §21.3 rule 2 forbids synthesising an alias for any of them —\n * sending a browser to an mTLS host raises a native certificate-chooser dialog\n * most users cannot answer. `issuer` is not aliased either, and §10.1 rule 3\n * still compares `iss` against it by exact string.\n *\n * Every member is optional even though the server's schema marks them\n * required. AXIAM builds them from one path through a shared macro and so\n * always publishes the complete set, but RFC 8705 §5 permits an OP to alias\n * fewer, and the shape of this member must never be why a client stops\n * working — the same principle rule 2 point 1 states for the object as a\n * whole, one level in. An absent entry falls back to the top-level endpoint of\n * the same name, exactly as an absent object does.\n */\nexport interface MtlsEndpointAliases {\n /** The mTLS token endpoint — RFC 8705 §2 client authentication and §3 the mint of a certificate-bound token. */\n token_endpoint?: string;\n /** The mTLS userinfo endpoint — OIDC Core §5.3, reached with an access token that may carry `cnf`. */\n userinfo_endpoint?: string;\n /** The mTLS revocation endpoint — RFC 7009 §2.1, which authenticates the client. */\n revocation_endpoint?: string;\n /** The mTLS introspection endpoint — RFC 7662 §2.1, which authenticates the caller. */\n introspection_endpoint?: string;\n /** The mTLS device authorization endpoint — RFC 8628 §3.1, which authenticates the client. */\n device_authorization_endpoint?: string;\n /** The mTLS pushed authorization request endpoint — RFC 9126 §2, which authenticates the client. */\n pushed_authorization_request_endpoint?: string;\n /**\n * The mTLS CIBA backchannel authentication endpoint — CIBA Core §7, which\n * authenticates the client (contract 1.58, §21.3.1: the **seventh** alias;\n * a `tls_client_auth` CIBA client has no other way to present its\n * certificate on a two-listener deployment).\n */\n backchannel_authentication_endpoint?: string;\n}\n\n/**\n * The OIDC Discovery 1.0 metadata document served by\n * `GET /.well-known/openid-configuration` (wire schema\n * `OidcDiscoveryDocument`). Every field is required by the server's schema.\n *\n * @remarks\n * `issuer` is the **authoritative** issuer for ID-token validation\n * (CONTRACT.md §12.4 rule 3). It may legitimately differ from the client's\n * `baseUrl` when AXIAM runs behind a proxy, so this SDK never rejects a\n * document on an issuer/base-URL mismatch (§12.3 rule 6). Likewise `jwks_uri`\n * is read from here rather than hardcoded.\n */\nexport interface OidcConfiguration {\n /** The authorization server's issuer identifier — the value an ID token's `iss` claim must equal exactly. */\n issuer: string;\n /** The authorization endpoint `oidcBegin` builds its redirect URL from. */\n authorization_endpoint: string;\n /** The token endpoint used by `oidcExchange`, `oidcRefresh` and `loginClientCredentials`. */\n token_endpoint: string;\n /** The userinfo endpoint. Advertised by the server but deliberately NOT called by any SDK (§12.3 rule 5). */\n userinfo_endpoint: string;\n /** URI of the JWKS document whose keys verify ID-token signatures (§12.4 rule 2). */\n jwks_uri: string;\n /** The RFC 7009 revocation endpoint used by `revoke`. */\n revocation_endpoint: string;\n /** The RFC 7662 introspection endpoint used by `introspect`. */\n introspection_endpoint: string;\n /** OAuth2 `response_type` values the server supports. */\n response_types_supported: string[];\n /** Subject identifier types the server supports. */\n subject_types_supported: string[];\n /** ID-token signing algorithms the server advertises. Informational only: §12.4 rule 1 pins verification to `EdDSA` regardless of what appears here. */\n id_token_signing_alg_values_supported: string[];\n /** Scopes the server supports. */\n scopes_supported: string[];\n /** Client-authentication methods the token endpoint supports (`client_secret_post`, §12.1 note 3). */\n token_endpoint_auth_methods_supported: string[];\n /** Claims the server may include in an ID token. */\n claims_supported: string[];\n /** Grant types the token endpoint supports. */\n grant_types_supported: string[];\n /**\n * RFC 8628 device authorization endpoint, used by `deviceAuthorize` (§14.1).\n *\n * Optional because a server that does not implement the device grant does\n * not advertise it, and because this document may come from a non-AXIAM OP.\n * Its absence is an error at call time, never a cue to build the URL by\n * concatenation.\n */\n device_authorization_endpoint?: string;\n /**\n * OIDC RP-Initiated Logout 1.0 `end_session_endpoint`, used by `logoutUrl`\n * (§12.7.2 rule 1).\n *\n * Optional for the same reason, and the rule is stricter here: §12.7.2\n * rule 1 forbids synthesising this URL from the issuer. Code that\n * concatenates works against AXIAM and breaks against every other OP the\n * same application is pointed at.\n */\n end_session_endpoint?: string;\n /**\n * RFC 9126 pushed authorization request endpoint, used by `oidcPar` (§26.1).\n *\n * Optional for the same reason as the two above, and with the same rule: its\n * absence is an error at call time, never a cue to build `<issuer>/oauth2/par`\n * by concatenation.\n */\n pushed_authorization_request_endpoint?: string;\n /**\n * RFC 7636 §4.3 / RFC 8414 §2 — the PKCE code-challenge methods the\n * authorization endpoint accepts. AXIAM publishes `[\"S256\"]` and only\n * `[\"S256\"]` (contract 1.42, §21.5).\n *\n * Informational only: this SDK implements S256 and nothing else, so it\n * neither negotiates against this list nor falls back to `plain` — `plain`\n * is not implemented anywhere here.\n *\n * **Optional even though the server's schema marks it required**, and the\n * reason is the same one §21.5 gives: *RFC 8414 defines no default for this\n * member, so its absence does not mean `S256`*. This struct must still parse\n * a document from a non-AXIAM OP that omits it, exactly as it does for every\n * other member modelled optional here.\n */\n code_challenge_methods_supported?: string[];\n /**\n * RFC 8414 §2 — the JWS algorithms the token endpoint accepts on a\n * `private_key_jwt` client assertion. AXIAM publishes\n * `[\"PS256\", \"ES256\", \"EdDSA\"]` (contract 1.42, §21.5).\n *\n * Informational only, and optional for the same reason as\n * {@link OidcConfiguration.code_challenge_methods_supported}: RFC 8414\n * defines no default, so absence is not a statement about what the OP\n * accepts.\n */\n token_endpoint_auth_signing_alg_values_supported?: string[];\n /**\n * RFC 8414 §2 — the client-authentication methods the revocation endpoint\n * accepts; AXIAM publishes the token endpoint's list (contract 1.60,\n * §21.5).\n *\n * Informational only, and optional: a server before 1.0.0 omits all four\n * revocation and introspection members, and RFC 8414 then reads this one\n * as `client_secret_basic` alone. Neither changes how `revoke`\n * authenticates — it keeps the method this client was configured with\n * (§12.1 rules 3 and 4).\n */\n revocation_endpoint_auth_methods_supported?: string[];\n /**\n * RFC 8414 §2 — the client-authentication methods the introspection\n * endpoint accepts; AXIAM publishes the token endpoint's list without\n * `none`, since introspection refuses a public client (contract 1.60,\n * §21.5). Informational and optional, as above.\n */\n introspection_endpoint_auth_methods_supported?: string[];\n /**\n * RFC 8414 §2 — the JWS algorithms a `private_key_jwt` assertion at the\n * revocation endpoint may use; equal to\n * {@link OidcConfiguration.token_endpoint_auth_signing_alg_values_supported}\n * on AXIAM (contract 1.60, §21.5). Informational and optional.\n */\n revocation_endpoint_auth_signing_alg_values_supported?: string[];\n /**\n * RFC 8414 §2 — the JWS algorithms a `private_key_jwt` assertion at the\n * introspection endpoint may use (contract 1.60, §21.5). Informational and\n * optional.\n */\n introspection_endpoint_auth_signing_alg_values_supported?: string[];\n /**\n * CIBA Core §4 — the backchannel authentication endpoint `cibaInitiate`\n * posts to (contract 1.58, §21.5, §33.1). Optional: its absence means the\n * server does not support CIBA, and is an error at call time, never a cue\n * to build `<issuer>/oauth2/bc-authorize` by concatenation.\n */\n backchannel_authentication_endpoint?: string;\n /**\n * CIBA Core §4 — the token delivery modes the server offers. AXIAM\n * publishes `[\"poll\", \"ping\"]`. A statement about the server: which mode a\n * given client holds is its registration's answer.\n */\n backchannel_token_delivery_modes_supported?: string[];\n /** CIBA Core §4 — AXIAM publishes `false`, and this SDK never sends a `user_code` (§33.3 rule 3). */\n backchannel_user_code_parameter_supported?: boolean;\n /** CIBA Core §4 — the algorithms a signed authentication request may use: `[\"PS256\", \"ES256\", \"EdDSA\"]` (§33.2). */\n backchannel_authentication_request_signing_alg_values_supported?: string[];\n /** Whether the OP sends back-channel logout tokens. */\n backchannel_logout_supported?: boolean;\n /** Whether those logout tokens carry `sid`. AXIAM always sends it. */\n backchannel_logout_session_supported?: boolean;\n /**\n * RFC 8705 §5 endpoint aliases for a deployment that terminates mutual TLS\n * on a host other than the issuer's own (contract 1.40, §21.3 rule 2).\n *\n * Optional, and **absence means \"no separate host\", not \"mTLS unsupported\"**:\n * a deployment running `client_auth = optional` on a single listener serves\n * both populations at the conventional endpoints and correctly publishes\n * nothing here. A client that treats absence as an error refuses the most\n * common mTLS topology AXIAM ships. The server omits the key rather than\n * serialising `null`.\n */\n mtls_endpoint_aliases?: MtlsEndpointAliases;\n}\n\n// ---------------------------------------------------------------------------\n// oidcBegin\n// ---------------------------------------------------------------------------\n\n/**\n * The result of `oidcBegin` — everything the caller needs to start an\n * authorization-code + PKCE login (CONTRACT.md §12.1).\n *\n * @remarks\n * **The caller owns this state** (§12.3 rule 1). The SDK stores nothing: it\n * keeps no copy of `state`, `nonce` or `codeVerifier` in process-global state\n * or any implicit cache. Persist all three in your own HTTP session (or in an\n * {@link OidcStateStore}), redirect the browser to {@link url}, and pass\n * `nonce` + `codeVerifier` back into `oidcExchange` when the code arrives.\n */\nexport interface AuthorizationRequest {\n /** The fully-built authorization URL to redirect the browser to. */\n url: string;\n /** CSPRNG CSRF value (≥128 bits, base64url unpadded) to compare against the `state` the IdP returns. Not a secret (§12.3 rule 2). */\n state: string;\n /** CSPRNG replay-protection value (≥128 bits) that must equal the ID token's `nonce` claim. Not a secret (§12.3 rule 2). */\n nonce: string;\n /** The PKCE verifier, secret for its whole lifetime (§12.5). Pass it back into `oidcExchange`. */\n codeVerifier: Sensitive<string>;\n}\n\n/**\n * Arguments to `oidcPar` (CONTRACT.md §26.1).\n *\n * The parameters come from an {@link AuthorizationRequest} that `oidcBegin`\n * already produced — §26.2 rule 1 forbids a second generator for `state`,\n * `nonce` and PKCE, and the `codeVerifier` the caller must keep for\n * `oidcExchange` is the one `oidcBegin` gave them.\n */\nexport interface OidcParParams {\n /** The request `oidcBegin` returned. Its `url` is replaced by {@link PushedAuthorizationRequest.authorizationUrl}. */\n request: AuthorizationRequest;\n /** The relying party's redirect URI — the same value that will be sent at `oidcExchange` (§26.2 rule 6). */\n redirectUri: string;\n /** Requested scope. `openid` is added when absent, exactly as `oidcBegin` does. */\n scope?: string | string[];\n /** The discovery document, for the `authorization_endpoint`. Fetched via `oidcDiscover` when omitted. */\n configuration?: OidcConfiguration;\n /** Tenant UUID override for the mandatory `?tenant_id=` query parameter (§12.1 note 2). */\n tenantId?: string;\n /**\n * RFC 9449 §10.1 `dpop_jkt` — the base64url SHA-256 JWK thumbprint of the\n * key the client will use for DPoP proofs on the eventual token request.\n * Sent in the pushed form **only when set**; omitted entirely otherwise\n * (§12.1: an absent optional field is absent, never empty).\n *\n * @remarks\n * **The caller supplies this value; the SDK does not derive it.** This SDK\n * implements the resource-server half of DPoP — §21.7.2 proof\n * *verification* — and ships no proof generator, so it holds no DPoP key to\n * take a thumbprint of. A client that does generate proofs computes the\n * thumbprint from its own public JWK and passes it here;\n * `jwkThumbprintS256` (exported from the node entry point) is there for\n * exactly that and produces the RFC 7638 value this parameter wants.\n *\n * Why it is worth pushing at all: without it the authorization code is bound\n * to a DPoP key only at the token request, so an attacker who steals the code\n * can redeem it with a key of their own. RFC 9449 §10 binds the code to the\n * key at authorization time instead, which is the point of pushing the\n * request over the back channel in the first place.\n */\n dpopJkt?: string;\n /**\n * The provider hint to push (contract 1.65, §26.2 rule 8): the same optional\n * `idpHint` {@link OidcBeginParams.idpHint} takes, validated the same way.\n * When set, the pushed form carries `axiam_idp_hint` exactly once; it is\n * absent otherwise. It rides the pushed body only — the authorization URL\n * built from the `request_uri` stays exactly `client_id` and `request_uri`.\n *\n * @remarks\n * When this is unset, the `axiam_idp_hint` that the `oidcBegin` URL\n * ({@link OidcParParams.request}) carries is pushed instead (D-N36); when\n * both are set, this argument wins and the URL's hint is not pushed.\n */\n idpHint?: string;\n}\n\n/**\n * The result of a pushed authorization request (CONTRACT.md §26.1).\n *\n * The server answered `201` — RFC 9126 §2.2 specifies Created, and a success\n * predicate written `status === 200` would treat every successful push as a\n * failure.\n */\nexport interface PushedAuthorizationRequest {\n /**\n * The authorization URL to redirect the browser to.\n *\n * Carries **exactly** `client_id` and `request_uri` and nothing else: the\n * server refuses a request that mixes a `request_uri` with inline\n * authorization parameters rather than merging them, because merging is\n * where parameter confusion lives (§26.2 rule 2).\n */\n authorizationUrl: string;\n /** The opaque, single-use handle. Wrapped per §26.5 — it is a bearer handle to a formed authorization request. */\n requestUri: Sensitive<string>;\n /** Seconds until `requestUri` expires. Not advisory (§26.2 rule 3). */\n expiresIn: number;\n /** The `state` from the pushed request, to compare against what the IdP returns. */\n state: string;\n /** The `nonce` from the pushed request, to compare against the ID token's claim. */\n nonce: string;\n /** The PKCE verifier to pass into `oidcExchange` — the same one `oidcBegin` produced. */\n codeVerifier: Sensitive<string>;\n}\n\n/** Arguments to `oidcBegin` (pure local computation — no network I/O). */\nexport interface OidcBeginParams {\n /** The discovery document, as returned by `oidcDiscover`. `authorization_endpoint` is taken from it and never hardcoded (§12.1 rule 5). */\n configuration: OidcConfiguration;\n /** The relying party's redirect URI, echoed back into `oidcExchange` unchanged. */\n redirectUri: string;\n /** Requested scope, as a string or an array. `openid` is added automatically when absent (§12.1 rule 4). Defaults to `openid`. */\n scope?: string | string[];\n /**\n * Extra authorization-request parameters (e.g. `prompt`, `login_hint`,\n * `ui_locales`). §12.1 rule 5 allows caller-supplied additions but forbids\n * the SDK from adding any of its own beyond the mandated eight, so\n * attempting to override one of those eight throws.\n */\n extraParams?: Record<string, string>;\n /**\n * Which sign-in provider to send the browser to (contract 1.65, §12.1\n * \"`idp_hint`\"): a provider's UUID, its `provider_slug` or a branded kind\n * name (`google`, `apple`, …). Emitted as the single query parameter\n * `axiam_idp_hint` — the ninth parameter of §12.1 rule 5 — and only when set.\n *\n * @remarks\n * Validated for emptiness and length only: an empty string or one longer\n * than 256 UTF-8 bytes throws a `ValidationError` and no URL is built. It is\n * never trimmed, case-folded, parsed as a UUID or looked up. An unresolvable\n * hint is ignored by the server, so there is nothing to handle on that\n * outcome. When set it replaces any `axiam_idp_hint` in `extraParams`\n * (emitted exactly once). There is no `kc_idp_hint` alias.\n */\n idpHint?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Token sets\n// ---------------------------------------------------------------------------\n\n/**\n * A token set returned by the OAuth2 token endpoint (wire schema\n * `TokenResponse`), returned by `oidcExchange`, `oidcRefresh` and\n * `loginClientCredentials`.\n *\n * @remarks\n * `accessToken`, `refreshToken` and `idToken` are {@link Sensitive} (§12.5):\n * `toString()`, `JSON.stringify()` and `console.log`/`util.inspect` all\n * redact them to `[SENSITIVE]`, and the raw value is reachable only through\n * the documented-`@internal` `expose()` accessor.\n *\n * `idClaims` is present exactly when `idToken` is, and holds the\n * **already-validated** claim set (§12.4) — validation happens before this\n * object is ever constructed, so an `OidcTokenSet` in your hands is never\n * partially trusted (§12.4 rule 7).\n */\nexport interface OidcTokenSet {\n /** The OAuth2 access token (§12.5 secret). */\n accessToken: Sensitive<string>;\n /** The token type the server issued (`Bearer`). */\n tokenType: string;\n /** Access-token lifetime in seconds from the time of the response. */\n expiresIn: number;\n /**\n * Granted scope, when the server narrowed or echoed it.\n *\n * On an `oidcRefresh` result this is the **refresh response's** scope and the\n * token's scope from then on — never the original grant's. The server\n * intersects a grant with the client's current registration at every\n * refresh, so it may be narrower (and carry no ID token once `openid` is\n * gone), permanently for that grant (contract 1.60, §12.1).\n */\n scope?: string;\n /** The refresh token, when the grant issued one (§12.5 secret). */\n refreshToken?: Sensitive<string>;\n /** The raw ID token, when the grant issued one (§12.5 secret). */\n idToken?: Sensitive<string>;\n /** The validated ID-token claims — present exactly when {@link idToken} is (§12.1, §12.4). */\n idClaims?: IdTokenClaims;\n}\n\n/** Arguments to `oidcExchange` (`grant_type=authorization_code`). */\nexport interface OidcExchangeParams {\n /** The authorization code the IdP redirected back with. */\n code: string;\n /** The verifier from the matching {@link AuthorizationRequest}. Accepts the `Sensitive` wrapper or a bare string (e.g. rehydrated from your own session store). */\n codeVerifier: Sensitive<string> | string;\n /** The same `redirect_uri` that was sent on the authorization request. */\n redirectUri: string;\n /** The `nonce` from the matching {@link AuthorizationRequest}. MANDATORY — §12.4 rule 6 is not optional for this grant. */\n nonce: string;\n /** Tenant UUID for the token endpoint's required `tenant_id` query parameter. Defaults to the client's configured `tenantId` when it was built in UUID form (§12.3 rule 4). */\n tenantId?: string;\n /** A pre-fetched discovery document, to avoid re-reading the (cached) one. Fetched via `oidcDiscover` when omitted. */\n configuration?: OidcConfiguration;\n}\n\n/** Arguments to `oidcRefresh` (`grant_type=refresh_token`). */\nexport interface OidcRefreshParams {\n /** The refresh token to redeem. Accepts the `Sensitive` wrapper or a bare string. */\n refreshToken: Sensitive<string> | string;\n /** Optional narrowed scope to request. Omitted from the form body when absent. */\n scope?: string;\n /** Tenant UUID for the `tenant_id` query parameter (§12.3 rule 4). */\n tenantId?: string;\n /** A pre-fetched discovery document. Fetched via `oidcDiscover` when omitted. */\n configuration?: OidcConfiguration;\n}\n\n/** Arguments to `loginClientCredentials` (`grant_type=client_credentials`). */\nexport interface LoginClientCredentialsParams {\n /** Optional scope to request. This grant requests no `openid` scope and the response carries no `id_token` (§12.1). */\n scope?: string;\n /** Tenant UUID for the `tenant_id` query parameter (§12.3 rule 4). */\n tenantId?: string;\n /** A pre-fetched discovery document. Fetched via `oidcDiscover` when omitted. */\n configuration?: OidcConfiguration;\n /**\n * Adopt the returned `access_token` as this client's bearer credential for\n * subsequent REST calls on the same session — the §12.1\n * \"`login_client_credentials` as a credential source\" allowance (a **MAY**,\n * hence opt-in and `false` by default).\n *\n * When `true` the token is held behind {@link Sensitive} inside a request\n * interceptor closure and emitted as `Authorization: Bearer …`; it is never\n * written to `axios.defaults`, a public property, or the cookie jar, so it\n * stays unreachable through any public getter (§12.3 rule 2).\n */\n adoptAsCredential?: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Introspection / revocation\n// ---------------------------------------------------------------------------\n\n/** Arguments to `introspect` (RFC 7662). Requires confidential-client credentials (§12.1 note 4). */\nexport interface IntrospectParams {\n /** The token to introspect. Accepts the `Sensitive` wrapper or a bare string. */\n token: Sensitive<string> | string;\n /** Optional RFC 7662 `token_type_hint` (`access_token` / `refresh_token`). */\n tokenTypeHint?: string;\n /** Tenant UUID for the `tenant_id` query parameter (§12.3 rule 4). */\n tenantId?: string;\n /** A pre-fetched discovery document. Fetched via `oidcDiscover` when omitted. */\n configuration?: OidcConfiguration;\n}\n\n/** Arguments to `revoke` (RFC 7009). Requires confidential-client credentials (§12.1 note 4). */\nexport interface RevokeParams {\n /** The token to revoke. Accepts the `Sensitive` wrapper or a bare string. */\n token: Sensitive<string> | string;\n /** Optional RFC 7009 `token_type_hint`. */\n tokenTypeHint?: string;\n /** Tenant UUID for the `tenant_id` query parameter (§12.3 rule 4). */\n tenantId?: string;\n /** A pre-fetched discovery document. Fetched via `oidcDiscover` when omitted. */\n configuration?: OidcConfiguration;\n}\n\n/**\n * The RFC 7662 introspection result (wire schema `IntrospectionResponse`).\n * Only `active` is guaranteed; the server omits the metadata fields for an\n * inactive token.\n */\nexport interface IntrospectionResult {\n /** Whether the token is currently active. */\n active: boolean;\n /** Subject the token was issued to. */\n sub?: string;\n /** Client the token was issued to. */\n clientId?: string;\n /** Scope granted to the token. */\n scope?: string;\n /** Token type (`Bearer`). */\n tokenType?: string;\n /** Expiry time, epoch seconds. */\n exp?: number;\n /** Issued-at time, epoch seconds. */\n iat?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Federation SSO (upstream IdP)\n// ---------------------------------------------------------------------------\n\n/** Arguments to `ssoStart` (`POST /api/v1/auth/federation/oidc/start`). */\nexport interface SsoStartParams {\n /** UUID of the server-side federation configuration identifying the upstream IdP. */\n federationConfigId: string;\n /** Post-login destination, stored server-side and echoed back by `ssoComplete`. */\n redirectUri: string;\n /** Tenant UUID. One tenant form (`tenantId` or `tenantSlug`) is required; defaults to the client's configuration (§5.1). */\n tenantId?: string;\n /** Tenant slug. Alternative to {@link tenantId}. */\n tenantSlug?: string;\n /** Organization UUID. One org form (`orgId` or `orgSlug`) is required; defaults to the client's configuration (§5.1). */\n orgId?: string;\n /** Organization slug. Alternative to {@link orgId}. */\n orgSlug?: string;\n}\n\n/**\n * The result of `ssoStart` (wire schema `OidcStartResponse`).\n *\n * @remarks\n * There is deliberately **no nonce**: on the federation path the nonce never\n * leaves the server (§12.1 note 7). Round-trip {@link state} into\n * `ssoComplete` unmodified — the server stores it single-use with a 10-minute\n * TTL and recovers the whole login context from it.\n */\nexport interface SsoStartResult {\n /** The upstream IdP authorization URL to redirect the browser to. */\n authorizeUrl: string;\n /** Single-use CSRF state to round-trip back into `ssoComplete` unmodified. */\n state: string;\n /** Remaining TTL of the server-side state row, in seconds (600 = 10 min). */\n expiresInSecs: number;\n}\n\n/** Arguments to `ssoComplete` (`POST /api/v1/auth/federation/oidc/callback`). */\nexport interface SsoCompleteParams {\n /** The `state` value the IdP redirected back with — must be the one `ssoStart` returned. */\n state: string;\n /** The authorization code the IdP redirected back with. */\n code: string;\n}\n\n/**\n * The result of `ssoComplete` (wire schema `SsoLoginSuccessResponse`).\n *\n * @remarks\n * Carries **no token material** — the session arrives as `Set-Cookie`, so the\n * §4 cookie jar is what actually captures it (§12.1 note 6). Use a Node\n * session (`createNodeSession`) or the session is silently lost.\n */\nexport interface SsoCompleteResult {\n /** The provisioned/linked user's UUID. */\n userId: string;\n /** The established session's UUID. */\n sessionId: string;\n /** Session/access-token lifetime in seconds. */\n expiresIn: number;\n /** The post-login destination that was stored during `ssoStart`. */\n redirectUri: string;\n}\n\n// ---------------------------------------------------------------------------\n// Public \"Sign in with X\" login providers (contract 1.38)\n// ---------------------------------------------------------------------------\n\n/**\n * `protocol` value selecting `ssoStart` (CONTRACT.md §12.1 note 10).\n */\nexport const PROTOCOL_OIDC_CONNECT = 'OidcConnect';\n\n/** `protocol` value selecting `ssoStartOauth2` (§12.1 note 10). */\nexport const PROTOCOL_OAUTH2 = 'OAuth2';\n\n/**\n * `protocol` value selecting the SAML login endpoint, which is **not** a §12\n * vocabulary operation (§12.1 note 10).\n */\nexport const PROTOCOL_SAML = 'Saml';\n\n/**\n * The query parameter the server delivers a handoff code in, on the SPA's own\n * callback URL (CONTRACT.md §12.1 note 12).\n */\nexport const HANDOFF_QUERY_PARAM = 'axiam_handoff';\n\n/**\n * How long a handoff code is valid, in seconds (§12.1 note 12).\n *\n * @remarks\n * It exists to survive one redirect. Redeem it immediately, once.\n */\nexport const HANDOFF_CODE_TTL_SECS = 60;\n\n/**\n * One sign-in button (wire schema `PublicFederationProvider`).\n *\n * @remarks\n * This is an **unauthenticated** response and carries only what a button\n * needs. There is no `client_id`, no `metadata_url`, no endpoint URL and no\n * secret — absent by construction rather than filtered out — and §12.1 note 9\n * forbids an SDK from expecting one.\n */\nexport interface FederationProvider {\n /**\n * Config id, to be echoed back to the matching start operation.\n *\n * Pass it through unmodified: inheritance is resolved server-side (§12.1\n * note 13) and this id is how the server is told what resolution produced.\n */\n id: string;\n /**\n * Which provider this is, for the button's branding — `google`, `github`,\n * `generic_oidc`, … **Not** what selects the start operation; see\n * {@link protocol}.\n */\n providerKind: string;\n /** The operator's display name for the provider. */\n displayName: string;\n /**\n * `OidcConnect`, `Saml` or `OAuth2` — the value that selects which start\n * operation to call (§12.1 note 10). Compare against\n * {@link PROTOCOL_OIDC_CONNECT}, {@link PROTOCOL_OAUTH2} and\n * {@link PROTOCOL_SAML}.\n *\n * Kept as the wire string rather than narrowed to a union the SDK enforces:\n * the server owns this vocabulary, and a value added server-side must not\n * become a parse failure for the whole list.\n *\n * An `OAuth2` provider issues **no ID token** — the server authenticates by\n * calling a configured userinfo endpoint, so there is no signature, no\n * `nonce` and no `aud` (§12.1 note 11). A surface rendering these buttons\n * SHOULD make that distinction visible rather than presenting the two as\n * equivalent.\n */\n protocol: string;\n /**\n * Whether AXIAM ships this provider's own sign-in mark, which its button\n * must then use. `false` for the generic kinds, whose buttons read \"Sign in\n * with `displayName`\" and use {@link buttonIcon} where one was uploaded.\n */\n hasBundledMark: boolean;\n /**\n * `true` when the provider is inherited from the organization rather than\n * configured on this tenant (§12.1 note 13). Informational — it is not\n * needed to sign in, and nothing in this SDK computes it.\n */\n inherited: boolean;\n /**\n * The operator's uploaded button icon as a bounded raster `data:` URL.\n *\n * `undefined` for most providers: present only for generic ones whose\n * operator uploaded a mark.\n */\n buttonIcon?: string;\n}\n\n/**\n * The result of `ssoProviders` (wire schema\n * `PublicFederationProvidersResponse`).\n *\n * @remarks\n * An **empty** {@link providers} is a normal success, never an error (§12.1\n * note 9).\n */\nexport interface FederationProviderList {\n /** The providers to offer, in a stable server-defined order. */\n providers: FederationProvider[];\n}\n\n/**\n * Arguments to `ssoProviders` (`GET /api/v1/auth/federation/providers`).\n *\n * @remarks\n * Every field is optional and all four travel as **query** parameters — this\n * is a `GET` with no body (§12.1). Unset forms fall back to the session's own\n * configuration (§5.1); when neither the arguments nor the session supply a\n * workspace the request is still sent, and still answers `200` with an empty\n * list.\n */\nexport interface SsoProvidersParams {\n /** Organization UUID. Alternative to {@link orgSlug}. */\n orgId?: string;\n /** Organization slug, as typed on a login page. */\n orgSlug?: string;\n /** Tenant UUID. Alternative to {@link tenantSlug}. */\n tenantId?: string;\n /** Tenant slug. Omitted or blank means the organization's own scope. */\n tenantSlug?: string;\n}\n\n/**\n * Arguments to `ssoStartOauth2` (`POST /api/v1/auth/federation/oauth2/start`).\n *\n * @remarks\n * Deliberately identical in shape to {@link SsoStartParams}, because the wire\n * schemas are: `OAuth2StartRequest` and `OidcStartRequest` differ in name\n * only. There is **no** PKCE field, and there must not be — the verifier is\n * generated and held server-side (§12.1 note 11).\n */\nexport interface SsoStartOauth2Params {\n /** UUID of the federation configuration, from {@link FederationProvider.id}. */\n federationConfigId: string;\n /**\n * The SPA callback route. Sent to the provider verbatim, so it must match\n * what is registered there byte for byte.\n */\n redirectUri: string;\n /** Tenant UUID; defaults to the session's configuration (§5.1). */\n tenantId?: string;\n /** Tenant slug. Alternative to {@link tenantId}. */\n tenantSlug?: string;\n /** Organization UUID; defaults to the session's configuration (§5.1). */\n orgId?: string;\n /** Organization slug. Alternative to {@link orgId}. */\n orgSlug?: string;\n}\n\n/**\n * Arguments to `ssoCompleteOauth2`\n * (`POST /api/v1/auth/federation/oauth2/callback`).\n */\nexport interface SsoCompleteOauth2Params {\n /** The `state` the provider redirected back with — the one `ssoStartOauth2` returned, unmodified. */\n state: string;\n /** The authorization code the provider redirected back with. */\n code: string;\n}\n\n/**\n * Arguments to `ssoCompleteHandoff` (`POST /api/v1/auth/federation/handoff`).\n */\nexport interface SsoCompleteHandoffParams {\n /**\n * The single-use code read from the {@link HANDOFF_QUERY_PARAM} query\n * parameter on the SPA's callback URL.\n *\n * Valid for {@link HANDOFF_CODE_TTL_SECS} seconds and redeemable **once**.\n */\n code: string;\n}\n\n// ---------------------------------------------------------------------------\n// Wire types (snake_case, mirror the server schemas verbatim)\n// ---------------------------------------------------------------------------\n\n/** 200 body of `POST /oauth2/token` (wire schema `TokenResponse`). */\nexport interface TokenResponseWire {\n access_token: string;\n token_type: string;\n expires_in: number;\n scope?: string | null;\n refresh_token?: string | null;\n id_token?: string | null;\n}\n\n/** 200 body of `POST /oauth2/introspect` (wire schema `IntrospectionResponse`). */\nexport interface IntrospectionResponseWire {\n active: boolean;\n sub?: string | null;\n client_id?: string | null;\n scope?: string | null;\n token_type?: string | null;\n exp?: number | null;\n iat?: number | null;\n}\n\n/** 200 body of `POST /api/v1/auth/federation/oidc/start` (wire schema `OidcStartResponse`). */\nexport interface OidcStartResponseWire {\n authorize_url: string;\n state: string;\n expires_in_secs: number;\n}\n\n/** 200 body of `POST /api/v1/auth/federation/oidc/callback` (wire schema `SsoLoginSuccessResponse`). */\nexport interface SsoLoginSuccessResponseWire {\n user_id: string;\n session_id: string;\n expires_in: number;\n redirect_uri: string;\n}\n\n/** One item of `GET /api/v1/auth/federation/providers` (wire schema `PublicFederationProvider`). */\nexport interface PublicFederationProviderWire {\n id: string;\n provider_kind: string;\n display_name: string;\n protocol: string;\n has_bundled_mark: boolean;\n inherited: boolean;\n button_icon?: string | null;\n}\n\n/** 200 body of `GET /api/v1/auth/federation/providers` (wire schema `PublicFederationProvidersResponse`). */\nexport interface PublicFederationProvidersResponseWire {\n providers: PublicFederationProviderWire[];\n}\n\n/**\n * 200 body of `POST /api/v1/auth/federation/oauth2/start` (wire schema\n * `OAuth2StartResponse`).\n *\n * @remarks\n * The PKCE verifier is **not** here and never will be: it stays server-side in\n * the login-state row, for the same reason the OIDC `nonce` does (§12.1\n * note 11).\n */\nexport interface OAuth2StartResponseWire {\n authorize_url: string;\n state: string;\n expires_in_secs: number;\n}\n\n// ---------------------------------------------------------------------------\n// §14 Device Authorization Grant (RFC 8628)\n// ---------------------------------------------------------------------------\n\n/** Arguments to `deviceAuthorize` (CONTRACT.md §14.1). */\nexport interface DeviceAuthorizeParams {\n /** Scopes to request, as a string or array. */\n scope?: string | string[];\n /** Tenant UUID for the mandatory `tenant_id` query parameter (§12.1 note 2). */\n tenantId?: string;\n /** A pre-fetched discovery document; fetched via `oidcDiscover` when absent. */\n configuration?: OidcConfiguration;\n}\n\n/**\n * The `DeviceAuthorizationResponse` — what the device shows its user, plus the\n * `device_code` it polls with.\n *\n * @remarks\n * `deviceCode` is {@link Sensitive} (§14.5): a bearer credential for the\n * lifetime of the grant. `userCode` deliberately is **not** — it exists to be\n * read aloud and typed by a human, and wrapping it would defeat the one thing\n * it is for. Neither may be logged; displaying `userCode` is the caller's job.\n */\nexport interface DeviceAuthorization {\n /** The device's polling credential (§14.5 secret). */\n deviceCode: Sensitive<string>;\n /** The short code the human types into the verification page. */\n userCode: string;\n /** Where the human goes to enter {@link DeviceAuthorization.userCode}. */\n verificationUri: string;\n /**\n * The verification URI with the user code already embedded, when the server\n * sent one — prefer it when the device can render a QR code.\n *\n * Never synthesised by concatenation when absent (§14.3): its format is the\n * server's to choose.\n */\n verificationUriComplete?: string;\n /** Seconds until the grant expires. Polling stops here (§14.2 rule 4). */\n expiresIn: number;\n /** Seconds between polls, from the response, defaulted to 5 s when omitted. */\n interval: number;\n}\n\n/** Arguments to `devicePoll` (CONTRACT.md §14.1). */\nexport interface DevicePollParams {\n /** The `deviceCode` from {@link DeviceAuthorization}. */\n deviceCode: Sensitive<string> | string;\n /** Tenant UUID for the `tenant_id` query parameter. */\n tenantId?: string;\n /** A pre-fetched discovery document. */\n configuration?: OidcConfiguration;\n}\n\n/** Arguments to `deviceLogin` (CONTRACT.md §14.3). */\nexport interface DeviceLoginParams {\n /** Scopes to request. */\n scope?: string | string[];\n /** Tenant UUID for the `tenant_id` query parameter. */\n tenantId?: string;\n /** A pre-fetched discovery document. */\n configuration?: OidcConfiguration;\n /**\n * Called with the {@link DeviceAuthorization} **before the first poll**\n * (§14.3 rule 2), so the caller can display the code. The SDK never prints\n * it: what the device does with it is the application's decision.\n */\n onUserCode: (authorization: DeviceAuthorization) => void | Promise<void>;\n /**\n * The clock the polling loop waits on and measures the `expires_in` deadline\n * against (§14.2 rule 4); defaults to `Date.now` and `setTimeout`. Injectable\n * so the schedule is testable without sleeping.\n */\n clock?: CibaClock;\n}\n\n/** 200 body of `POST /oauth2/device_authorization`. */\nexport interface DeviceAuthorizationResponseWire {\n device_code: string;\n user_code: string;\n verification_uri: string;\n verification_uri_complete?: string | null;\n expires_in: number;\n interval?: number | null;\n}\n\n/**\n * **201** body of `POST /oauth2/par` (CONTRACT.md §26.1).\n *\n * RFC 9126 §2.2 specifies Created, not OK — a success predicate written\n * `status === 200` treats every successful push as a failure.\n */\nexport interface PushedAuthorizationResponseWire {\n request_uri: string;\n expires_in: number;\n}\n\n// ---------------------------------------------------------------------------\n// §15 Token Exchange (RFC 8693)\n// ---------------------------------------------------------------------------\n\n/**\n * Arguments to `tokenExchange` (CONTRACT.md §15.1).\n *\n * @remarks\n * `subjectToken` is the only required field; everything else is optional and\n * **named**, because four optional strings in positional order is a bug\n * waiting to be written (§15.1).\n */\nexport interface TokenExchangeParams {\n /** The token being exchanged (§15.5 secret). */\n subjectToken: Sensitive<string> | string;\n /**\n * What kind of token `subjectToken` is. **Required** (§15.1).\n *\n * @remarks\n * There is no default. A defaulted type would be the SDK choosing which kind\n * of credential you are holding, which is exactly what §15.7 forbids — so\n * TypeScript refuses the call at compile time instead.\n *\n * Pass `ACCESS_TOKEN_TYPE` for the same-domain exchange of §15.1, or\n * `JWT_TOKEN_TYPE` for a trusted external issuer's JWT (§15.7).\n *\n * The SDK never reads `subjectToken` to decide this value (§15.7). Which\n * kind of token you hold is something only you know; AXIAM refuses refresh\n * and ID token types by name, and the SDK will not retry a refusal as a\n * different type.\n */\n subjectTokenType: string;\n /**\n * The acting party, when this is a **delegation** (§15.2 rule 1).\n *\n * Its absence selects **impersonation** — a different operation with\n * different risk. The SDK never fills this in for you.\n *\n * It must have been issued to the exchanging client (§15.2 rule 9, contract\n * 1.60): the usual actor is **the same client's own `client_credentials`\n * token** — `(await oidc.loginClientCredentials()).accessToken`. A token\n * issued to another client, a console sign-in or a service account is\n * answered `invalid_request` (\"actor_token was not issued to the exchanging\n * client\"), which is surfaced unchanged and never retried or dropped.\n */\n actorToken?: Sensitive<string> | string;\n /** Scopes to request. Omitted from the body when absent. */\n scopes?: string[];\n /** The service the issued token is for. */\n audience?: string;\n /** RFC 8707 synonym of `audience`; the server refuses the pair when they disagree. */\n resource?: string;\n /** Tenant UUID for the `tenant_id` query parameter. */\n tenantId?: string;\n /** A pre-fetched discovery document. */\n configuration?: OidcConfiguration;\n}\n\n/**\n * The result of an exchange (wire schema `TokenExchangeResponse`).\n *\n * @remarks\n * **There is no `refreshToken` field, and that is deliberate** (§15.2 rule 4).\n * RFC 8693 issues none, so the type cannot represent one: an application that\n * wants a fresh exchanged token re-runs the exchange. This result also never\n * enters the §9 single-flight refresh guard — there is nothing to refresh.\n */\nexport interface ExchangedToken {\n /** The issued token (§15.5 secret). */\n accessToken: Sensitive<string>;\n /**\n * What the server actually issued. Mandatory in RFC 8693 §2.2.1 and\n * surfaced rather than dropped (§15.2 rule 6), so a client that asked for\n * one type and got another can tell.\n */\n issuedTokenType: string;\n /** The token type (`Bearer`). */\n tokenType: string;\n /** Lifetime in seconds — never longer than the subject token's remaining life. */\n expiresIn: number;\n /**\n * **The granted scope, which may be narrower than requested** even on\n * success (§15.2 rule 7). Read it rather than assuming the request was\n * honoured verbatim.\n */\n scope?: string;\n}\n\n/** 200 body of a token-exchange `POST /oauth2/token`. */\nexport interface TokenExchangeResponseWire {\n access_token: string;\n issued_token_type: string;\n token_type: string;\n expires_in: number;\n scope?: string | null;\n}\n\n// ---------------------------------------------------------------------------\n// §12.7 Logout helpers\n// ---------------------------------------------------------------------------\n\n/** Arguments to `logoutUrl` (CONTRACT.md §12.7.2). */\nexport interface LogoutUrlParams {\n /**\n * A previously-issued ID token, placed in `id_token_hint` — the only\n * *authenticated* statement of which session is being ended.\n */\n idToken: Sensitive<string> | string;\n /**\n * Where the OP should send the browser afterwards. Honoured only on exact\n * match against the client's registered allow-list — a server-side check the\n * SDK deliberately does not duplicate (§12.7.2 rule 3).\n */\n postLogoutRedirectUri?: string;\n /**\n * An opaque value echoed back on the redirect. Generated and checked by the\n * caller (§12.7.2 rule 2), never by the SDK.\n */\n state?: string;\n /** A pre-fetched discovery document. */\n configuration?: OidcConfiguration;\n}\n\n/**\n * What a verified logout token names (§12.7.3).\n *\n * @remarks\n * Deliberately **not** a bare boolean: the RP has to know *which* session to\n * end, and a verifier that only says \"valid\" would force the caller to\n * re-parse the token themselves, with none of the checks this type is proof\n * of.\n */\nexport interface VerifiedLogoutToken {\n /**\n * The session that ended. **When present, end only this session** — falling\n * back to \"every session for `sub`\" is over-reach the AXIAM server itself\n * refuses to make.\n */\n sid?: string;\n /** The subject whose session ended. */\n sub?: string;\n /**\n * Replay identifier.\n *\n * **The RP dedups on this, not the SDK.** Back-channel delivery is\n * at-least-once with retry, so a valid token legitimately arrives twice; the\n * SDK has no durable store and an in-memory guard would silently drop a real\n * second logout after a restart. Surfaced, never consumed.\n */\n jti: string;\n}\n\n// ---------------------------------------------------------------------------\n// §20 UMA 2.0 — Protection API and ticket grant\n// ---------------------------------------------------------------------------\n\n/**\n * A UMA resource set — an AXIAM resource seen through the Protection API\n * (CONTRACT.md §20.1).\n *\n * `_id` is **the AXIAM resource id**, not a parallel identifier: the same UUID\n * is directly usable as the `resourceId` of a later {@link RequestedPermission},\n * and as the resource id anywhere else in this SDK.\n */\nexport interface ResourceSet {\n /** Assigned by the server on registration; absent on the way in. */\n id?: string;\n /** Human-readable name, shown in the admin UI. */\n name: string;\n /**\n * Free-form resource type. Defaults server-side to `uma_resource` when\n * omitted, so a resource server that leaves it out does not produce a row\n * that sorts oddly next to hand-made ones.\n */\n type?: string;\n /**\n * The scope names a resource server may ask for on this resource.\n *\n * **Replaced wholesale by an update, never merged** (§20.2 rule 8). This SDK\n * does not read the current scopes and fold them into an update payload as a\n * convenience — doing so would make removing a scope impossible through it.\n */\n resourceScopes?: string[];\n}\n\n/** One `(resource, scopes)` pair a resource server requires (§20.1). */\nexport interface RequestedPermission {\n /** The AXIAM resource id — the same UUID the Protection API returned as `_id`. */\n resourceId: string;\n /**\n * Scope names, each of which the resource must already declare. Matched\n * exactly: no prefix or wildcard semantics in either direction.\n */\n resourceScopes: string[];\n}\n\n/**\n * One entry of an RPT's `permissions` claim.\n *\n * **A record of a decision already made, not a live authorization answer**\n * (§20.2 rule 7). These are the pairs the engine allowed when the RPT was\n * minted; a grant revoked afterwards does not empty a live RPT. Do not cache\n * them beyond the token's own expiry — which is why that expiry is short.\n */\nexport interface RptPermission {\n resourceId: string;\n resourceScopes: string[];\n /** Absolute expiry, seconds since the epoch. */\n exp: number;\n}\n\n/**\n * A Requesting Party Token (§20.1).\n *\n * **There is no `refreshToken` field, and that is deliberate** (§20.2 rule 5).\n * The grant issues none, so an RPT cannot outlive the ticket that authorised\n * it; an application that wants a fresh one re-runs the grant. This result\n * never enters the §9 single-flight refresh guard — there is nothing to refresh.\n */\nexport interface RequestingPartyToken {\n /** The RPT itself (§20.6 secret). */\n accessToken: Sensitive<string>;\n /** Always `Bearer`. */\n tokenType: string;\n /** `min(claimToken remaining, server ceiling, 300 s)`. */\n expiresIn: number;\n}\n\n/**\n * A parsed `WWW-Authenticate: UMA` challenge (§20.3).\n */\nexport interface UmaChallenge {\n /** The protection realm the resource server named. */\n realm?: string;\n /**\n * The authorization server the resource server nominates.\n *\n * **Not automatically trusted.** See `umaParseChallenge`.\n */\n asUri?: string;\n /** The ticket to exchange — a bearer credential for its 60-second life. */\n ticket?: Sensitive<string>;\n}\n\n/** Arguments to `umaExchangeTicket` (§20.1). */\nexport interface UmaExchangeTicketParams {\n /** The permission ticket, from `umaRequestTicket` or a parsed challenge. */\n ticket: Sensitive<string> | string;\n /**\n * The requesting party's access token.\n *\n * **Required**, though UMA 2.0 §3.3.1 marks it optional: v1 implements\n * neither incremental authorization nor claims-gathering, so this is the only\n * channel that names a requesting party (§20.2 rule 2).\n */\n claimToken: Sensitive<string> | string;\n /** Tenant UUID for the `tenant_id` query parameter. */\n tenantId?: string;\n /** A pre-fetched discovery document. */\n configuration?: OidcConfiguration;\n}\n\n/** Wire shape of a resource set (snake_case, as the server sends it). */\nexport interface ResourceSetWire {\n _id?: string;\n name: string;\n type?: string;\n resource_scopes?: string[];\n}\n\n/** Wire shape of the RPT the ticket grant returns. */\nexport interface RptResponseWire {\n access_token: string;\n token_type: string;\n expires_in: number;\n}\n\n// ---------------------------------------------------------------------------\n// §33 CIBA — client-initiated backchannel authentication (contract 1.58)\n// ---------------------------------------------------------------------------\n\n/**\n * Whom `cibaInitiate` asks AXIAM to authenticate: **exactly one** hint\n * (§33.2). The type makes both, or neither, unwritable; a JavaScript caller\n * that builds one anyway is refused locally with a `ValidationError`.\n * `login_hint_token` is not offered (§33.3 rule 3).\n */\nexport type CibaUserHint =\n | {\n /** A username, then an e-mail address, within the tenant. Personal data: never logged by the SDK. */\n loginHint: string;\n /** Not with `loginHint`. */\n idTokenHint?: never;\n }\n | {\n /** An ID token this deployment issued to this client; it names the user only. */\n idTokenHint: string;\n /** Not with `idTokenHint`. */\n loginHint?: never;\n };\n\n/**\n * How the client receives the outcome, as it registered (§33.3 rule 1).\n * Poll is the default; push is not offered (the server does not).\n */\nexport type CibaDelivery =\n | {\n /** The client polls the token endpoint (`cibaAwait`). */\n mode: 'poll';\n }\n | {\n /** AXIAM pings the client's registered notification endpoint, then the client polls once. */\n mode: 'ping';\n /**\n * The bearer AXIAM presents at the ping; keep it to check the ping with\n * `cibaHandlePing`. Required and non-empty (1–1 024 visible ASCII; at least\n * 22 for a `fapi2` client). Never returned by AXIAM.\n */\n clientNotificationToken: Sensitive<string>;\n };\n\n/** The algorithms a signed CIBA request may use (§33.2). */\nexport type CibaSigningAlg = 'PS256' | 'ES256' | 'EdDSA';\n\n/**\n * Arguments to `cibaInitiate` (§33.2 `CibaInitiateRequest`).\n *\n * Exactly the members set are sent. `bindingMessage` and `loginHint` can be\n * personal data: the SDK never logs them. There is no parameter for\n * `login_hint_token`, `user_code` or `request_uri` — AXIAM refuses each\n * (§33.3 rule 3) — and no channel for any other form parameter.\n */\nexport type CibaInitiateParams = CibaUserHint & {\n /** Space-separated; must include `openid` (the server checks; the SDK does not pre-validate, §33.3 rule 5). */\n scope: string;\n /** Shown to the user on the approval page — what lets them tell the request they started from an attacker's. Required for a `fapi2` client. */\n bindingMessage?: string;\n /** The requested lifetime in seconds, 30–600 (absent: 300). Sent as a string on the form, as a number inside a signed request. */\n requestedExpiry?: number;\n /** Space-separated authentication context classes. */\n acrValues?: string;\n /** RFC 8707 resource indicator. */\n resource?: string;\n /** Poll (default) or ping, as registered. */\n delivery?: CibaDelivery;\n /**\n * Send the request as one signed JWT (`request`, CIBA Core §7.1.1) —\n * required of a client that registered\n * `backchannel_authentication_request_signing_alg`, refused from one that\n * did not. Build it with `CibaRequestSigner.create`.\n */\n signer?: import('./oidc.js').CibaRequestSigner;\n /** Tenant UUID for the `tenant_id` query parameter (§12.3 rule 4). */\n tenantId?: string;\n /** A pre-fetched discovery document. */\n configuration?: OidcConfiguration;\n};\n\n/**\n * `CibaInitiateResponse` (§33.2), plus when it was received.\n *\n * **A successful initiate proves nothing about the user** (§33.3 rule 4):\n * AXIAM answers a hint that names nobody, a locked user and a real one\n * identically. The only signal that a user did not answer is `expired_token`.\n */\nexport interface CibaInitiateResponse {\n /** The request's id at the token endpoint — a bearer credential for the grant (§33.5). Never parse or length-check it. */\n authReqId: Sensitive<string>;\n /** The request's lifetime in seconds — authoritative (§33.7 rule 4). */\n expiresIn: number;\n /** The minimum seconds between token requests: the response's value, or 5 when it was absent or zero (§33.7 rule 2). */\n interval: number;\n /** When the response was received, in epoch milliseconds; `cibaAwait`'s deadline is this plus `expiresIn`. */\n receivedAt: number;\n}\n\n/** Arguments to `cibaPoll`. */\nexport interface CibaPollParams {\n /** The `auth_req_id` from {@link CibaInitiateResponse} or a ping. */\n authReqId: Sensitive<string>;\n /** Tenant UUID for the `tenant_id` query parameter. */\n tenantId?: string;\n /** A pre-fetched discovery document. */\n configuration?: OidcConfiguration;\n}\n\n/**\n * The clock `cibaAwait` waits on — injectable so its schedule is testable\n * without sleeping (§33.8 tests 6 and 7).\n */\nexport interface CibaClock {\n /** The current time, epoch milliseconds. */\n now(): number;\n /** Wait `ms` milliseconds. */\n sleep(ms: number): Promise<void>;\n}\n\n/** Arguments to `cibaAwait`. */\nexport interface CibaAwaitParams {\n /** Tenant UUID for the `tenant_id` query parameter. */\n tenantId?: string;\n /** A pre-fetched discovery document. */\n configuration?: OidcConfiguration;\n /** The clock to wait on; defaults to `Date.now` and `setTimeout`. */\n clock?: CibaClock;\n}\n\n/**\n * The request headers `cibaHandlePing` accepts, in whichever shape the HTTP\n * framework hands them over:\n *\n * - Node's `req.rawHeaders` (a flat `[name, value, name, value, …]` array) —\n * **prefer it**: `req.headers` silently drops a duplicated `Authorization`,\n * which §33.1 requires refusing;\n * - an iterable of `[name, value]` pairs (a fetch `Headers`, a `Map`);\n * - a header record (`req.headers`), a value possibly an array.\n */\nexport type CibaPingHeaders =\n | readonly string[]\n | Iterable<readonly [string, string]>\n | Record<string, string | readonly string[] | undefined>;\n\n// ---------------------------------------------------------------------------\n// Native sign-in with a provider ID token (CONTRACT.md §37, contract 1.65)\n// ---------------------------------------------------------------------------\n\n/** Options of `OidcClient.loginWithProviderIdToken` beyond its three positional inputs (§37.1). */\nexport interface LoginWithProviderIdTokenOptions {\n /**\n * Scopes to request, sent space-joined as `scope`. Sent **only when named**:\n * an omitted or empty list sends no `scope` field, which the server reads as\n * the empty set — no `openid`, hence no `id_token` in the response. The SDK\n * adds no scope of its own (§37.2 rule 7); pass `openid` to receive\n * `idClaims`.\n */\n scopes?: readonly string[];\n /** An RFC 8707 `resource` indicator. Sent only when set. */\n resource?: string;\n /** Tenant UUID for the `tenant_id` query parameter (§12.3 rule 4). A slug-only client must pass it. */\n tenantId?: string;\n /** A pre-fetched discovery document. Fetched via `oidcDiscover` when omitted. */\n configuration?: OidcConfiguration;\n}\n\n/**\n * The pair {@link nativeNonce} returns (CONTRACT.md §37.4): give `hashed` to\n * the provider's SDK and `raw` to `loginWithProviderIdToken`.\n */\nexport interface ProviderNonce {\n /**\n * The raw nonce: at least 32 CSPRNG bytes, base64url without padding. A\n * credential (§37.6) — held behind {@link Sensitive}, and to be kept only for\n * the length of the sign-in attempt.\n */\n raw: Sensitive<string>;\n /** `SHA-256(raw)` as 64 lower-case hexadecimal characters; not a secret. */\n hashed: string;\n}\n"]}
|