axiam-sdk 1.0.0-alpha19 → 1.0.0-alpha21
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 +155 -4
- package/dist/amqp/index.d.cts +1 -1
- package/dist/amqp/index.d.ts +1 -1
- package/dist/amqp/index.js +4 -0
- package/dist/amqp/index.js.map +1 -1
- package/dist/amqp/index.mjs +4 -0
- package/dist/amqp/index.mjs.map +1 -1
- package/dist/{authzCore-CcTdIf78.d.ts → authzCore-DtSN59if.d.ts} +2 -2
- package/dist/{authzCore-B7GSd3-t.d.cts → authzCore-DuRI1aJf.d.cts} +2 -2
- package/dist/client-B_FqmZ0i.d.cts +72 -0
- package/dist/client-Dn1fs5MH.d.ts +72 -0
- package/dist/cookieJar-BTDnjjbL.d.cts +122 -0
- package/dist/cookieJar-Cl8Lq9dL.d.ts +122 -0
- package/dist/grpc/index.d.cts +6 -5
- package/dist/grpc/index.d.ts +6 -5
- package/dist/grpc/index.js +178 -4
- package/dist/grpc/index.js.map +1 -1
- package/dist/grpc/index.mjs +178 -4
- package/dist/grpc/index.mjs.map +1 -1
- package/dist/index.d.cts +4 -2
- package/dist/index.d.ts +4 -2
- package/dist/index.js +76 -3
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +71 -4
- package/dist/index.mjs.map +1 -1
- package/dist/jwks-BgojMGC5.d.cts +152 -0
- package/dist/jwks-BgojMGC5.d.ts +152 -0
- package/dist/middleware/index.d.cts +194 -4
- package/dist/middleware/index.d.ts +194 -4
- package/dist/middleware/index.js +1107 -1
- package/dist/middleware/index.js.map +1 -1
- package/dist/middleware/index.mjs +1100 -3
- package/dist/middleware/index.mjs.map +1 -1
- package/dist/nestjs/index.d.cts +2 -2
- package/dist/nestjs/index.d.ts +2 -2
- package/dist/nestjs/index.js +3 -0
- package/dist/nestjs/index.js.map +1 -1
- package/dist/nestjs/index.mjs +3 -0
- package/dist/nestjs/index.mjs.map +1 -1
- package/dist/node/index.d.cts +50 -113
- package/dist/node/index.d.ts +50 -113
- package/dist/node/index.js +873 -4
- package/dist/node/index.js.map +1 -1
- package/dist/node/index.mjs +857 -5
- package/dist/node/index.mjs.map +1 -1
- package/dist/oidcState-BGxqWUun.d.cts +598 -0
- package/dist/oidcState-CkFuCjpM.d.ts +598 -0
- package/dist/rest/index.d.cts +107 -5
- package/dist/rest/index.d.ts +107 -5
- package/dist/rest/index.js +76 -3
- package/dist/rest/index.js.map +1 -1
- package/dist/rest/index.mjs +71 -4
- package/dist/rest/index.mjs.map +1 -1
- package/dist/sensitive-BC_s7Rrd.d.cts +39 -0
- package/dist/sensitive-BC_s7Rrd.d.ts +39 -0
- package/dist/{client-Co_baHgU.d.ts → session-BWUWhhyB.d.cts} +1 -70
- package/dist/{client-CzhzwRGg.d.cts → session-BWUWhhyB.d.ts} +1 -70
- package/package.json +2 -2
- package/dist/jwks-B8dPy2c6.d.cts +0 -36
- package/dist/jwks-B8dPy2c6.d.ts +0 -36
- package/dist/sensitive-CWBH_tHr.d.cts +0 -12
- package/dist/sensitive-CWBH_tHr.d.ts +0 -12
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/core/errors.ts","../../src/middleware/authzCore.ts","../../src/middleware/cookieHeader.ts","../../src/middleware/verifyCore.ts","../../src/middleware/express.ts","../../src/middleware/fastify.ts"],"names":["authzDeniedBody","missingCredentialsBody","invalidTokenBody","csrfDeniedBody"],"mappings":";;;AASO,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;AAEO,IAAM,SAAA,GAAN,MAAM,UAAA,SAAkB,UAAA,CAAW;AAAA,EACxC,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,C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,MAAM,YAAa,OAAA,CAAgC,SAAA;AACnD,IAAA,IAAI,CAAC,SAAA,EAAW;AACd,MAAA,MAAM,MAAM,IAAA,CAAK,GAAG,CAAA,CAAE,IAAA,CAAK,iBAAiB,CAAA;AAC5C,MAAA;AAAA,IACF;AACA,IAAA,IAAI,CAAC,UAAA,CAAW,SAAA,CAAU,KAAA,EAAO,KAAK,CAAA,EAAG;AACvC,MAAA,MAAM,MAAM,IAAA,CAAK,GAAG,EAAE,IAAA,CAAK,eAAA,CAAsB,uBAAuB,CAAC,CAAA;AACzE,MAAA;AAAA,IACF;AAAA,EACF,CAAA;AACF","file":"index.mjs","sourcesContent":["// AxiamError taxonomy (CONTRACT.md §2, D-16).\n//\n// Exactly three concrete error types: AuthError, AuthzError, NetworkError,\n// all extending the abstract AxiamError base. No error message or field may\n// embed a raw token string (D-16). The prototype chain is fixed up manually\n// in each constructor so `instanceof` works reliably across the transpiled\n// CJS+ESM outputs (a well-known TS-to-ES5/ES2022-target caveat when\n// extending built-ins like Error).\n\nexport abstract class AxiamError extends Error {\n protected constructor(message: string) {\n super(message);\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport class AuthError extends AxiamError {\n constructor(message: string) {\n super(message);\n this.name = 'AuthError';\n Object.setPrototypeOf(this, AuthError.prototype);\n }\n}\n\nexport class AuthzError extends AxiamError {\n readonly action?: string;\n readonly resourceId?: string;\n\n constructor(message: string, action?: string, resourceId?: string) {\n super(message);\n this.name = 'AuthzError';\n this.action = action;\n this.resourceId = resourceId;\n Object.setPrototypeOf(this, AuthzError.prototype);\n }\n}\n\nexport class NetworkError extends AxiamError {\n readonly cause?: unknown;\n\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = 'NetworkError';\n this.cause = cause;\n Object.setPrototypeOf(this, NetworkError.prototype);\n }\n}\n","// 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 } 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\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 | {\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): Promise<CheckOutcome> {\n try {\n const decision = await checker.checkAccess({ action, resourceId, scope, subjectId });\n if (!decision.allowed) {\n return { kind: 'denied', message: decision.reason ?? 'access denied' };\n }\n return { kind: 'allowed' };\n } catch (err) {\n if (err instanceof AuthzError) {\n return { kind: 'denied', message: err.message };\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/** 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","// 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 type { Verifier } from '../node/jwks.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.\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 /** The tenant this resource server is configured for (CR-03); a validly-signed token minted for a different tenant in the same org is rejected. */\n tenantHeaderValue: string;\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 * Throws `AuthError` on any verification failure (missing/invalid/expired\n * token, or a malformed sub/tenant_id claim).\n */\nexport async function authenticateRequest(\n session: VerifiableSession,\n token: string,\n): Promise<AxiamIdentity> {\n let claims;\n try {\n claims = await session.jwksVerifier.verifyAccessToken(token);\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 if (!claims.tenant_id) {\n throw new AuthError('invalid tenant_id claim');\n }\n // CR-03: JWKS is org-wide (node/jwks.ts), so signature validity alone does\n // NOT imply the token was minted for THIS resource server's tenant.\n // Enforce equality after the presence checks to preserve their error\n // messages/ordering.\n if (claims.tenant_id !== session.tenantHeaderValue) {\n throw new AuthError('token tenant_id does not match configured tenant');\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 { 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 return async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n const credential = extractCredential(req.headers.cookie, req.headers.authorization);\n if (!credential) {\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 const identity = await authenticateRequest(session, credential.token);\n (req as AxiamRequest).axiamUser = identity;\n next();\n } catch (err) {\n if (err instanceof AuthzError) {\n res.status(403).json(authzDeniedBody(err.message));\n return;\n }\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\n return async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n const axiamUser = (req as AxiamRequest).axiamUser;\n if (!axiamUser) {\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(checker, action, resourceId, axiamUser.userId, opts?.scope);\n if (outcome.kind === 'denied') {\n opts?.logger?.debug('axiam_sdk.authz', 'access denied', { action, resourceId });\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`. `session` is accepted only for\n * signature parity with `requireAuth`/`requireAccess` (every §11 helper\n * takes the session first) — this check never dereferences it. Cheaper but\n * coarser than `requireAccess`; NOT a substitute for a resource-level check.\n */\nexport function requireRole(session: VerifiableSession, ...roles: string[]): RequestHandler {\n void session;\n return (req: Request, res: Response, next: NextFunction): void => {\n const axiamUser = (req as AxiamRequest).axiamUser;\n if (!axiamUser) {\n res.status(401).json(missingAuthBody());\n return;\n }\n if (!hasAnyRole(axiamUser.roles, roles)) {\n res.status(403).json(authzDeniedBodyShared('missing required role'));\n return;\n }\n next();\n };\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 { 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): PreHandlerHook {\n return async (request: FastifyRequest, reply: FastifyReply) => {\n const credential = extractCredential(request.headers.cookie, request.headers.authorization);\n if (!credential) {\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 const identity = await authenticateRequest(session, credential.token);\n (request as AxiamFastifyRequest).axiamUser = identity;\n } catch (err) {\n if (err instanceof AuthzError) {\n await reply.code(403).send(authzDeniedBody(err.message));\n return;\n }\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 const plugin: FastifyPluginAsync = async (fastify) => {\n fastify.addHook('preHandler', buildAuthHook(session));\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);\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\n return async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n const axiamUser = (request as AxiamFastifyRequest).axiamUser;\n if (!axiamUser) {\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(checker, action, resourceId, axiamUser.userId, opts?.scope);\n if (outcome.kind === 'denied') {\n opts?.logger?.debug('axiam_sdk.authz', 'access denied', { action, resourceId });\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 accepted only for signature parity with\n * `requireAuthHook`/`requireAccessHook` — this check never dereferences it.\n */\nexport function requireRoleHook(session: VerifiableSession, ...roles: string[]): PreHandlerHook {\n void session;\n return async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n const axiamUser = (request as AxiamFastifyRequest).axiamUser;\n if (!axiamUser) {\n await reply.code(401).send(missingAuthBody());\n return;\n }\n if (!hasAnyRole(axiamUser.roles, roles)) {\n await reply.code(403).send(authzDeniedBodyShared('missing required role'));\n return;\n }\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/core/errors.ts","../../src/core/errorMapper.ts","../../src/core/sensitive.ts","../../src/middleware/authzCore.ts","../../src/middleware/cookieHeader.ts","../../src/middleware/oidcLoginCore.ts","../../src/middleware/verifyCore.ts","../../src/middleware/express.ts","../../src/middleware/fastify.ts","../../src/node/oidcIdToken.ts","../../src/node/jwks.ts","../../src/node/oidcPkce.ts","../../src/node/oidc.ts","../../src/node/oidcState.ts"],"names":["invalidRequestBody","authzDeniedBody","missingCredentialsBody","invalidTokenBody","csrfDeniedBody","sendOidcOutcome","timingSafeEqual"],"mappings":";;;AAyBO,IAAe,UAAA,GAAf,cAAkC,KAAA,CAAM;AAAA,EACnC,YAAY,OAAA,EAAiB;AACrC,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,GAAA,CAAA,MAAA,CAAW,SAAS,CAAA;AAAA,EAClD;AACF,CAAA;AAOO,IAAM,SAAA,GAAN,MAAM,UAAA,SAAkB,UAAA,CAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAU/B,MAAA;AAAA,EAET,WAAA,CAAY,SAAiB,MAAA,EAAiB;AAC5C,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,MA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AAA,EACF;AACF","file":"index.mjs","sourcesContent":["// AxiamError taxonomy (CONTRACT.md §2, D-16).\n//\n// Three concrete TOP-LEVEL error types: AuthError, AuthzError, NetworkError,\n// all extending the abstract AxiamError base. §2 additionally permits\n// language-idiomatic SUB-TYPES of those three (they never replace them):\n// this module ships one, `OAuthProtocolError extends AuthError`, mandated by\n// §12.3 rule 3 for `OAuth2ErrorResponse` bodies returned by `/oauth2/*`.\n// `instanceof AuthError` therefore still matches every authentication\n// failure, including OAuth2 protocol errors — that backward compatibility is\n// what makes contract 1.4 additive rather than breaking.\n//\n// No error message or field may embed a raw token string, client secret, or\n// code verifier (D-16, §12.3 rule 3). The prototype chain is fixed up\n// manually in each constructor so `instanceof` works reliably across the\n// transpiled CJS+ESM outputs (a well-known TS-to-ES5/ES2022-target caveat\n// when extending built-ins like Error).\n\n/**\n * Base class of every error this SDK throws (CONTRACT.md §2).\n *\n * Catch this to handle any AXIAM failure uniformly; catch one of the three\n * concrete subclasses — {@link AuthError}, {@link AuthzError},\n * {@link NetworkError} — to distinguish authentication, authorization and\n * transport failures.\n */\nexport abstract class AxiamError extends Error {\n protected constructor(message: string) {\n super(message);\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Authentication failure (CONTRACT.md §2): wrong credentials, an expired\n * session, a failed MFA challenge, a `401` on refresh, or a failed ID-token\n * validation.\n */\nexport class AuthError extends AxiamError {\n /**\n * Optional stable, machine-readable reason code for the failure.\n *\n * Populated by the CONTRACT.md §12.4 ID-token validation checklist with\n * one of the seven codes §12.3 rule 3 enumerates (see\n * {@link IdTokenFailureReason}); `undefined` for every other `AuthError`.\n * It is a *code*, never free text, so callers can branch on it without\n * parsing `message`.\n */\n readonly reason?: string;\n\n constructor(message: string, reason?: string) {\n super(message);\n this.name = 'AuthError';\n this.reason = reason;\n Object.setPrototypeOf(this, AuthError.prototype);\n }\n}\n\n/**\n * The seven stable reason codes CONTRACT.md §12.3 rule 3 defines for\n * ID-token validation failures, one per §12.4 rule. Surfaced on\n * {@link AuthError.reason}.\n */\nexport type IdTokenFailureReason =\n | 'invalid_alg'\n | 'unknown_kid'\n | 'invalid_signature'\n | 'invalid_issuer'\n | 'invalid_audience'\n | 'token_expired'\n | 'nonce_mismatch';\n\n/**\n * An RFC 6749 protocol error returned by an `/oauth2/*` endpoint as an\n * `OAuth2ErrorResponse` body (CONTRACT.md §2 sub-type table, §12.3 rule 3).\n *\n * @remarks\n * A **sub-type of {@link AuthError}**, not a replacement for it: existing\n * `catch (e) { if (e instanceof AuthError) … }` code keeps working unchanged.\n * Raised for a `400` from `POST /oauth2/token` (e.g. `invalid_grant`) and for\n * a `401` from `POST /oauth2/introspect` / `POST /oauth2/revoke` (client\n * authentication failed) — neither of which may collapse into the generic\n * §2 `400 → NetworkError` / `401 → AuthError` rows.\n *\n * `message` is always exactly `\"<error>: <error_description>\"`, built from\n * the two wire fields, which are also exposed individually.\n *\n * @example\n * ```ts\n * try {\n * await oidc.oidcExchange({ code, codeVerifier, nonce, redirectUri });\n * } catch (err) {\n * if (err instanceof OAuthProtocolError && err.error === 'invalid_grant') {\n * // the authorization code was replayed, expired, or bound to another client\n * }\n * }\n * ```\n */\nexport class OAuthProtocolError extends AuthError {\n /** The RFC 6749 `error` code (e.g. `\"invalid_grant\"`, `\"invalid_client\"`, `\"unsupported_grant_type\"`). */\n readonly error: string;\n /** The server's human-readable `error_description`. Never contains token material. */\n readonly errorDescription: string;\n\n constructor(error: string, errorDescription: string) {\n super(`${error}: ${errorDescription}`);\n this.name = 'OAuthProtocolError';\n this.error = error;\n this.errorDescription = errorDescription;\n Object.setPrototypeOf(this, OAuthProtocolError.prototype);\n }\n}\n\n/**\n * Authorization failure (CONTRACT.md §2): the caller is authenticated but\n * lacks permission for the requested operation (`403`, or `409` for a\n * resource-level denial).\n */\nexport class AuthzError extends AxiamError {\n /** The denied action, when the server reported it. */\n readonly action?: string;\n /** The resource the denied action targeted, when the server reported it. */\n readonly resourceId?: string;\n\n constructor(message: string, action?: string, resourceId?: string) {\n super(message);\n this.name = 'AuthzError';\n this.action = action;\n this.resourceId = resourceId;\n Object.setPrototypeOf(this, AuthzError.prototype);\n }\n}\n\n/**\n * Transport-level failure (CONTRACT.md §2): connection refused, timeout, TLS\n * or DNS error, a malformed request (`400`), rate limiting (`429`), or a `5xx`\n * server error.\n */\nexport class NetworkError extends AxiamError {\n /** The underlying transport error, with every non-allowlisted response header redacted (§2, X-3). */\n readonly cause?: unknown;\n\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = 'NetworkError';\n this.cause = cause;\n Object.setPrototypeOf(this, NetworkError.prototype);\n }\n}\n","// Central status -> error mapper (CONTRACT.md §2, D-17).\n//\n// The single source of truth for both rest/ and grpc/ transports so the two\n// cannot drift on the error taxonomy. Transcribes CONTRACT.md §2's HTTP and\n// gRPC tables exactly.\n//\n// GrpcStatus is exported here (not imported from @grpc/grpc-js) so that\n// core stays dependency-free — grpc/ imports the numeric codes from core\n// rather than the other way around.\n\nimport {\n AuthError,\n AuthzError,\n NetworkError,\n OAuthProtocolError,\n type AxiamError,\n} from './errors.js';\n\n/** gRPC status codes referenced by CONTRACT.md §2 (subset of the full grpc.status enum). */\nexport const GrpcStatus = {\n DEADLINE_EXCEEDED: 4,\n PERMISSION_DENIED: 7,\n RESOURCE_EXHAUSTED: 8,\n INTERNAL: 13,\n UNAVAILABLE: 14,\n UNAUTHENTICATED: 16,\n} as const;\n\nexport interface HttpErrorContext {\n action?: string;\n resourceId?: string;\n cause?: unknown;\n /**\n * The request URL (absolute or path-only) the error came from, when\n * available. Load-bearing for the two **endpoint-qualified** rows of §2's\n * HTTP table (added by contract 1.4): a `400`/`401` carrying an\n * `OAuth2ErrorResponse` body maps to `OAuthProtocolError` only when it came\n * from an `/oauth2/*` endpoint. Omitting it simply keeps the generic rows.\n */\n url?: string;\n /**\n * The parsed JSON response body (when available). For a 403/409\n * authorization-denied response the server shapes this as\n * `{ error: \"authorization_denied\", message, action?, resource_id? }`\n * (`action` present when known, `resource_id` present only for a\n * resource-scoped denial). `mapHttpStatusToError` prefers these body\n * fields over `action`/`resourceId` above when populating `AuthzError`.\n */\n body?: unknown;\n}\n\n/**\n * Extract `action`/`resource_id` (snake_case -> camelCase) from a parsed\n * authorization-denied response body, if present and string-typed. Any other\n * shape (missing fields, non-object body, older servers with no body at all)\n * yields `{}`, so callers fall back to caller-supplied context.\n */\nfunction extractAuthzFieldsFromBody(body: unknown): { action?: string; resourceId?: string } {\n if (body === null || typeof body !== 'object') {\n return {};\n }\n const record = body as Record<string, unknown>;\n const action = typeof record.action === 'string' ? record.action : undefined;\n const resourceId = typeof record.resource_id === 'string' ? record.resource_id : undefined;\n return { action, resourceId };\n}\n\n/**\n * The RFC 6749 error body shape (`OAuth2ErrorResponse` in `openapi.json`)\n * returned by AXIAM's `/oauth2/*` endpoints. Both fields are required by the\n * schema.\n */\nexport interface OAuth2ErrorResponseWire {\n /** RFC 6749 error code, e.g. `invalid_grant`. */\n error: string;\n /** Human-readable description of the failure. */\n error_description: string;\n}\n\n/**\n * Path prefix identifying AXIAM's OAuth2 endpoint family (`/oauth2/token`,\n * `/oauth2/introspect`, `/oauth2/revoke`, …). The two endpoint-qualified §2\n * rows apply only to URLs whose path starts with it.\n */\nconst OAUTH2_PATH_PREFIX = '/oauth2/';\n\n/**\n * Whether `url` targets an `/oauth2/*` endpoint. Accepts both an absolute URL\n * (as taken from the discovery document) and a bare path (as axios request\n * configs carry), and never throws on a malformed value — an unparseable URL\n * simply falls back to a substring test, so a mis-shaped URL can only ever\n * *fail* to qualify for the OAuth2 rows, never wrongly qualify for them.\n */\nexport function isOAuth2EndpointUrl(url: string | undefined): boolean {\n if (!url) {\n return false;\n }\n try {\n // A relative path has no base here, so `URL` throws and we fall through.\n return new URL(url).pathname.startsWith(OAUTH2_PATH_PREFIX);\n } catch {\n return url.startsWith(OAUTH2_PATH_PREFIX) || url.includes(OAUTH2_PATH_PREFIX);\n }\n}\n\n/**\n * Narrow a parsed response body to {@link OAuth2ErrorResponseWire}. Both\n * `error` and `error_description` must be present and string-typed — a body\n * that carries only one of them is NOT an `OAuth2ErrorResponse` and keeps the\n * generic §2 mapping (better a generic error than a fabricated\n * `error_description`).\n */\nexport function isOAuth2ErrorBody(body: unknown): body is OAuth2ErrorResponseWire {\n if (body === null || typeof body !== 'object') {\n return false;\n }\n const record = body as Record<string, unknown>;\n return typeof record.error === 'string' && typeof record.error_description === 'string';\n}\n\n/**\n * ALLOWLIST (X-3) of response headers that are safe to preserve in a\n * NetworkError.cause. Every header NOT listed here has its value redacted to a\n * placeholder, so a custom sensitive header (e.g. `X-Auth-Token`) can never\n * survive into a thrown error — unlike a small denylist, which only catches the\n * headers it happens to enumerate. Names are compared case-insensitively (all\n * entries are lower-case). Keep this list small and strictly non-secret:\n * standard diagnostic response headers plus this SDK's own non-secret request\n * headers (e.g. `x-tenant-id`).\n */\nconst SAFE_RESPONSE_HEADERS = new Set([\n 'content-type',\n 'content-length',\n 'date',\n 'server',\n 'retry-after',\n 'x-request-id',\n 'x-tenant-id',\n]);\n\n/** Placeholder substituted for the value of any non-allowlisted header. */\nconst REDACTED_HEADER = '[REDACTED]';\n\n/**\n * Redact every non-allowlisted response header from an axios-error-shaped\n * `err` before it is attached as `NetworkError.cause` (CR-04, D-16, X-3). On\n * login/refresh error paths the server may have already issued Set-Cookie\n * headers containing raw `axiam_access`/`axiam_refresh` values (and callers may\n * set custom sensitive headers such as `X-Auth-Token`); none of these must be\n * reachable via `console.log`/`JSON.stringify`/`util.inspect` of the thrown\n * error. Only headers on `SAFE_RESPONSE_HEADERS` keep their value; all others\n * are replaced with `[REDACTED]`.\n *\n * Returns a new, shallow-cloned object for any input shaped like\n * `{ response: { headers: {...} } }` — the caller's original axios error\n * object is left untouched. Non-object inputs (plain Error, string,\n * undefined) and objects with no `response.headers` are returned unchanged.\n */\nexport function sanitizeAxiosError(err: unknown): unknown {\n if (err === null || typeof err !== 'object') {\n return err;\n }\n const candidate = err as { response?: unknown };\n if (candidate.response === null || typeof candidate.response !== 'object') {\n return err;\n }\n const response = candidate.response as { headers?: unknown };\n if (response.headers === null || typeof response.headers !== 'object') {\n return err;\n }\n\n const sanitizedHeaders: Record<string, unknown> = { ...(response.headers as Record<string, unknown>) };\n for (const key of Object.keys(sanitizedHeaders)) {\n if (!SAFE_RESPONSE_HEADERS.has(key.toLowerCase())) {\n sanitizedHeaders[key] = REDACTED_HEADER;\n }\n }\n\n return {\n ...err,\n response: {\n ...response,\n headers: sanitizedHeaders,\n },\n };\n}\n\n/**\n * Map an HTTP status code to an AxiamError variant per CONTRACT.md §2's HTTP\n * status table.\n *\n * | Status | Type |\n * |-----------|--------------|\n * | 400 | NetworkError |\n * | 400 from `/oauth2/*` with an `OAuth2ErrorResponse` body | OAuthProtocolError |\n * | 401 | AuthError |\n * | 401 from `/oauth2/*` with an `OAuth2ErrorResponse` body | OAuthProtocolError |\n * | 403 | AuthzError |\n * | 408, 429 | NetworkError |\n * | 409 | AuthzError |\n * | 5xx | NetworkError |\n * | other | NetworkError |\n *\n * Where two rows match the same response the more specific\n * (endpoint- and body-qualified) row wins, per §2 — so the two\n * `OAuthProtocolError` rows are evaluated first. They require BOTH an\n * `/oauth2/*` `ctx.url` AND an `OAuth2ErrorResponse`-shaped `ctx.body`;\n * anything else keeps the generic mapping.\n *\n * NetworkError's `cause` (when provided via `ctx.cause`) is always passed\n * through `sanitizeAxiosError` first (CR-04) — this is the single choke\n * point for both rest/ auth call sites and any future caller.\n *\n * For 403/409, `action`/`resourceId` are sourced from the response body\n * (`ctx.body`) when the body carries them, falling back to the\n * caller-supplied `ctx.action`/`ctx.resourceId` (the request call-args)\n * otherwise — this keeps compatibility with older servers that don't yet\n * echo `action`/`resource_id` in the denial body.\n */\nexport function mapHttpStatusToError(\n status: number,\n message: string,\n ctx?: HttpErrorContext,\n): AxiamError {\n // Endpoint-qualified rows first (§2 \"the more specific row wins\",\n // §12.3 rule 3). `message` is deliberately ignored here: the contract fixes\n // OAuthProtocolError's message to \"<error>: <error_description>\".\n if ((status === 400 || status === 401) && isOAuth2EndpointUrl(ctx?.url) && isOAuth2ErrorBody(ctx?.body)) {\n return new OAuthProtocolError(ctx.body.error, ctx.body.error_description);\n }\n if (status === 401) {\n return new AuthError(message);\n }\n if (status === 403 || status === 409) {\n const fromBody = extractAuthzFieldsFromBody(ctx?.body);\n return new AuthzError(message, fromBody.action ?? ctx?.action, fromBody.resourceId ?? ctx?.resourceId);\n }\n // 400, 408, 429, 5xx, and any other status fall through to NetworkError.\n return new NetworkError(message, sanitizeAxiosError(ctx?.cause));\n}\n\n/**\n * Map a gRPC status code to an AxiamError variant per CONTRACT.md §2's gRPC\n * status table.\n *\n * | Code | Type |\n * |------------------------|--------------|\n * | 16 UNAUTHENTICATED | AuthError |\n * | 7 PERMISSION_DENIED | AuthzError |\n * | 14 UNAVAILABLE | NetworkError |\n * | 4 DEADLINE_EXCEEDED | NetworkError |\n * | 13 INTERNAL | NetworkError |\n * | 8 RESOURCE_EXHAUSTED | NetworkError |\n * | other | NetworkError |\n */\nexport function mapGrpcStatusToError(code: number, message: string): AxiamError {\n if (code === GrpcStatus.UNAUTHENTICATED) {\n return new AuthError(message);\n }\n if (code === GrpcStatus.PERMISSION_DENIED) {\n return new AuthzError(message);\n }\n return new NetworkError(message);\n}\n","// Sensitive<T> — token-redaction wrapper (CONTRACT.md §7, D-26).\n//\n// Redacts to '[SENSITIVE]' across all three JS stringification surfaces:\n// toString(), JSON.stringify() (via toJSON), and Node's\n// util.inspect/console.log (via the well-known Symbol.for('nodejs.util.inspect.custom')\n// symbol). The symbol is referenced directly (not via `import { inspect } from\n// 'node:util'`) so core never imports node:util and stays runtime-agnostic —\n// the symbol lookup is a documented no-op in browsers, where this class is\n// never constructed anyway (D-06: browser persona holds no tokens).\n//\n// The raw value is reachable only via `expose()`, documented @internal.\n\nexport const REDACTED = '[SENSITIVE]';\n\nconst NODE_INSPECT_CUSTOM = Symbol.for('nodejs.util.inspect.custom');\n\n/**\n * A redaction wrapper for token and secret material (CONTRACT.md §7).\n *\n * @remarks\n * The wrapped value is held in a private class field, so it cannot be reached\n * through any public property. All three JavaScript stringification surfaces\n * redact it to `\"[SENSITIVE]\"`: `toString()`, `JSON.stringify()` and\n * `console.log`/`util.inspect`. The raw value is available only via the\n * documented-`@internal` `expose()` accessor, which SDK-internal code calls at\n * the point of handing the value to the transport.\n *\n * Every field CONTRACT.md §12.5 names — `access_token`, `refresh_token`,\n * `id_token`, `client_secret`, `code_verifier` — is wrapped in this class. By\n * contrast `state` and `nonce` are **not** secrets (§12.3 rule 2) and stay\n * plain strings.\n *\n * @example\n * ```ts\n * const tokens = await oidc.oidcExchange({ code, codeVerifier, nonce, redirectUri });\n * console.log(tokens.accessToken); // [SENSITIVE]\n * JSON.stringify(tokens); // {\"accessToken\":\"[SENSITIVE]\",…}\n * ```\n */\nexport class Sensitive<T> {\n readonly #value: T;\n\n /** Wrap `value` so it can never be logged or serialized by accident. */\n constructor(value: T) {\n this.#value = value;\n }\n\n /** @internal package-only accessor. Never pass the return value to a log/serialize sink. */\n expose(): T {\n return this.#value;\n }\n\n /** Returns the `\"[SENSITIVE]\"` placeholder — never the wrapped value. */\n toString(): string {\n return REDACTED;\n }\n\n /** Makes `JSON.stringify()` emit the `\"[SENSITIVE]\"` placeholder. */\n toJSON(): string {\n return REDACTED;\n }\n\n /** Makes `console.log`/`util.inspect` print the `\"[SENSITIVE]\"` placeholder. */\n [NODE_INSPECT_CUSTOM](): string {\n return REDACTED;\n }\n}\n","// 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 } 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\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 | {\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): Promise<CheckOutcome> {\n try {\n const decision = await checker.checkAccess({ action, resourceId, scope, subjectId });\n if (!decision.allowed) {\n return { kind: 'denied', message: decision.reason ?? 'access denied' };\n }\n return { kind: 'allowed' };\n } catch (err) {\n if (err instanceof AuthzError) {\n return { kind: 'denied', message: err.message };\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/** 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","// 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","// 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 type { Verifier } from '../node/jwks.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.\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 /** The tenant this resource server is configured for (CR-03); a validly-signed token minted for a different tenant in the same org is rejected. */\n tenantHeaderValue: string;\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 * Throws `AuthError` on any verification failure (missing/invalid/expired\n * token, or a malformed sub/tenant_id claim).\n */\nexport async function authenticateRequest(\n session: VerifiableSession,\n token: string,\n): Promise<AxiamIdentity> {\n let claims;\n try {\n claims = await session.jwksVerifier.verifyAccessToken(token);\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 if (!claims.tenant_id) {\n throw new AuthError('invalid tenant_id claim');\n }\n // CR-03: JWKS is org-wide (node/jwks.ts), so signature validity alone does\n // NOT imply the token was minted for THIS resource server's tenant.\n // Enforce equality after the presence checks to preserve their error\n // messages/ordering.\n if (claims.tenant_id !== session.tenantHeaderValue) {\n throw new AuthError('token tenant_id does not match configured tenant');\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 beginOidcLogin,\n completeOidcLogin,\n type OidcLoginOptions,\n type OidcLoginOutcome,\n} from './oidcLoginCore.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 return async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n const credential = extractCredential(req.headers.cookie, req.headers.authorization);\n if (!credential) {\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 const identity = await authenticateRequest(session, credential.token);\n (req as AxiamRequest).axiamUser = identity;\n next();\n } catch (err) {\n if (err instanceof AuthzError) {\n res.status(403).json(authzDeniedBody(err.message));\n return;\n }\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\n return async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n const axiamUser = (req as AxiamRequest).axiamUser;\n if (!axiamUser) {\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(checker, action, resourceId, axiamUser.userId, opts?.scope);\n if (outcome.kind === 'denied') {\n opts?.logger?.debug('axiam_sdk.authz', 'access denied', { action, resourceId });\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`. `session` is accepted only for\n * signature parity with `requireAuth`/`requireAccess` (every §11 helper\n * takes the session first) — this check never dereferences it. Cheaper but\n * coarser than `requireAccess`; NOT a substitute for a resource-level check.\n */\nexport function requireRole(session: VerifiableSession, ...roles: string[]): RequestHandler {\n void session;\n return (req: Request, res: Response, next: NextFunction): void => {\n const axiamUser = (req as AxiamRequest).axiamUser;\n if (!axiamUser) {\n res.status(401).json(missingAuthBody());\n return;\n }\n if (!hasAnyRole(axiamUser.roles, roles)) {\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 beginOidcLogin,\n completeOidcLogin,\n type OidcLoginOptions,\n type OidcLoginOutcome,\n} from './oidcLoginCore.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): PreHandlerHook {\n return async (request: FastifyRequest, reply: FastifyReply) => {\n const credential = extractCredential(request.headers.cookie, request.headers.authorization);\n if (!credential) {\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 const identity = await authenticateRequest(session, credential.token);\n (request as AxiamFastifyRequest).axiamUser = identity;\n } catch (err) {\n if (err instanceof AuthzError) {\n await reply.code(403).send(authzDeniedBody(err.message));\n return;\n }\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 const plugin: FastifyPluginAsync = async (fastify) => {\n fastify.addHook('preHandler', buildAuthHook(session));\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);\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\n return async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n const axiamUser = (request as AxiamFastifyRequest).axiamUser;\n if (!axiamUser) {\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(checker, action, resourceId, axiamUser.userId, opts?.scope);\n if (outcome.kind === 'denied') {\n opts?.logger?.debug('axiam_sdk.authz', 'access denied', { action, resourceId });\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 accepted only for signature parity with\n * `requireAuthHook`/`requireAccessHook` — this check never dereferences it.\n */\nexport function requireRoleHook(session: VerifiableSession, ...roles: string[]): PreHandlerHook {\n void session;\n return async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {\n const axiamUser = (request as AxiamFastifyRequest).axiamUser;\n if (!axiamUser) {\n await reply.code(401).send(missingAuthBody());\n return;\n }\n if (!hasAnyRole(axiamUser.roles, roles)) {\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","// ID-token claim validation — CONTRACT.md §12.4, OIDC Core §3.1.3.7.\n//\n// PURE logic only: no network, no jose, no crypto beyond a constant-time\n// compare. The signature half of §12.4 (rules 1–2: `alg` allowlist, `kid`\n// lookup, Ed25519 verification, single JWKS re-fetch) lives in node/jwks.ts,\n// on the SAME verifier the §10 middleware already uses — §12 forbids forking\n// it. This module holds rules 3–6 (issuer, audience, time, nonce) plus the\n// reason-code vocabulary, so both halves can be unit-tested independently and\n// ported as one pair.\n//\n// Every failure raises `AuthError` carrying one of the seven stable reason\n// codes from §12.3 rule 3. Rule 7 (all-or-nothing discard) is enforced by the\n// caller — `OidcClient.oidcExchange` never returns a token set whose ID token\n// failed here, so `access_token`/`refresh_token` from the same response are\n// dropped with it.\n\nimport { timingSafeEqual } from 'node:crypto';\nimport { AuthError, type IdTokenFailureReason } from '../core/index.js';\n\n/**\n * The decoded, **already-validated** ID-token claim set carried by\n * {@link OidcTokenSet.idClaims} (CONTRACT.md §12.1).\n *\n * @remarks\n * Claim names are kept verbatim in their JWT/OIDC spelling (`iss`, `sub`,\n * `aud`, …) rather than camelCased: they are protocol identifiers a caller\n * cross-references against OIDC Core, exactly as {@link AxiamClaims} already\n * does for access-token claims. The open index signature is mandated by\n * §12.1 — the ID token's full claim set is not enumerated by `openapi.json`,\n * so unknown claims MUST be preserved and MUST NOT be rejected.\n */\nexport interface IdTokenClaims {\n /** Issuer — matched for exact string equality against the discovery document's `issuer` (§12.4 rule 3). */\n iss: string;\n /** Subject — the authenticated end user's stable identifier at AXIAM. */\n sub: string;\n /** Audience — contains the relying party's `client_id` (§12.4 rule 4). */\n aud: string | string[];\n /** Expiry time (epoch seconds). */\n exp: number;\n /** Issued-at time (epoch seconds). */\n iat: number;\n /** Not-before time (epoch seconds), when the server sends one. */\n nbf?: number;\n /** The `nonce` echoed back from the authorization request (§12.4 rule 6). */\n nonce?: string;\n /** Authorized party — required to equal `client_id` when `aud` holds multiple audiences (§12.4 rule 4). */\n azp?: string;\n /** Any further claim the server sends (e.g. `email`, `preferred_username`) — preserved, never rejected (§12.1). */\n [claim: string]: unknown;\n}\n\n/**\n * What an ID token is checked against by {@link IdTokenVerifier.verifyIdToken}\n * (CONTRACT.md §12.4 rules 3–6).\n */\nexport interface IdTokenExpectations {\n /**\n * The authoritative issuer — always the `issuer` value of the discovery\n * document the token endpoint was read from, never the client base URL\n * (§12.3 rule 6: behind a proxy the two legitimately differ).\n */\n issuer: string;\n /** The relying party's own `client_id`, matched against `aud`/`azp` (rule 4). */\n clientId: string;\n /**\n * The `nonce` returned by `oidcBegin` and passed back into `oidcExchange`.\n *\n * Mandatory for `oidcExchange`. Left `undefined` by `oidcRefresh` and\n * `loginClientCredentials`, which skip rule 6 entirely — OIDC Core §12.2\n * does not require a `nonce` in a refresh-issued ID token.\n */\n nonce?: string;\n /**\n * Permitted clock skew in seconds for `exp`/`iat`/`nbf` (rule 5). Defaults\n * to {@link MAX_CLOCK_SKEW_SEC} and is clamped to it — the contract forbids\n * configuring it *above* 60 s, so a larger value is silently reduced rather\n * than honoured.\n */\n clockSkewSec?: number;\n}\n\n/**\n * Maximum (and default) permitted clock skew in seconds for ID-token time\n * claims. CONTRACT.md §12.4 rule 5 caps this at 60 s and forbids any\n * configuration above the bound.\n */\nexport const MAX_CLOCK_SKEW_SEC = 60;\n\n/**\n * Build the `AuthError` for a §12.4 failure: a stable machine-readable\n * `reason` code plus a human-readable message that — per §12.3 rule 3 and §2's\n * construction rules — never embeds the token, a claim value that could carry\n * secret material, or the expected nonce.\n */\nexport function idTokenAuthError(reason: IdTokenFailureReason, message: string): AuthError {\n return new AuthError(`id_token validation failed (${reason}): ${message}`, reason);\n}\n\n/**\n * Resolve the effective clock skew: the caller's value clamped into\n * `[0, MAX_CLOCK_SKEW_SEC]`, or the maximum when unset.\n */\nexport function resolveClockSkewSec(clockSkewSec?: number): number {\n if (clockSkewSec === undefined) {\n return MAX_CLOCK_SKEW_SEC;\n }\n return Math.min(Math.max(clockSkewSec, 0), MAX_CLOCK_SKEW_SEC);\n}\n\n/**\n * Constant-time string equality, used for the `nonce` comparison §12.4 rule 6\n * requires. A length mismatch short-circuits to `false` (`timingSafeEqual`\n * throws on unequal-length buffers) — the same idiom\n * `middleware/cookieHeader.ts` and `amqp/hmac.ts` already use.\n */\nexport function constantTimeEquals(a: string, b: string): boolean {\n const left = Buffer.from(a, 'utf8');\n const right = Buffer.from(b, 'utf8');\n if (left.length !== right.length) {\n return false;\n }\n return timingSafeEqual(left, right);\n}\n\n/** Reject the JOSE header `alg` unless it is exactly `EdDSA` (§12.4 rule 1). */\nexport const ID_TOKEN_ALG = 'EdDSA';\n\n/**\n * §12.4 rule 1 — algorithm check, run against the JOSE **header** and BEFORE\n * any signature work, so the token can never select its own verification\n * algorithm. `none` is rejected by the same equality test as every other\n * non-`EdDSA` value; it gets no special case and no separate code path.\n */\nexport function assertIdTokenAlg(alg: unknown): void {\n if (alg !== ID_TOKEN_ALG) {\n throw idTokenAuthError(\n 'invalid_alg',\n `expected alg \"${ID_TOKEN_ALG}\", got ${typeof alg === 'string' ? `\"${alg}\"` : 'no alg header'}`,\n );\n }\n}\n\n/**\n * §12.4 rules 3–6 — issuer, audience, time and nonce checks over an\n * already-signature-verified claim set. Returns the claims unchanged on\n * success; throws the matching `AuthError` reason code on the first failure.\n *\n * @param claims the verified JWT payload.\n * @param expectations issuer/client_id/nonce to check against.\n * @param nowSec current time in epoch seconds — injectable so tests can pin it.\n */\nexport function checkIdTokenClaims(\n claims: IdTokenClaims,\n expectations: IdTokenExpectations,\n nowSec: number = Math.floor(Date.now() / 1000),\n): IdTokenClaims {\n const skew = resolveClockSkewSec(expectations.clockSkewSec);\n\n // Rule 3 — exact string comparison. No normalization, no trailing-slash\n // tolerance, no prefix matching.\n if (claims.iss !== expectations.issuer) {\n throw idTokenAuthError('invalid_issuer', 'iss does not equal the discovery document issuer');\n }\n\n // Rule 4 — aud must contain our client_id; with multiple audiences an azp\n // claim must be present and equal to it.\n const audiences = Array.isArray(claims.aud) ? claims.aud : [claims.aud];\n if (!audiences.includes(expectations.clientId)) {\n throw idTokenAuthError('invalid_audience', 'aud does not contain this client_id');\n }\n if (audiences.length > 1 && claims.azp !== expectations.clientId) {\n throw idTokenAuthError(\n 'invalid_audience',\n 'aud holds multiple audiences and azp is absent or does not equal this client_id',\n );\n }\n\n // Rule 5 — exp must be in the future, iat must not be in the future, nbf is\n // honored when present; all within `skew` seconds. `exp` is treated as\n // REQUIRED: a token with no expiry could never satisfy \"exp must be in the\n // future\", so its absence is an expiry failure rather than a free pass.\n if (typeof claims.exp !== 'number') {\n throw idTokenAuthError('token_expired', 'exp claim is missing or not a number');\n }\n if (claims.exp + skew <= nowSec) {\n throw idTokenAuthError('token_expired', 'exp is in the past');\n }\n if (typeof claims.iat !== 'number') {\n throw idTokenAuthError('token_expired', 'iat claim is missing or not a number');\n }\n if (claims.iat - skew > nowSec) {\n throw idTokenAuthError('token_expired', 'iat is in the future');\n }\n if (typeof claims.nbf === 'number' && claims.nbf - skew > nowSec) {\n throw idTokenAuthError('token_expired', 'nbf is in the future');\n }\n\n // Rule 6 — mandatory for oidcExchange, skipped when the caller supplied no\n // expected nonce (oidcRefresh / loginClientCredentials).\n if (expectations.nonce !== undefined) {\n if (typeof claims.nonce !== 'string' || !constantTimeEquals(claims.nonce, expectations.nonce)) {\n throw idTokenAuthError('nonce_mismatch', 'nonce claim is absent or does not match the request nonce');\n }\n }\n\n return claims;\n}\n","// Local JWKS verification (D-11, CONTRACT.md §7 defense-in-depth via\n// explicit algorithm allowlist) — for BOTH inbound access tokens (§10\n// middleware) and relying-party ID tokens (§12.4). One verifier, one cached\n// remote key set, two entry points: `verifyAccessToken` and `verifyIdToken`.\n// §12 explicitly forbids forking this module for the OIDC flow.\n//\n// Endpoint: `{baseUrl}/oauth2/jwks` — organization-wide, NOT tenant-scoped,\n// serving exactly one EdDSA (Ed25519) key in the common case\n// (RESEARCH.md Area 3, mirrors the Rust SDK's src/token/jwks.rs). `jose`'s\n// `createRemoteJWKSet` handles fetch + cache + refetch-on-unknown-kid\n// natively; we use its single-cooldown model rather than porting the Rust\n// SDK's two-timer (TTL + forced-refetch) design (RESEARCH.md Area 3 explicit\n// recommendation).\n//\n// Pitfall 1 (jose is ESM-only): `jose` 5+/6.x ships no CJS entry condition,\n// so a tsup CJS build's transpiled `require('jose')` would throw\n// `ERR_REQUIRE_ESM`. `createVerifier` obtains jose via a dynamic\n// `await import('jose')`, deferring resolution to first call rather than\n// module-load time — this keeps `require('axiam-sdk/grpc')` (or any other\n// CJS entry that reaches this module) from throwing at import time.\n\nimport type { AuthError } from '../core/index.js';\nimport {\n assertIdTokenAlg,\n checkIdTokenClaims,\n ID_TOKEN_ALG,\n idTokenAuthError,\n resolveClockSkewSec,\n type IdTokenClaims,\n type IdTokenExpectations,\n} from './oidcIdToken.js';\n\n/** Verified claims carried by an AXIAM access token (the JWT payload {@link Verifier.verifyAccessToken} returns). */\nexport interface AxiamClaims {\n /** Subject — user ID (UUID). */\n sub: string;\n /** Tenant ID (UUID). */\n tenant_id: string;\n /** Organization ID (UUID), if present. */\n org_id?: string;\n /** Issuer — the AXIAM authorization server that minted the token. */\n iss: string;\n /** Issued-at time (epoch seconds), if present. */\n iat?: number;\n /** Expiry time (epoch seconds); the verifier rejects the token once it has passed. */\n exp: number;\n /** Unique token ID / session id — needed for logout(). */\n jti?: string;\n /** Token audience — \"axiam:user\" | \"axiam:m2m\". */\n aud?: string;\n /** OAuth2 scopes (space-separated). */\n scope?: string;\n}\n\n/** Path (relative to the client base URL) of the org-wide JWKS endpoint. */\nexport const JWKS_PATH = '/oauth2/jwks';\n\nconst COOLDOWN_DURATION_MS = 60_000;\nconst TIMEOUT_DURATION_MS = 5_000;\n\n/** Verifies an AXIAM access token's EdDSA signature against the org-wide remote JWKS. */\nexport interface Verifier {\n /** Verify `token` against the cached JWKS (EdDSA only) and return its claims; rejects any invalid/expired/wrong-algorithm token. */\n verifyAccessToken(token: string): Promise<AxiamClaims>;\n}\n\n/**\n * The relying-party half of the same verifier (CONTRACT.md §12.4): validates\n * an OIDC **ID token** rather than an AXIAM access token.\n *\n * @remarks\n * Kept as its own interface, and *added* to the object {@link createVerifier}\n * returns rather than to {@link Verifier} itself, so existing code that\n * implements `Verifier` (e.g. a hand-rolled test double supplied as\n * `VerifiableSession.jwksVerifier`) keeps compiling — contract 1.4 is\n * additive.\n */\nexport interface IdTokenVerifier {\n /**\n * Validate an OIDC ID token per CONTRACT.md §12.4 and return its claims.\n *\n * Enforces rule 1 (`alg` MUST be `EdDSA`, read from the header *before* any\n * signature work — `none` and every other algorithm rejected), rule 2\n * (Ed25519 signature against the key selected by `kid`, with the single\n * JWKS re-fetch policy §10 already implements), then rules 3–6 via\n * {@link checkIdTokenClaims}. Rejects with `AuthError` carrying the\n * matching §12.3 reason code on the first failure.\n */\n verifyIdToken(token: string, expectations: IdTokenExpectations): Promise<IdTokenClaims>;\n}\n\n/**\n * The concrete verifier {@link createVerifier} / {@link createJwksVerifier}\n * return: one object, one cached remote key set, both the §10 access-token\n * path and the §12.4 ID-token path. §12 forbids a second verifier.\n */\nexport interface JwksVerifier extends Verifier, IdTokenVerifier {}\n\n/**\n * Build a verifier bound to `{baseUrl}/oauth2/jwks`.\n *\n * `jose` is loaded lazily via dynamic `import()` (Pitfall 1 — CJS-safe); the\n * remote JWKS itself is also fetched/cached lazily by `jose`, not eagerly\n * here.\n *\n * For the relying-party (§12) flow use {@link createJwksVerifier} with the\n * `jwks_uri` the discovery document advertises instead of hardcoding\n * {@link JWKS_PATH} — §12.3 rule 6 requires reading the URI from the document.\n */\nexport function createVerifier(baseUrl: string): JwksVerifier {\n return createJwksVerifier(`${baseUrl}${JWKS_PATH}`);\n}\n\n/**\n * Build a verifier bound to an explicit, absolute JWKS URI — the `jwks_uri`\n * value taken from the OIDC discovery document (CONTRACT.md §12.3 rule 6).\n *\n * Identical machinery to {@link createVerifier}: one lazily-resolved\n * `createRemoteJWKSet` singleton per verifier instance, shared by\n * `verifyAccessToken` and `verifyIdToken`.\n */\nexport function createJwksVerifier(jwksUri: string): JwksVerifier {\n // Lazily-resolved singleton so repeated verifyAccessToken() calls reuse\n // the same createRemoteJWKSet cache instead of rebuilding it per call.\n //\n // D-08/D-09 (single-flight, PERF-03): a concurrent invalid-`kid` burst\n // against a cold cache must collapse to exactly ONE network fetch. Proven\n // (not just assumed) by `test/node/jwks.test.ts`'s \"collapses N concurrent\n // verifyAccessToken calls ... to exactly one JWKS fetch\" test, which mocks\n // global `fetch` with a call counter and fires 8 concurrent calls: jose's\n // `createRemoteJWKSet` (see jose's `RemoteJWKSet.reload()`,\n // `this.#pendingFetch ||= fetchJwks(...).then(...)`) ALREADY holds its own\n // internal lazy-promise-singleton around the underlying fetch, so\n // concurrent callers reaching a cold/unknown-kid getter share the same\n // in-flight fetch promise natively — no additional `inFlightFetch` guard\n // is added here (it would be redundant). If a future `jose` upgrade\n // removes that internal guarantee, the burst test above will start\n // failing and an explicit guard (mirroring `jwksPromise`'s shape) must be\n // added at that point.\n let jwksPromise: Promise<ReturnType<typeof import('jose').createRemoteJWKSet>> | null = null;\n\n async function getJwks() {\n if (!jwksPromise) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-imports\n jwksPromise = import('jose').then(({ createRemoteJWKSet }) =>\n createRemoteJWKSet(new URL(jwksUri), {\n cooldownDuration: COOLDOWN_DURATION_MS,\n timeoutDuration: TIMEOUT_DURATION_MS,\n }),\n );\n }\n return jwksPromise;\n }\n\n return {\n async verifyAccessToken(token: string): Promise<AxiamClaims> {\n const { jwtVerify } = await import('jose');\n const jwks = await getJwks();\n // Explicit algorithm allowlist — never trust the token's own `alg`\n // header; defense against algorithm-confusion attacks (T-17-14).\n const { payload } = await jwtVerify(token, jwks, { algorithms: ['EdDSA'] });\n return payload as unknown as AxiamClaims;\n },\n\n async verifyIdToken(token: string, expectations: IdTokenExpectations): Promise<IdTokenClaims> {\n const { decodeProtectedHeader, jwtVerify } = await import('jose');\n\n // §12.4 rule 1 — read `alg` from the header and reject anything but\n // EdDSA BEFORE touching the JWKS or the signature. A malformed token\n // (not three base64url segments) cannot even yield a header, which is\n // itself an `invalid_alg` failure: no algorithm was assertable.\n let header: { alg?: string; kid?: string };\n try {\n header = decodeProtectedHeader(token);\n } catch {\n throw idTokenAuthError('invalid_alg', 'token is not a well-formed JWS');\n }\n assertIdTokenAlg(header.alg);\n\n // §12.4 rule 2 — a token with no `kid` is rejected outright: there is\n // no key to select, and guessing \"the only key\" would defeat rotation.\n if (!header.kid) {\n throw idTokenAuthError('unknown_kid', 'token carries no kid header');\n }\n\n const jwks = await getJwks();\n const skew = resolveClockSkewSec(expectations.clockSkewSec);\n let claims: IdTokenClaims;\n try {\n // `algorithms` is passed again (belt and braces with rule 1) so jose\n // can never be talked into another algorithm either. `clockTolerance`\n // keeps jose's own exp/nbf checks aligned with rule 5's bound; the\n // explicit re-checks in checkIdTokenClaims cover iat and give each\n // failure its own reason code.\n const { payload } = await jwtVerify(token, jwks, {\n algorithms: [ID_TOKEN_ALG],\n clockTolerance: skew,\n });\n claims = payload as unknown as IdTokenClaims;\n } catch (err) {\n throw mapJoseVerifyError(err);\n }\n\n return checkIdTokenClaims(claims, { ...expectations, clockSkewSec: skew });\n },\n };\n}\n\n/**\n * Translate a `jose` verification failure into the §12.3 reason-code\n * vocabulary. jose's error `code` strings are stable public API\n * (`ERR_JWKS_NO_MATCHING_KEY`, `ERR_JWT_EXPIRED`, …); anything unrecognized\n * degrades to `invalid_signature`, the safest catch-all — an unclassifiable\n * verification failure is never treated as success.\n */\nfunction mapJoseVerifyError(err: unknown): AuthError {\n const code = typeof err === 'object' && err !== null && 'code' in err ? String((err as { code: unknown }).code) : '';\n switch (code) {\n case 'ERR_JWKS_NO_MATCHING_KEY':\n // jose has already performed its single re-fetch-then-fail dance here\n // (createRemoteJWKSet reloads once per cooldown window on an unmatched\n // kid) — exactly the §12.4 rule 2 / §10 policy.\n return idTokenAuthError('unknown_kid', 'no JWKS key matches the token kid');\n case 'ERR_JWT_EXPIRED':\n return idTokenAuthError('token_expired', 'exp is in the past');\n case 'ERR_JWT_CLAIM_VALIDATION_FAILED':\n return idTokenAuthError('token_expired', 'a time-based claim (nbf/iat) is not yet valid');\n default:\n return idTokenAuthError('invalid_signature', 'signature verification failed');\n }\n}\n","// PKCE + CSPRNG primitives for the OIDC relying-party flow\n// (CONTRACT.md §12.1 \"oidc_begin inputs and construction\", RFC 7636).\n//\n// Node's `node:crypto` covers everything needed — CSPRNG, SHA-256 and\n// base64url — so §12 adds NO new runtime dependency (plan §6 criterion 4).\n// This module is deliberately tiny, pure and synchronous: `oidc_begin`\n// performs no network I/O (§12.1), and every value here is derived locally.\n//\n// S256 ONLY. `plain` is not implemented, not reachable, and not configurable:\n// there is no code path in this SDK that can emit\n// `code_challenge_method=plain`.\n\nimport { createHash, randomBytes } from 'node:crypto';\nimport { Sensitive } from '../core/index.js';\n\n/**\n * The only PKCE code-challenge method this SDK emits (RFC 7636 §4.2,\n * CONTRACT.md §12.1 rule 3). `plain` is intentionally absent.\n */\nexport const CODE_CHALLENGE_METHOD_S256 = 'S256';\n\n/**\n * Entropy, in bytes, of a generated `state` / `nonce` / `code_verifier`.\n *\n * §12.1 rule 1 requires at least 16 bytes (128 bits) and RECOMMENDS 32;\n * rule 2 RECOMMENDS 32 bytes for the verifier, which base64url-encodes to\n * exactly 43 characters — the minimum RFC 7636 §4.1 length, drawn only from\n * the unreserved set `[A-Za-z0-9-._~]`.\n */\nexport const CSPRNG_BYTES = 32;\n\n/**\n * Generate a URL-safe random token: `bytes` CSPRNG bytes, base64url-encoded\n * **without** padding (RFC 4648 §5 — Node's `'base64url'` encoding never\n * emits `=`).\n *\n * Used for both `state` and `nonce`, which §12.3 rule 2 classes as\n * **non-secret**: they are returned as plain strings, are echoed through the\n * browser's address bar by construction, and are safe to log.\n */\nexport function randomUrlSafeToken(bytes: number = CSPRNG_BYTES): string {\n return randomBytes(bytes).toString('base64url');\n}\n\n/**\n * Generate a fresh PKCE `code_verifier` (RFC 7636 §4.1): 32 CSPRNG bytes\n * base64url-encoded without padding, i.e. 43 characters from the unreserved\n * set.\n *\n * Returned already wrapped in {@link Sensitive} — §12.5 makes the verifier\n * secret **for its whole lifetime**, including while it sits in the\n * `AuthorizationRequest` handed back to the caller and in any\n * `OidcStateStore` entry.\n */\nexport function generateCodeVerifier(): Sensitive<string> {\n return new Sensitive(randomUrlSafeToken(CSPRNG_BYTES));\n}\n\n/**\n * Derive the PKCE `code_challenge` from a verifier:\n * `BASE64URL-ENCODE(SHA256(ASCII(code_verifier)))`, unpadded\n * (RFC 7636 §4.2, CONTRACT.md §12.1 rule 3).\n *\n * The verifier is hashed as ASCII exactly as the RFC specifies. Verified\n * against the RFC 7636 Appendix B test vector in\n * `test/node/oidcPkce.test.ts`, which every SDK must carry (§12.1 rule 3).\n *\n * The challenge is a one-way digest and is **not** secret — it travels in the\n * authorization URL — so it is returned as a plain string.\n */\nexport function computeCodeChallenge(codeVerifier: string): string {\n return createHash('sha256').update(codeVerifier, 'ascii').digest('base64url');\n}\n","// OIDC / SSO relying-party helpers — CONTRACT.md §12 (contract 1.4).\n//\n// The nine canonical §12 operations, under the exact §12.2 TypeScript names:\n// oidcDiscover, oidcBegin, oidcExchange, oidcRefresh, loginClientCredentials,\n// introspect, revoke, ssoStart, ssoComplete.\n//\n// ── Why a separate class instead of methods on AxiamClient ─────────────────\n// `AxiamClient` lives in the browser-safe `src/rest/` core, and CI's SC#1\n// bundle-and-grep gate proves a `/rest` browser bundle pulls in zero Node-only\n// code. These helpers need `node:crypto` (CSPRNG + SHA-256 for PKCE) and\n// `jose` (ID-token verification), so hanging them off `AxiamClient` would drag\n// both into every browser bundle. They therefore live on a Node-only\n// `OidcClient` reached through the `axiam-sdk/node` subpath — the same shape\n// the repo already uses for the gRPC-only operations (`AuthzGrpcClient`,\n// `UserInfoGrpcClient`). §12 fixes the *method names*, not which object hosts\n// them, so this is conformant; an SDK without a browser-bundle constraint\n// (Rust, Python, Go, Java, Kotlin, C#, PHP) SHOULD put the nine methods\n// directly on its existing client, as the plan's T2–T8 items say.\n//\n// Everything else is reuse, not reimplementation (§12 forbids forking):\n// * transport + §2 error mapping + §3 CSRF + §4 cookie jar + §5 tenant\n// header + §6 TLS → the SharedSession/NodeSession axios instance;\n// * §9 single-flight refresh → session.refreshGuard;\n// * §12.4 signature verification → node/jwks.ts's verifier;\n// * §7/§12.5 redaction → core/sensitive.ts.\n\nimport type { AxiosRequestConfig, AxiosResponse } from 'axios';\nimport {\n AuthError,\n AxiamError,\n mapHttpStatusToError,\n NetworkError,\n sanitizeAxiosError,\n Sensitive,\n} from '../core/index.js';\nimport type { SharedSession } from '../rest/session.js';\nimport { createJwksVerifier, type JwksVerifier } from './jwks.js';\nimport type { IdTokenClaims } from './oidcIdToken.js';\nimport {\n CODE_CHALLENGE_METHOD_S256,\n computeCodeChallenge,\n generateCodeVerifier,\n randomUrlSafeToken,\n} from './oidcPkce.js';\nimport type {\n AuthorizationRequest,\n IntrospectParams,\n IntrospectionResponseWire,\n IntrospectionResult,\n LoginClientCredentialsParams,\n OidcBeginParams,\n OidcConfiguration,\n OidcExchangeParams,\n OidcRefreshParams,\n OidcStartResponseWire,\n OidcTokenSet,\n RevokeParams,\n SsoCompleteParams,\n SsoCompleteResult,\n SsoLoginSuccessResponseWire,\n SsoStartParams,\n SsoStartResult,\n TokenResponseWire,\n} from './oidcTypes.js';\n\n/** Path of the OIDC discovery document, relative to the client base URL. */\nexport const DISCOVERY_PATH = '/.well-known/openid-configuration';\n\n/** Path of the federation SSO step-1 endpoint. */\nexport const SSO_START_PATH = '/api/v1/auth/federation/oidc/start';\n\n/** Path of the federation SSO step-2 (callback) endpoint. */\nexport const SSO_CALLBACK_PATH = '/api/v1/auth/federation/oidc/callback';\n\n/**\n * Minimum — and default — discovery-cache TTL. CONTRACT.md §12.3 rule 6 sets\n * a floor of 5 minutes; a smaller configured value is raised to it.\n */\nexport const MIN_DISCOVERY_TTL_MS = 300_000;\n\n/** The `openid` scope, which every authorization request must carry (§12.1 rule 4). */\nconst OPENID_SCOPE = 'openid';\n\n/**\n * The eight query parameters `oidcBegin` owns (§12.1 rule 5). Caller-supplied\n * `extraParams` may add to the authorization request but never override these.\n */\nconst RESERVED_AUTHORIZE_PARAMS = new Set([\n 'response_type',\n 'client_id',\n 'redirect_uri',\n 'scope',\n 'state',\n 'nonce',\n 'code_challenge',\n 'code_challenge_method',\n]);\n\n/** Shape of a UUID, used to reject a slug where §12.3 rule 4 requires a UUID. */\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/** Configuration for {@link OidcClient}. */\nexport interface OidcClientOptions {\n /**\n * The relying party's OAuth2 `client_id`. Used on every grant and matched\n * against the ID token's `aud`/`azp` (§12.4 rule 4).\n */\n clientId: string;\n /**\n * The `client_secret` for a confidential client, held behind\n * {@link Sensitive} (§12.5). Omit for a public client — then it is never\n * added to a form body (§12.1 \"MUST omit rather than send empty/null\").\n *\n * `introspect` and `revoke` REQUIRE it: the server marks `client_secret`\n * non-nullable on both, so a public client cannot call them (§12.1 note 4).\n */\n clientSecret?: Sensitive<string> | string;\n /**\n * Default tenant UUID for the `tenant_id` query parameter the token,\n * introspection and revocation endpoints require. Falls back to the\n * session's configured `tenantId` when it was built in UUID form; a\n * slug-only client must pass `tenantId` per call (§12.3 rule 4).\n */\n tenantId?: string;\n /**\n * Discovery-cache TTL in milliseconds. Defaults to (and is floored at)\n * {@link MIN_DISCOVERY_TTL_MS} — §12.3 rule 6 forbids a TTL under 5 minutes.\n */\n discoveryTtlMs?: number;\n /**\n * Permitted ID-token clock skew in seconds. Defaults to 60 and is clamped to\n * 60 — §12.4 rule 5 forbids configuring it higher.\n */\n clockSkewSec?: number;\n}\n\n/** A cached discovery document together with its expiry. */\ninterface CachedDiscovery {\n document: OidcConfiguration;\n expiresAt: number;\n}\n\n/**\n * Origin-keyed discovery cache with single-flight fetching\n * (CONTRACT.md §12.3 rule 6).\n *\n * @remarks\n * The key is the **normalized scheme + host + port** of the base URL the\n * document was fetched from, so a document fetched from one origin can never\n * be served for another (cross-issuer cache poisoning). The cache is *not*\n * keyed on the tenant, and — because each {@link OidcClient} owns its own\n * instance — it is not shared across tenants either, nor process-global.\n *\n * Single-flight uses the same mechanism §9 prescribes for TypeScript: a shared\n * `Promise` held in a map for the duration of the fetch, cleared on settle, so\n * N concurrent callers produce exactly one HTTP request and all receive the\n * same document (or the same failure).\n *\n * @internal\n */\nclass DiscoveryCache {\n readonly #documents = new Map<string, CachedDiscovery>();\n readonly #inFlight = new Map<string, Promise<OidcConfiguration>>();\n readonly #ttlMs: number;\n\n constructor(ttlMs: number) {\n this.#ttlMs = Math.max(ttlMs, MIN_DISCOVERY_TTL_MS);\n }\n\n async get(originKey: string, fetcher: () => Promise<OidcConfiguration>): Promise<OidcConfiguration> {\n const cached = this.#documents.get(originKey);\n if (cached && cached.expiresAt > Date.now()) {\n return cached.document;\n }\n\n const pending = this.#inFlight.get(originKey);\n if (pending) {\n return pending;\n }\n\n const fetch = fetcher()\n .then((document) => {\n this.#documents.set(originKey, { document, expiresAt: Date.now() + this.#ttlMs });\n return document;\n })\n .finally(() => {\n this.#inFlight.delete(originKey);\n });\n this.#inFlight.set(originKey, fetch);\n return fetch;\n }\n}\n\n/**\n * Normalize a URL to its cache key: lowercased scheme and host with the port\n * always explicit (§12.3 rule 6). `https://IAM.example.com/` and\n * `https://iam.example.com:443/x` therefore share one key, while\n * `http://iam.example.com` gets its own.\n */\nexport function normalizeOrigin(url: string): string {\n const parsed = new URL(url);\n const scheme = parsed.protocol.replace(/:$/, '').toLowerCase();\n const host = parsed.hostname.toLowerCase();\n const defaultPort = scheme === 'https' ? '443' : scheme === 'http' ? '80' : '';\n const port = parsed.port || defaultPort;\n return `${scheme}://${host}:${port}`;\n}\n\n/** Read a secret that the caller may have supplied wrapped or bare. */\nfunction exposeSecret(value: Sensitive<string> | string): string {\n return typeof value === 'string' ? value : value.expose();\n}\n\n/** Pull the HTTP status off an axios-shaped error, if any. */\nfunction axiosStatus(err: unknown): number | undefined {\n if (err && typeof err === 'object' && 'response' in err) {\n return (err as { response?: { status?: number } }).response?.status;\n }\n return undefined;\n}\n\n/** Pull the parsed response body off an axios-shaped error, if any. */\nfunction axiosBody(err: unknown): unknown {\n if (err && typeof err === 'object' && 'response' in err) {\n return (err as { response?: { data?: unknown } }).response?.data;\n }\n return undefined;\n}\n\n/** Best-effort human-readable message from a parsed error body. */\nfunction bodyMessage(body: unknown, fallback: string): string {\n if (body && typeof body === 'object') {\n const record = body as Record<string, unknown>;\n if (typeof record.error_description === 'string') {\n return record.error_description;\n }\n if (typeof record.message === 'string') {\n return record.message;\n }\n }\n return fallback;\n}\n\n/**\n * Map any failure from a §12 wire call onto the §2 taxonomy, routing\n * everything through the single `mapHttpStatusToError` source of truth so the\n * endpoint-qualified `OAuthProtocolError` rows apply (§12.3 rule 3).\n *\n * An error that is *already* an `AxiamError` is passed through untouched: the\n * rest/interceptors.ts response interceptor may have mapped it first (it does\n * exactly that for a 401 on an `/oauth2/*` path), and re-mapping would discard\n * the richer error it built.\n */\nfunction mapOidcError(err: unknown, url: string, fallbackMessage: string): AxiamError {\n if (err instanceof AxiamError) {\n return err;\n }\n const status = axiosStatus(err);\n if (status !== undefined) {\n const body = axiosBody(err);\n return mapHttpStatusToError(status, bodyMessage(body, fallbackMessage), { url, body, cause: err });\n }\n return new NetworkError(fallbackMessage, sanitizeAxiosError(err));\n}\n\n/**\n * The OIDC / SSO relying-party client (CONTRACT.md §12).\n *\n * @remarks\n * Build one with {@link createOidcClient}, passing the same session your\n * `AxiamClient` uses so the cookie jar (§4), TLS configuration (§6), tenant\n * header (§5) and single-flight refresh guard (§9) are shared rather than\n * duplicated.\n *\n * **The caller owns the login state.** `oidcBegin` returns `state`, `nonce`\n * and `codeVerifier`; this class stores none of them (§12.3 rule 1). Keep them\n * in your own HTTP session — or use {@link MemoryOidcStateStore} together with\n * the `oidcLoginHandlers` glue from `axiam-sdk/middleware`, which does that\n * bookkeeping for you.\n *\n * @example\n * ```ts\n * const session = createNodeSession({ baseUrl, tenantId });\n * const oidc = createOidcClient(session, { clientId: 'my-app', clientSecret: secret });\n *\n * // 1. redirect the browser\n * const configuration = await oidc.oidcDiscover();\n * const request = oidc.oidcBegin({ configuration, redirectUri, scope: 'openid profile' });\n * // …store request.state / request.nonce / request.codeVerifier in your session…\n * res.redirect(request.url);\n *\n * // 2. on the callback, having checked the returned `state` matches\n * const tokens = await oidc.oidcExchange({\n * code, codeVerifier: request.codeVerifier, nonce: request.nonce, redirectUri,\n * });\n * console.log(tokens.idClaims?.sub); // validated ID-token subject\n * ```\n */\nexport class OidcClient {\n readonly #session: SharedSession;\n readonly #options: OidcClientOptions;\n readonly #discoveryCache: DiscoveryCache;\n /** One verifier per `jwks_uri` — the same node/jwks.ts implementation the §10 middleware uses. */\n readonly #verifiers = new Map<string, JwksVerifier>();\n /** The access token adopted by `loginClientCredentials({ adoptAsCredential: true })`, if any. */\n #adoptedCredential: Sensitive<string> | null = null;\n #adoptionInterceptorInstalled = false;\n /** In-flight `oidcRefresh`, shared by concurrent callers (§9 rule 2). */\n #pendingRefresh: Promise<OidcTokenSet> | null = null;\n\n constructor(session: SharedSession, options: OidcClientOptions) {\n this.#session = session;\n this.#options = options;\n this.#discoveryCache = new DiscoveryCache(options.discoveryTtlMs ?? MIN_DISCOVERY_TTL_MS);\n }\n\n // -------------------------------------------------------------------------\n // 1. oidcDiscover\n // -------------------------------------------------------------------------\n\n /**\n * `GET /.well-known/openid-configuration` (§12.1) — fetch the OIDC discovery\n * document, cached per origin with a ≥5-minute TTL and single-flight\n * de-duplication of concurrent calls (§12.3 rule 6).\n *\n * The document's own `issuer` is authoritative for ID-token validation and\n * may legitimately differ from `baseUrl` behind a proxy, so a mismatch is\n * never treated as an error.\n */\n async oidcDiscover(): Promise<OidcConfiguration> {\n const originKey = normalizeOrigin(this.#session.baseUrl);\n return this.#discoveryCache.get(originKey, async () => {\n const response = await this.#get<OidcConfiguration>(DISCOVERY_PATH, 'oidc discovery request failed');\n return response.data;\n });\n }\n\n // -------------------------------------------------------------------------\n // 2. oidcBegin\n // -------------------------------------------------------------------------\n\n /**\n * Build an authorization request (§12.1) — **pure local computation, no\n * network I/O**.\n *\n * Generates a 32-byte CSPRNG `state` and `nonce` (base64url, unpadded) and a\n * fresh PKCE verifier/challenge pair using **S256 only** — `plain` is not\n * implemented anywhere in this SDK. The URL is built from the discovery\n * document's `authorization_endpoint` with exactly the eight parameters\n * §12.1 rule 5 mandates, plus any `extraParams` the caller adds.\n *\n * Nothing is stored: persist the returned `state`, `nonce` and\n * `codeVerifier` yourself (§12.3 rule 1).\n *\n * @throws Error when `extraParams` tries to override one of the eight\n * SDK-owned parameters — a programming error, caught at call time.\n */\n oidcBegin(params: OidcBeginParams): AuthorizationRequest {\n const state = randomUrlSafeToken();\n const nonce = randomUrlSafeToken();\n const codeVerifier = generateCodeVerifier();\n const codeChallenge = computeCodeChallenge(codeVerifier.expose());\n\n const scope = normalizeScope(params.scope);\n const target = new URL(params.configuration.authorization_endpoint);\n const query = new URLSearchParams(target.search);\n\n for (const [key, value] of Object.entries(params.extraParams ?? {})) {\n if (RESERVED_AUTHORIZE_PARAMS.has(key)) {\n throw new Error(\n `oidcBegin: extraParams may not override the SDK-owned authorization parameter \"${key}\" (CONTRACT.md §12.1 rule 5).`,\n );\n }\n query.set(key, value);\n }\n\n query.set('response_type', 'code');\n query.set('client_id', this.#options.clientId);\n query.set('redirect_uri', params.redirectUri);\n query.set('scope', scope);\n query.set('state', state);\n query.set('nonce', nonce);\n query.set('code_challenge', codeChallenge);\n query.set('code_challenge_method', CODE_CHALLENGE_METHOD_S256);\n\n // URLSearchParams serializes a space as '+', which is legal in a query\n // string but not RFC 3986 percent-encoding; §12.1 rule 5 asks for the\n // latter, so spaces become %20. Every other character is already\n // percent-encoded correctly by URLSearchParams.\n target.search = query.toString().replace(/\\+/g, '%20');\n\n return { url: target.toString(), state, nonce, codeVerifier };\n }\n\n // -------------------------------------------------------------------------\n // 3. oidcExchange\n // -------------------------------------------------------------------------\n\n /**\n * `POST /oauth2/token` with `grant_type=authorization_code` (§12.1) —\n * exchange an authorization code for a token set, validating the returned\n * ID token in full before returning.\n *\n * The `nonce` argument is mandatory: this grant always requests the `openid`\n * scope, so §12.4 rule 6 always applies. If **any** §12.4 rule fails, the\n * whole token set is discarded and `AuthError` is raised with the matching\n * reason code — the access and refresh tokens from the same response are\n * never returned (§12.4 rule 7).\n */\n async oidcExchange(params: OidcExchangeParams): Promise<OidcTokenSet> {\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const form = new URLSearchParams();\n form.set('grant_type', 'authorization_code');\n form.set('code', params.code);\n form.set('code_verifier', exposeSecret(params.codeVerifier));\n form.set('redirect_uri', params.redirectUri);\n form.set('client_id', this.#options.clientId);\n this.#appendClientSecret(form);\n\n const wire = await this.#postToken(configuration, form, params.tenantId);\n return this.#toTokenSet(wire, configuration, params.nonce);\n }\n\n // -------------------------------------------------------------------------\n // 4. oidcRefresh\n // -------------------------------------------------------------------------\n\n /**\n * `POST /oauth2/token` with `grant_type=refresh_token` (§12.1) — refresh an\n * {@link OidcTokenSet}, under the §9 single-flight refresh guard.\n *\n * @remarks\n * This is a **distinct operation** from `AxiamClient.refresh()`, which drives\n * the cookie/opaque-token session path at `POST /api/v1/auth/refresh`. The\n * two are never merged or aliased and neither falls back to the other\n * (§12.1). They do share the session's §9 guard, so at most one refresh of\n * either kind is ever in flight for a session.\n *\n * Concurrent `oidcRefresh` calls collapse into one HTTP request and all\n * receive the same token set — §9 rule 2's result sharing.\n *\n * An `id_token` in the response is validated against §12.4 rules 1–5 and 7;\n * rule 6 (nonce) is skipped, since OIDC Core §12.2 does not require a nonce\n * in a refresh-issued ID token.\n */\n oidcRefresh(params: OidcRefreshParams): Promise<OidcTokenSet> {\n const existing = this.#pendingRefresh;\n if (existing) {\n return existing;\n }\n const pending = this.#refreshUnderGuard(params);\n this.#pendingRefresh = pending;\n const clear = (): void => {\n if (this.#pendingRefresh === pending) {\n this.#pendingRefresh = null;\n }\n };\n pending.then(clear, clear);\n return pending;\n }\n\n // -------------------------------------------------------------------------\n // 5. loginClientCredentials\n // -------------------------------------------------------------------------\n\n /**\n * `POST /oauth2/token` with `grant_type=client_credentials` (§12.1) —\n * service-account machine-to-machine login.\n *\n * Requests no `openid` scope, so the response carries no `id_token`. Pass\n * `adoptAsCredential: true` to additionally use the returned access token as\n * this session's bearer credential for subsequent REST calls (§12.1, a MAY).\n *\n * @throws AuthError when no `clientSecret` is configured — this grant cannot\n * be performed by a public client.\n */\n async loginClientCredentials(params: LoginClientCredentialsParams = {}): Promise<OidcTokenSet> {\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const form = new URLSearchParams();\n form.set('grant_type', 'client_credentials');\n form.set('client_id', this.#options.clientId);\n form.set('client_secret', this.#requireClientSecret('loginClientCredentials'));\n if (params.scope !== undefined) {\n form.set('scope', params.scope);\n }\n\n const wire = await this.#postToken(configuration, form, params.tenantId);\n // No nonce: rule 6 does not apply to this grant (§12.4 rule 6).\n const tokenSet = await this.#toTokenSet(wire, configuration, undefined);\n\n if (params.adoptAsCredential) {\n this.#adoptCredential(tokenSet.accessToken);\n }\n return tokenSet;\n }\n\n // -------------------------------------------------------------------------\n // 6. introspect\n // -------------------------------------------------------------------------\n\n /**\n * `POST /oauth2/introspect` (RFC 7662, §12.1) — ask the server whether a\n * token is active and, if so, for its metadata.\n *\n * Requires confidential-client credentials (§12.1 note 4). A `401` here is a\n * *client-credential* failure surfaced as `OAuthProtocolError`; it never\n * enters the §9 refresh guard, because refreshing the user session cannot\n * fix a bad `client_secret` (§12.3 rule 3).\n *\n * @throws AuthError when no `clientSecret` is configured.\n */\n async introspect(params: IntrospectParams): Promise<IntrospectionResult> {\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const form = new URLSearchParams();\n form.set('token', exposeSecret(params.token));\n form.set('client_id', this.#options.clientId);\n form.set('client_secret', this.#requireClientSecret('introspect'));\n if (params.tokenTypeHint !== undefined) {\n form.set('token_type_hint', params.tokenTypeHint);\n }\n\n const url = this.#endpointUrl(configuration.introspection_endpoint, params.tenantId);\n const response = await this.#postForm<IntrospectionResponseWire>(url, form, 'introspect request failed');\n const wire = response.data;\n return {\n active: wire.active,\n ...(wire.sub != null ? { sub: wire.sub } : {}),\n ...(wire.client_id != null ? { clientId: wire.client_id } : {}),\n ...(wire.scope != null ? { scope: wire.scope } : {}),\n ...(wire.token_type != null ? { tokenType: wire.token_type } : {}),\n ...(wire.exp != null ? { exp: wire.exp } : {}),\n ...(wire.iat != null ? { iat: wire.iat } : {}),\n };\n }\n\n // -------------------------------------------------------------------------\n // 7. revoke\n // -------------------------------------------------------------------------\n\n /**\n * `POST /oauth2/revoke` (RFC 7009, §12.1) — revoke an access or refresh\n * token. Returns nothing.\n *\n * Per RFC 7009 the server answers `200` for unknown, expired and\n * already-revoked tokens alike, so revocation is **idempotent**: any `200`\n * is success and no error is raised for a token the server has never seen.\n * Only a `401` (client authentication failed) is an error, surfaced as\n * `OAuthProtocolError` (§12.1 note 5, §12.3 rule 3).\n *\n * @throws AuthError when no `clientSecret` is configured.\n */\n async revoke(params: RevokeParams): Promise<void> {\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const form = new URLSearchParams();\n form.set('token', exposeSecret(params.token));\n form.set('client_id', this.#options.clientId);\n form.set('client_secret', this.#requireClientSecret('revoke'));\n if (params.tokenTypeHint !== undefined) {\n form.set('token_type_hint', params.tokenTypeHint);\n }\n\n const url = this.#endpointUrl(configuration.revocation_endpoint, params.tenantId);\n await this.#postForm<void>(url, form, 'revoke request failed');\n }\n\n // -------------------------------------------------------------------------\n // 8. ssoStart\n // -------------------------------------------------------------------------\n\n /**\n * `POST /api/v1/auth/federation/oidc/start` (§12.1) — step 1 of first-time\n * SSO against an **upstream** IdP. No JWT required.\n *\n * One tenant form (`tenantId` or `tenantSlug`) and one org form (`orgId` or\n * `orgSlug`) must be resolvable, from the arguments or from the session's\n * construction options (§5.1). Redirect the browser to the returned\n * `authorizeUrl` and round-trip `state` back into {@link ssoComplete}\n * unmodified — the server keeps the nonce to itself (§12.1 note 7).\n *\n * @throws AuthError client-side, without a wire call, when tenant or org\n * context cannot be resolved.\n */\n async ssoStart(params: SsoStartParams): Promise<SsoStartResult> {\n const tenantId = params.tenantId ?? this.#session.tenantId;\n const tenantSlug = params.tenantSlug ?? this.#session.tenantSlug;\n const orgId = params.orgId ?? this.#session.orgId;\n const orgSlug = params.orgSlug ?? this.#session.orgSlug;\n\n if (!tenantId && !tenantSlug) {\n throw new AuthError(\n 'ssoStart requires tenant context: pass tenantId or tenantSlug, or construct the client with one (CONTRACT.md §5.1).',\n );\n }\n if (!orgId && !orgSlug) {\n throw new AuthError(\n 'ssoStart requires organization context: pass orgId or orgSlug, or construct the client with one (CONTRACT.md §5.1).',\n );\n }\n\n const body: Record<string, string> = {\n federation_config_id: params.federationConfigId,\n redirect_uri: params.redirectUri,\n };\n // One tenant form AND one org form (§5.1). The UUID form wins when both\n // are present, mirroring how tenantSlug/tenantId already resolve.\n if (tenantId) {\n body.tenant_id = tenantId;\n } else if (tenantSlug) {\n body.tenant_slug = tenantSlug;\n }\n if (orgId) {\n body.org_id = orgId;\n } else if (orgSlug) {\n body.org_slug = orgSlug;\n }\n\n const response = await this.#postJson<OidcStartResponseWire>(\n SSO_START_PATH,\n body,\n 'ssoStart request failed',\n );\n return {\n authorizeUrl: response.data.authorize_url,\n state: response.data.state,\n expiresInSecs: response.data.expires_in_secs,\n };\n }\n\n // -------------------------------------------------------------------------\n // 9. ssoComplete\n // -------------------------------------------------------------------------\n\n /**\n * `POST /api/v1/auth/federation/oidc/callback` (§12.1) — step 2 of upstream\n * SSO: consumes the single-use `state`, provisions or links the user, and\n * establishes the session.\n *\n * @remarks\n * The session arrives as **`Set-Cookie`**, not in the response body\n * (§12.1 note 6), so this call must go through the §4 cookie jar: use a\n * `NodeSession` (`createNodeSession`/`createNodeClient`) or the session is\n * silently lost. On success the session is marked authenticated and its\n * post-authentication hook runs, syncing the CSRF token and cached access\n * token out of the jar exactly as `login()` does.\n *\n * §12.4 does not apply here — no ID token ever reaches the SDK on the\n * federation path.\n */\n async ssoComplete(params: SsoCompleteParams): Promise<SsoCompleteResult> {\n const response = await this.#postJson<SsoLoginSuccessResponseWire>(\n SSO_CALLBACK_PATH,\n { state: params.state, code: params.code },\n 'ssoComplete request failed',\n );\n\n this.#session.authenticated = true;\n // Same post-login sync login()/verifyMfa() perform (CR-01/D-05): reads the\n // freshly-set axiam_csrf/axiam_access cookies out of the jar. A no-op on\n // the browser SharedSession, which has no jar.\n await this.#session.onAuthenticated?.();\n\n return {\n userId: response.data.user_id,\n sessionId: response.data.session_id,\n expiresIn: response.data.expires_in,\n redirectUri: response.data.redirect_uri,\n };\n }\n\n // -------------------------------------------------------------------------\n // internals\n // -------------------------------------------------------------------------\n\n /**\n * Run one `refresh_token` grant under the session's §9 single-flight guard.\n *\n * The guard's callback signature returns `void`, so the token set is\n * published through a local variable. When the callback does NOT run, the\n * guard was already busy with a *different* refresh (the §1 cookie-session\n * path, which cannot produce an `OidcTokenSet`); rather than return a stale\n * or wrong result we simply try again now that the other refresh has\n * settled. Bounded, so a pathologically busy guard fails loudly instead of\n * spinning.\n */\n async #refreshUnderGuard(params: OidcRefreshParams): Promise<OidcTokenSet> {\n const configuration = params.configuration ?? (await this.oidcDiscover());\n const form = new URLSearchParams();\n form.set('grant_type', 'refresh_token');\n form.set('refresh_token', exposeSecret(params.refreshToken));\n form.set('client_id', this.#options.clientId);\n this.#appendClientSecret(form);\n if (params.scope !== undefined) {\n form.set('scope', params.scope);\n }\n\n for (let attempt = 0; attempt < 3; attempt += 1) {\n let refreshed: OidcTokenSet | undefined;\n await this.#session.refreshGuard(async () => {\n const wire = await this.#postToken(configuration, form, params.tenantId);\n // No nonce: rule 6 does not apply to a refresh-issued ID token.\n refreshed = await this.#toTokenSet(wire, configuration, undefined);\n });\n if (refreshed) {\n return refreshed;\n }\n }\n throw new AuthError(\n 'oidcRefresh could not acquire the single-flight refresh guard (CONTRACT.md §9); another refresh kept it busy.',\n );\n }\n\n /** POST a form body to the token endpoint from the discovery document. */\n async #postToken(\n configuration: OidcConfiguration,\n form: URLSearchParams,\n tenantId: string | undefined,\n ): Promise<TokenResponseWire> {\n const url = this.#endpointUrl(configuration.token_endpoint, tenantId);\n const response = await this.#postForm<TokenResponseWire>(url, form, 'token request failed');\n return response.data;\n }\n\n /**\n * Convert a `TokenResponse` into an {@link OidcTokenSet}, validating any\n * `id_token` first (§12.4). Validation precedes construction, so a failure\n * discards the whole set — the caller never sees the access or refresh token\n * from a response whose ID token was rejected (§12.4 rule 7).\n */\n async #toTokenSet(\n wire: TokenResponseWire,\n configuration: OidcConfiguration,\n nonce: string | undefined,\n ): Promise<OidcTokenSet> {\n let idClaims: IdTokenClaims | undefined;\n if (wire.id_token) {\n idClaims = await this.#verifierFor(configuration.jwks_uri).verifyIdToken(wire.id_token, {\n issuer: configuration.issuer,\n clientId: this.#options.clientId,\n ...(nonce !== undefined ? { nonce } : {}),\n ...(this.#options.clockSkewSec !== undefined ? { clockSkewSec: this.#options.clockSkewSec } : {}),\n });\n }\n\n return {\n accessToken: new Sensitive(wire.access_token),\n tokenType: wire.token_type,\n expiresIn: wire.expires_in,\n ...(wire.scope != null ? { scope: wire.scope } : {}),\n ...(wire.refresh_token != null ? { refreshToken: new Sensitive(wire.refresh_token) } : {}),\n ...(wire.id_token != null ? { idToken: new Sensitive(wire.id_token) } : {}),\n ...(idClaims !== undefined ? { idClaims } : {}),\n };\n }\n\n /** Lazily build (and reuse) the JWKS verifier for a `jwks_uri` (§12.3 rule 6). */\n #verifierFor(jwksUri: string): JwksVerifier {\n const existing = this.#verifiers.get(jwksUri);\n if (existing) {\n return existing;\n }\n const verifier = createJwksVerifier(jwksUri);\n this.#verifiers.set(jwksUri, verifier);\n return verifier;\n }\n\n /**\n * Build the final endpoint URL: the discovery document's endpoint plus the\n * mandatory `?tenant_id=<uuid>` query parameter (§12.1 note 2). Existing\n * query parameters on the endpoint are preserved.\n */\n #endpointUrl(endpoint: string, tenantId: string | undefined): string {\n const url = new URL(endpoint);\n url.searchParams.set('tenant_id', this.#resolveTenantId(tenantId));\n return url.toString();\n }\n\n /**\n * Resolve the tenant UUID for the `tenant_id` query parameter (§12.3\n * rule 4): the explicit argument, else the client-level `tenantId`, else the\n * session's `tenantId` — and only ever a UUID. A slug-only client raises the\n * taxonomy error client-side, with no wire call, rather than sending a slug\n * where the server requires a UUID.\n */\n #resolveTenantId(explicit: string | undefined): string {\n const candidate = explicit ?? this.#options.tenantId ?? this.#session.tenantId;\n if (!candidate) {\n throw new AuthError(\n 'this operation requires a tenant_id UUID for the /oauth2 query parameter: pass tenantId explicitly, ' +\n 'or construct the client with the tenantId (UUID) form (CONTRACT.md §12.3 rule 4).',\n );\n }\n if (!UUID_RE.test(candidate)) {\n throw new AuthError(\n 'tenant_id must be a UUID for the /oauth2 query parameter; a tenant slug cannot be substituted ' +\n '(CONTRACT.md §12.3 rule 4).',\n );\n }\n return candidate;\n }\n\n /**\n * Add `client_secret` to a form body for a confidential client, and omit it\n * entirely for a public client — §12.1 forbids sending an empty/null value\n * for an absent optional field.\n */\n #appendClientSecret(form: URLSearchParams): void {\n const secret = this.#options.clientSecret;\n if (secret !== undefined) {\n form.set('client_secret', exposeSecret(secret));\n }\n }\n\n /** The `client_secret` for an operation that cannot be performed without one (§12.1 note 4). */\n #requireClientSecret(operation: string): string {\n const secret = this.#options.clientSecret;\n if (secret === undefined) {\n throw new AuthError(\n `${operation} requires confidential-client credentials: construct the OidcClient with a clientSecret ` +\n '(CONTRACT.md §12.1 note 4).',\n );\n }\n return exposeSecret(secret);\n }\n\n /**\n * Adopt an access token as this session's bearer credential (§12.1, opt-in).\n *\n * The token lives only inside the interceptor closure, behind\n * {@link Sensitive} — never on `axios.defaults`, a public property or the\n * cookie jar — so it stays unreachable through any public getter (§12.3\n * rule 2). It is deliberately NOT sent to `/oauth2/*`: those endpoints\n * authenticate the client through the form body (§12.1 note 3).\n */\n #adoptCredential(accessToken: Sensitive<string>): void {\n this.#adoptedCredential = accessToken;\n if (this.#adoptionInterceptorInstalled) {\n return;\n }\n this.#adoptionInterceptorInstalled = true;\n this.#session.axios.interceptors.request.use((config) => {\n const adopted = this.#adoptedCredential;\n const url = config.url ?? '';\n if (!adopted || this.#session.isForeignHost(url) || url.includes('/oauth2/')) {\n return config;\n }\n config.headers = config.headers ?? {};\n config.headers['Authorization'] = `Bearer ${adopted.expose()}`;\n return config;\n });\n }\n\n /** GET through the session transport, mapping failures onto the §2 taxonomy. */\n async #get<T>(url: string, fallbackMessage: string): Promise<AxiosResponse<T>> {\n try {\n return await this.#session.axios.get<T>(url);\n } catch (err) {\n throw mapOidcError(err, url, fallbackMessage);\n }\n }\n\n /** POST a form-encoded body (§12.1 note 1) through the session transport. */\n async #postForm<T>(\n url: string,\n form: URLSearchParams,\n fallbackMessage: string,\n ): Promise<AxiosResponse<T>> {\n const config: AxiosRequestConfig = {\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n };\n try {\n return await this.#session.axios.post<T>(url, form.toString(), config);\n } catch (err) {\n throw mapOidcError(err, url, fallbackMessage);\n }\n }\n\n /** POST a JSON body (the federation endpoints) through the session transport. */\n async #postJson<T>(\n url: string,\n body: Record<string, string>,\n fallbackMessage: string,\n ): Promise<AxiosResponse<T>> {\n try {\n return await this.#session.axios.post<T>(url, body);\n } catch (err) {\n throw mapOidcError(err, url, fallbackMessage);\n }\n }\n}\n\n/**\n * Normalize the requested scope to a space-separated string that always\n * contains `openid` (§12.1 rule 4 — the helper adds it when the caller omits\n * it). Duplicate entries are collapsed so `\"openid openid profile\"` cannot be\n * produced.\n */\nfunction normalizeScope(scope: string | string[] | undefined): string {\n const requested = Array.isArray(scope) ? scope : (scope ?? '').split(' ');\n const values = requested.map((value) => value.trim()).filter(Boolean);\n if (!values.includes(OPENID_SCOPE)) {\n values.unshift(OPENID_SCOPE);\n }\n return [...new Set(values)].join(' ');\n}\n\n/**\n * Build an {@link OidcClient} on an existing session (CONTRACT.md §12).\n *\n * @param session the session the rest of the SDK already uses — normally a\n * `NodeSession` from `createNodeSession`, so the §4 cookie jar is in place\n * for `ssoComplete` (its session arrives as `Set-Cookie`).\n * @param options the relying party's `clientId`, optional `clientSecret`, and\n * optional tenant/TTL/skew overrides.\n *\n * @example\n * ```ts\n * import { createNodeSession, createOidcClient } from 'axiam-sdk/node';\n *\n * const session = createNodeSession({ baseUrl, tenantId, orgId });\n * const oidc = createOidcClient(session, {\n * clientId: process.env.AXIAM_CLIENT_ID!,\n * clientSecret: process.env.AXIAM_CLIENT_SECRET,\n * });\n * ```\n */\nexport function createOidcClient(session: SharedSession, options: OidcClientOptions): OidcClient {\n return new OidcClient(session, options);\n}\n","// OidcStateStore + MemoryOidcStateStore (CONTRACT.md §12.3 rule 1).\n//\n// STRICTLY OPTIONAL. The nine §12 operations never touch a store: `oidcBegin`\n// and `oidcExchange` are stateless by contract, and the caller normally keeps\n// `state`/`nonce`/`code_verifier` in its own HTTP session. This store exists\n// for the framework glue (`middleware/oidcLogin*`), where a login and its\n// callback are two separate HTTP requests with nothing but a `state` value\n// linking them.\n//\n// Semantics mirror the server's `federation_login_state` table exactly:\n// 10-minute TTL, single-use consume. That symmetry is deliberate — a reader\n// who knows the server side already knows this class.\n\nimport { Sensitive } from '../core/index.js';\n\n/**\n * The tuple an {@link OidcStateStore} holds for one in-flight login.\n *\n * @remarks\n * `codeVerifier` stays {@link Sensitive} while stored (§12.5: the verifier is\n * secret for its whole lifetime, \"including … in any `OidcStateStore` entry\"),\n * so `JSON.stringify()`ing an entry — e.g. into a Redis-backed store — emits\n * `\"[SENSITIVE]\"` rather than the verifier. A store implementation that needs\n * to persist the value must call `expose()` explicitly and is then responsible\n * for protecting it at rest.\n */\nexport interface OidcStateEntry {\n /** The `state` value this entry is keyed by. Not a secret (§12.3 rule 2). */\n state: string;\n /** The `nonce` to check the ID token's `nonce` claim against. Not a secret (§12.3 rule 2). */\n nonce: string;\n /** The PKCE verifier for the matching authorization request (§12.5 secret). */\n codeVerifier: Sensitive<string>;\n /** The `redirect_uri` that was sent on the authorization request and must be replayed on exchange. */\n redirectUri: string;\n /** Optional application-owned data, e.g. the page the user was heading to before login. */\n returnTo?: string;\n}\n\n/**\n * Optional server-side store for in-flight `oidcBegin` state\n * (CONTRACT.md §12.3 rule 1).\n *\n * @remarks\n * Implement this to back the login/callback handlers with your own storage\n * (Redis, a database, an encrypted cookie). Two invariants are normative:\n *\n * 1. **Single-use.** {@link consume} MUST return the entry *and delete it\n * atomically*, so a replayed callback cannot reuse a `state`.\n * 2. **Expiry.** An entry older than 10 minutes MUST NOT be returned.\n */\nexport interface OidcStateStore {\n /** Persist an entry, keyed by its `state`, starting its TTL now. */\n save(entry: OidcStateEntry): Promise<void>;\n /**\n * Atomically fetch **and remove** the entry for `state`. Returns\n * `undefined` when the state is unknown, already consumed, or expired —\n * three cases a caller MUST treat identically (as a failed login), because\n * distinguishing them leaks whether a `state` ever existed.\n */\n consume(state: string): Promise<OidcStateEntry | undefined>;\n}\n\n/**\n * The contract-mandated TTL for stored login state: 10 minutes, matching the\n * server's `federation_login_state` row lifetime (D-22, §12.3 rule 1).\n */\nexport const OIDC_STATE_TTL_MS = 600_000;\n\n/**\n * In-memory reference implementation of {@link OidcStateStore} (§12.3 rule 1).\n *\n * @remarks\n * Per-instance (never process-global), single-use, 10-minute TTL. Expired\n * entries are dropped lazily on {@link consume} and swept opportunistically on\n * {@link save}, so no timer is held and the store needs no shutdown hook — a\n * long-lived `setInterval` would keep a Node process alive and would be a\n * surprising side effect for a library.\n *\n * Suitable for a single-process app and for tests. A multi-instance deployment\n * needs a shared store (Redis, database) — implement {@link OidcStateStore}\n * yourself for that; nothing in the SDK assumes this class.\n *\n * @example\n * ```ts\n * const store = new MemoryOidcStateStore();\n * await store.save({ state, nonce, codeVerifier, redirectUri });\n * const entry = await store.consume(state); // returns the entry\n * const again = await store.consume(state); // undefined — single-use\n * ```\n */\nexport class MemoryOidcStateStore implements OidcStateStore {\n readonly #entries = new Map<string, { entry: OidcStateEntry; expiresAt: number }>();\n readonly #ttlMs: number;\n\n /**\n * @param ttlMs entry lifetime in milliseconds. Defaults to\n * {@link OIDC_STATE_TTL_MS} (10 minutes) and is **clamped to it**: a\n * shorter TTL is honoured (useful in tests), a longer one is reduced,\n * because §12.3 rule 1 fixes 10 minutes as the maximum.\n */\n constructor(ttlMs: number = OIDC_STATE_TTL_MS) {\n this.#ttlMs = Math.min(ttlMs, OIDC_STATE_TTL_MS);\n }\n\n /** Number of unexpired entries currently held. Intended for tests and metrics. */\n get size(): number {\n this.#sweep();\n return this.#entries.size;\n }\n\n /** Persist `entry` under its own `state`, expiring `ttlMs` from now. */\n async save(entry: OidcStateEntry): Promise<void> {\n this.#sweep();\n this.#entries.set(entry.state, { entry, expiresAt: Date.now() + this.#ttlMs });\n }\n\n /**\n * Atomically return and delete the entry for `state`. Deletion happens\n * before the expiry check, so even an expired hit is removed rather than\n * left to accumulate — and a second call can never return the same entry\n * twice regardless of timing (JavaScript's single-threaded event loop makes\n * this get-then-delete pair genuinely atomic; a store backed by real\n * concurrency must use an atomic primitive such as Redis `GETDEL`).\n */\n async consume(state: string): Promise<OidcStateEntry | undefined> {\n const held = this.#entries.get(state);\n if (!held) {\n return undefined;\n }\n this.#entries.delete(state);\n if (held.expiresAt <= Date.now()) {\n return undefined;\n }\n return held.entry;\n }\n\n /** Drop every expired entry. Lazy housekeeping — no background timer. */\n #sweep(): void {\n const now = Date.now();\n for (const [state, held] of this.#entries) {\n if (held.expiresAt <= now) {\n this.#entries.delete(state);\n }\n }\n }\n}\n"]}
|
package/dist/nestjs/index.d.cts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { R as RequireAccessOptions, A as AuthzVerifiableSession } from '../authzCore-DuRI1aJf.cjs';
|
|
2
2
|
import { CanActivate, ExecutionContext } from '@nestjs/common';
|
|
3
3
|
import { Reflector } from '@nestjs/core';
|
|
4
4
|
import '../types-BVkMoqLU.cjs';
|
|
5
|
-
import '../jwks-
|
|
5
|
+
import '../jwks-BgojMGC5.cjs';
|
|
6
6
|
|
|
7
7
|
/** `{ param: 'id' }` form of the `@RequireAccess` `resource` argument (§11.2.3.b): resolve the resource id from the named route parameter at request time. */
|
|
8
8
|
interface NestParamResource {
|