{"version":3,"file":"index.mjs","names":[],"sources":["../src/errors/monocloud-auth-base-error.ts","../src/errors/monocloud-op-error.ts","../src/errors/monocloud-http-error.ts","../src/errors/monocloud-token-error.ts","../src/errors/monocloud-validation-error.ts","../src/client-auth.ts","../src/helper.ts","../src/monocloud-oidc-client-base.ts","../src/monocloud-oidc-client.ts","../src/monocloud-oidc-backend-client.ts"],"sourcesContent":["import { MonoCloudRawResponse } from '../types';\n\n/**\n * Base class for all MonoCloud authentication errors.\n *\n * All errors thrown by the MonoCloud SDK extend this class, allowing applications to safely detect and handle MonoCloud-specific failures using `instanceof`.\n *\n * @category Error Classes\n */\nexport class MonoCloudAuthBaseError extends Error {\n  /**\n   * The raw HTTP response this error was derived from.\n   */\n  readonly raw?: MonoCloudRawResponse;\n\n  constructor(message?: string, raw?: MonoCloudRawResponse) {\n    super(message);\n    this.raw = raw;\n  }\n}\n","import { MonoCloudRawResponse } from '../types';\nimport { MonoCloudAuthBaseError } from './monocloud-auth-base-error';\n\n/**\n * OAuth error returned by the authorization server.\n *\n * @category Error Classes\n */\nexport class MonoCloudOPError extends MonoCloudAuthBaseError {\n  /**\n   * OAuth error code returned by the authorization server.\n   *\n   * When the response carries no readable error body, this is inferred from the endpoint and status code instead.\n   */\n  error: string;\n\n  /** Human-readable description of the error. */\n  errorDescription?: string;\n\n  constructor(\n    error: string,\n    errorDescription?: string,\n    raw?: MonoCloudRawResponse\n  ) {\n    super(error, raw);\n    this.error = error;\n    this.errorDescription = errorDescription;\n  }\n}\n","import { MonoCloudAuthBaseError } from './monocloud-auth-base-error';\n\n/**\n * Error thrown when a request to the MonoCloud authorization server fails.\n *\n * This error typically indicates a network failure, an unexpected HTTP response, or an unsuccessful response returned by the authorization server.\n *\n * @category Error Classes\n */\nexport class MonoCloudHttpError extends MonoCloudAuthBaseError {\n  /**\n   * HTTP status code of the response that caused the error.\n   *\n   * Undefined when no response was received, such as a network failure.\n   */\n  get status(): number | undefined {\n    return this.raw?.status;\n  }\n\n  /**\n   * HTTP status text of the response that caused the error.\n   */\n  get statusText(): string | undefined {\n    return this.raw?.statusText;\n  }\n}\n","import { MonoCloudRawResponse, MonoCloudTokenErrorCode } from '../types';\nimport { MonoCloudAuthBaseError } from './monocloud-auth-base-error';\n\n/**\n * Error thrown when a token operation fails.\n *\n * @category Error Classes\n */\nexport class MonoCloudTokenError extends MonoCloudAuthBaseError {\n  /** Code identifying why the token operation failed. */\n  readonly code: MonoCloudTokenErrorCode;\n\n  constructor(\n    message?: string,\n    code: MonoCloudTokenErrorCode = 'invalid_token',\n    raw?: MonoCloudRawResponse\n  ) {\n    super(message, raw);\n    this.code = code;\n  }\n}\n","import { MonoCloudAuthBaseError } from './monocloud-auth-base-error';\n\n/**\n * Error thrown when validation fails.\n *\n * @category Error Classes\n */\nexport class MonoCloudValidationError extends MonoCloudAuthBaseError {}\n","import {\n  encodeBase64,\n  encodeBase64Url,\n  randomBytes,\n  stringToArrayBuffer,\n} from './utils/internal';\nimport { ClientAuthMethod, Jwk } from './types';\n\nexport const isMtlsClientAuthMethod = (method?: ClientAuthMethod): boolean =>\n  method === 'tls_client_auth' ||\n  method === 'self_signed_tls_client_auth' ||\n  method === 'spiffe_x509';\n\nconst algToSubtle = (\n  alg?: string\n): HmacImportParams | RsaHashedImportParams | EcKeyImportParams => {\n  switch (alg) {\n    case 'HS256':\n    case 'HS384':\n    case 'HS512':\n      return { name: 'HMAC', hash: `SHA-${alg.slice(-3)}` };\n    case 'PS256':\n    case 'PS384':\n    case 'PS512':\n      return { name: 'RSA-PSS', hash: `SHA-${alg.slice(-3)}` };\n    case 'RS256':\n    case 'RS384':\n    case 'RS512':\n      return { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${alg.slice(-3)}` };\n    case 'ES256':\n    case 'ES384':\n      return { name: 'ECDSA', namedCurve: `P-${alg.slice(-3)}` };\n    case 'ES512':\n      return { name: 'ECDSA', namedCurve: 'P-521' };\n    /* v8 ignore next */\n    default:\n      throw new Error('unsupported JWS algorithm');\n  }\n};\n\nconst psAlg = (key: CryptoKey): string => {\n  switch ((key.algorithm as RsaHashedKeyAlgorithm).hash.name) {\n    case 'SHA-256':\n      return 'PS256';\n    case 'SHA-384':\n      return 'PS384';\n    case 'SHA-512':\n      return 'PS512';\n    /* v8 ignore next */\n    default:\n      throw new Error('unsupported RsaHashedKeyAlgorithm hash name');\n  }\n};\n\nconst rsAlg = (key: CryptoKey): string => {\n  switch ((key.algorithm as RsaHashedKeyAlgorithm).hash.name) {\n    case 'SHA-256':\n      return 'RS256';\n    case 'SHA-384':\n      return 'RS384';\n    case 'SHA-512':\n      return 'RS512';\n    /* v8 ignore next */\n    default:\n      throw new Error('unsupported RsaHashedKeyAlgorithm hash name');\n  }\n};\n\nconst esAlg = (key: CryptoKey): string => {\n  switch ((key.algorithm as EcKeyAlgorithm).namedCurve) {\n    case 'P-256':\n      return 'ES256';\n    case 'P-384':\n      return 'ES384';\n    case 'P-521':\n      return 'ES512';\n    /* v8 ignore next */\n    default:\n      throw new Error('unsupported EcKeyAlgorithm namedCurve');\n  }\n};\n\nconst hsAlg = (key: CryptoKey): string => {\n  switch ((key.algorithm as HmacKeyAlgorithm).hash.name) {\n    case 'SHA-256':\n      return 'HS256';\n    case 'SHA-384':\n      return 'HS384';\n    case 'SHA-512':\n      return 'HS512';\n    /* v8 ignore next */\n    default:\n      throw new Error('unsupported HMAC Algorithm hash');\n  }\n};\n\nconst keyToJws = (key: CryptoKey): string => {\n  switch (key.algorithm.name) {\n    case 'HMAC':\n      return hsAlg(key);\n    case 'RSA-PSS':\n      return psAlg(key);\n    case 'RSASSA-PKCS1-v1_5':\n      return rsAlg(key);\n    case 'ECDSA':\n      return esAlg(key);\n    /* v8 ignore next */\n    default:\n      throw new Error('unsupported CryptoKey algorithm name');\n  }\n};\n\nconst checkRsaKeyAlgorithm = (key: CryptoKey): void => {\n  const { algorithm } = key as CryptoKey & { algorithm: RsaHashedKeyAlgorithm };\n\n  /* v8 ignore if -- @preserve */\n  if (\n    typeof algorithm.modulusLength !== 'number' ||\n    algorithm.modulusLength < 2048\n  ) {\n    throw new Error(`Unsupported ${algorithm.name} modulusLength`);\n  }\n};\n\nconst ecdsaHashName = (key: CryptoKey): string => {\n  const { algorithm } = key as CryptoKey & { algorithm: EcKeyAlgorithm };\n  switch (algorithm.namedCurve) {\n    case 'P-256':\n      return 'SHA-256';\n    case 'P-384':\n      return 'SHA-384';\n    case 'P-521':\n      return 'SHA-512';\n    /* v8 ignore next */\n    default:\n      throw new Error('unsupported ECDSA namedCurve');\n  }\n};\n\nexport const keyToSubtle = (\n  key: CryptoKey\n): AlgorithmIdentifier | RsaPssParams | EcdsaParams => {\n  switch (key.algorithm.name) {\n    case 'HMAC': {\n      return { name: key.algorithm.name };\n    }\n    case 'ECDSA':\n      return {\n        name: key.algorithm.name,\n        hash: ecdsaHashName(key),\n      } as EcdsaParams;\n    case 'RSA-PSS': {\n      checkRsaKeyAlgorithm(key);\n      switch ((key.algorithm as RsaHashedKeyAlgorithm).hash.name) {\n        case 'SHA-256': // Fall through\n        case 'SHA-384': // Fall through\n        case 'SHA-512':\n          return {\n            name: key.algorithm.name,\n            saltLength:\n              parseInt(\n                (key.algorithm as RsaHashedKeyAlgorithm).hash.name.slice(-3),\n                10\n              ) >> 3,\n          } as RsaPssParams;\n        /* v8 ignore next */\n        default:\n          throw new Error('unsupported RSA-PSS hash name');\n      }\n    }\n    case 'RSASSA-PKCS1-v1_5':\n      checkRsaKeyAlgorithm(key);\n      return key.algorithm.name;\n  }\n  /* v8 ignore next -- @preserve */\n  throw new Error('unsupported CryptoKey algorithm name');\n};\n\nconst clientAssertionPayload = (\n  issuer: string,\n  clientId: string,\n  skew: number\n): Record<string, number | string> => {\n  const now = Math.floor(Date.now() / 1000) + skew;\n  return {\n    jti: randomBytes(),\n    aud: issuer,\n    exp: now + 60,\n    iat: now,\n    nbf: now,\n    iss: clientId,\n    sub: clientId,\n  };\n};\n\nconst jwtAssertionGenerator = async (\n  issuer: string,\n  clientId: string,\n  clientSecret: Jwk,\n  body: URLSearchParams,\n  skew: number\n): Promise<void> => {\n  const key = await crypto.subtle.importKey(\n    'jwk',\n    clientSecret as JsonWebKey,\n    algToSubtle(clientSecret.alg),\n    false,\n    ['sign']\n  );\n\n  const header = { alg: keyToJws(key), kid: clientSecret.kid };\n  const payload = clientAssertionPayload(issuer, clientId, skew);\n\n  body.set('client_id', clientId);\n  body.set(\n    'client_assertion_type',\n    'urn:ietf:params:oauth:client-assertion-type:jwt-bearer'\n  );\n\n  const input = `${encodeBase64Url(stringToArrayBuffer(JSON.stringify(header)))}.${encodeBase64Url(stringToArrayBuffer(JSON.stringify(payload)))}`;\n  const signature = encodeBase64Url(\n    await crypto.subtle.sign(\n      keyToSubtle(key),\n      key,\n      stringToArrayBuffer(input) as BufferSource\n    )\n  );\n\n  body.set('client_assertion', `${input}.${signature}`);\n};\n\nexport const clientAuth = async (\n  clientId: string,\n  clientSecret?: string | Jwk,\n  method?: ClientAuthMethod,\n  issuer?: string,\n  headers?: Record<string, string>,\n  body?: URLSearchParams,\n  jwtAssertionSkew?: number\n): Promise<void> => {\n  switch (true) {\n    case method === 'client_secret_basic' &&\n      !!headers &&\n      (clientSecret === undefined || typeof clientSecret === 'string'): {\n      // eslint-disable-next-line no-param-reassign\n      headers.authorization = `Basic ${encodeBase64(\n        `${clientId}:${clientSecret ?? ''}`\n      )}`;\n      break;\n    }\n\n    case method === 'client_secret_post' && !!body: {\n      body.set('client_id', clientId);\n      if (typeof clientSecret === 'string') {\n        body.set('client_secret', clientSecret);\n      }\n      break;\n    }\n\n    case method === 'client_secret_jwt' &&\n      !!issuer &&\n      !!body &&\n      (typeof clientSecret === 'string' || clientSecret?.kty === 'oct'): {\n      const cs =\n        typeof clientSecret === 'string'\n          ? {\n              k: encodeBase64Url(stringToArrayBuffer(clientSecret)),\n              kty: 'oct',\n              alg: 'HS256',\n            }\n          : clientSecret;\n\n      await jwtAssertionGenerator(\n        issuer,\n        clientId,\n        cs,\n        body,\n        jwtAssertionSkew ?? 0\n      );\n      break;\n    }\n\n    case method === 'private_key_jwt' &&\n      typeof clientSecret === 'object' &&\n      clientSecret.kty !== 'oct' &&\n      !!issuer &&\n      !!body: {\n      await jwtAssertionGenerator(\n        issuer,\n        clientId,\n        clientSecret,\n        body,\n        jwtAssertionSkew ?? 0\n      );\n      break;\n    }\n\n    case isMtlsClientAuthMethod(method) && !!body: {\n      body.set('client_id', clientId);\n      break;\n    }\n\n    case method === 'spiffe_jwt' &&\n      typeof clientSecret === 'string' &&\n      !!body: {\n      body.set('client_id', clientId);\n      body.set(\n        'client_assertion_type',\n        'urn:ietf:params:oauth:client-assertion-type:jwt-spiffe'\n      );\n      body.set('client_assertion', clientSecret);\n      break;\n    }\n\n    default:\n      throw new Error('Invalid Client Authentication Method');\n  }\n};\n","import { MonoCloudHttpError } from './errors/monocloud-http-error';\nimport { MonoCloudValidationError } from './errors/monocloud-validation-error';\nimport { IssuerMetadata, MonoCloudRawResponse } from './types';\nimport { isPresent } from './utils/internal';\n\nexport const JWT_ASSERTION_CLOCK_SKEW = 5;\n\nexport function assertMetadataProperty<K extends keyof IssuerMetadata>(\n  metadata: IssuerMetadata,\n  property: K\n): asserts metadata is IssuerMetadata & Required<Pick<IssuerMetadata, K>> {\n  if (metadata[property] === undefined || metadata[property] === null) {\n    throw new MonoCloudValidationError(\n      `${property as string} endpoint is required but not available in the issuer metadata`\n    );\n  }\n}\n\nexport const innerFetch = async (\n  input: string,\n  reqInit: RequestInit = {},\n  customFetch?: typeof fetch,\n  timeout?: number\n): Promise<Response> => {\n  const fetcher = customFetch ?? fetch;\n\n  let timedOut = false;\n  let timer: ReturnType<typeof setTimeout> | undefined;\n  let init = { ...reqInit };\n\n  if (isPresent(timeout) && timeout > 0) {\n    const controller = new AbortController();\n\n    init = { ...init, signal: controller.signal };\n\n    timer = setTimeout(() => {\n      timedOut = true;\n      controller.abort();\n    }, timeout);\n  }\n\n  try {\n    return await fetcher(input, init);\n  } catch (e) {\n    if (timedOut) {\n      throw new MonoCloudHttpError(\n        `Request to ${input} timed out after ${timeout}ms`\n      );\n    }\n\n    /* v8 ignore next -- @preserve */\n    throw new MonoCloudHttpError(\n      (e as any).message ?? 'Unexpected Network Error'\n    );\n  } finally {\n    clearTimeout(timer);\n  }\n};\n\nexport const readRawResponse = async (\n  res: Response\n): Promise<MonoCloudRawResponse> => {\n  let body: string;\n\n  /* v8 ignore start -- @preserve */\n  try {\n    body = await res.text();\n  } catch {\n    body = '';\n  }\n  /* v8 ignore stop */\n\n  return {\n    status: res.status,\n    statusText: res.statusText,\n    headers: Object.fromEntries(\n      [...res.headers].filter(([name]) => name !== 'set-cookie')\n    ),\n    body,\n  };\n};\n\nexport const readErrorResponse = async <T = any>(\n  res: Response\n): Promise<{ raw: MonoCloudRawResponse; json: Partial<T> }> => {\n  const raw = await readRawResponse(res);\n\n  let json: Partial<T> = {};\n\n  try {\n    const parsed = JSON.parse(raw.body);\n    if (parsed !== null && typeof parsed === 'object') {\n      json = parsed;\n    }\n  } catch {\n    json = {};\n  }\n\n  return { raw, json };\n};\n\nexport const deserializeJson = async <T = any>(res: Response): Promise<T> => {\n  const raw = await readRawResponse(res);\n\n  try {\n    return JSON.parse(raw.body);\n  } catch (e) {\n    throw new MonoCloudHttpError(\n      /* v8 ignore next -- @preserve */\n      `Failed to parse response body as JSON ${(e as any).message ? `: ${(e as any).message}` : ''}`,\n      raw\n    );\n  }\n};\n","import { decodeBase64Url, now } from './utils/internal';\nimport {\n  JwtClaims,\n  IssuerMetadata,\n  Jwks,\n  MonoCloudOidcClientBaseOptions,\n  MtlsEndpointAliases,\n} from './types';\nimport { MonoCloudHttpError } from './errors/monocloud-http-error';\nimport { MonoCloudTokenError } from './errors/monocloud-token-error';\nimport { MonoCloudAuthBaseError } from './errors/monocloud-auth-base-error';\nimport { MonoCloudValidationError } from './errors/monocloud-validation-error';\nimport { isMtlsClientAuthMethod } from './client-auth';\nimport {\n  assertMetadataProperty,\n  deserializeJson,\n  innerFetch,\n  readRawResponse,\n} from './helper';\n\n/**\n * @category Classes\n */\nexport class MonoCloudOidcClientBase {\n  /**\n   * The normalized tenant domain URL used as the base for discovery endpoints.\n   */\n  protected readonly tenantDomain: string;\n\n  /**\n   * Cached JSON Web Key Set retrieved from the issuer's JWKS endpoint.\n   */\n  protected jwks?: Jwks;\n\n  /**\n   * Timestamp (in seconds) when the cached JWKS expires.\n   */\n  protected jwksCacheExpiry = 0;\n\n  /**\n   * Duration (in seconds) for which the JWKS is cached. Defaults to 300 (5 minutes).\n   */\n  protected jwksCacheDuration = 300;\n\n  /**\n   * Cached issuer metadata retrieved from the OpenID Connect discovery endpoint.\n   */\n  protected metadata?: IssuerMetadata;\n\n  /**\n   * Timestamp (in seconds) when the cached metadata expires.\n   */\n  protected metadataCacheExpiry = 0;\n\n  /**\n   * Duration (in seconds) for which the metadata is cached. Defaults to 300 (5 minutes).\n   */\n  protected metadataCacheDuration = 300;\n\n  /**\n   * Custom fetch implementation used for making HTTP requests. Falls back to the global `fetch` if not provided.\n   */\n  protected fetcher?: typeof fetch;\n\n  /**\n   * Maximum time (in milliseconds) to wait for a response from the authorization server before\n   * aborting the request.\n   */\n  protected readonly responseTimeout?: number;\n\n  /**\n   * Identifier of the trust store whose mTLS endpoint aliases should be used, if any.\n   */\n  protected readonly trustStoreId?: string;\n\n  /**\n   * Optional custom resolver for the issuer metadata, used instead of the discovery request.\n   */\n  protected readonly metadataResolver?: () =>\n    IssuerMetadata | Promise<IssuerMetadata>;\n\n  /**\n   * Optional custom resolver for the JSON Web Key Set, used instead of the JWKS request.\n   */\n  protected readonly jwksResolver?: () => Jwks | Promise<Jwks>;\n\n  /**\n   * Whether the configured client authentication method uses mutual TLS, and therefore requires\n   * the mTLS endpoint aliases from the issuer metadata.\n   */\n  protected readonly usesMtlsEndpoints: boolean;\n\n  /**\n   * Creates a new instance of MonoCloudOidcClientBase.\n   *\n   * @param options - Base client configuration options.\n   */\n  constructor(options: MonoCloudOidcClientBaseOptions) {\n    let { tenantDomain } = options;\n    tenantDomain ??= '';\n    /* v8 ignore next -- @preserve */\n    this.tenantDomain = `${!tenantDomain.startsWith('https://') ? 'https://' : ''}${tenantDomain.endsWith('/') ? tenantDomain.slice(0, -1) : tenantDomain}`;\n\n    if (options.metadataCacheDuration !== undefined) {\n      this.metadataCacheDuration = options.metadataCacheDuration;\n    }\n\n    if (options.jwksCacheDuration !== undefined) {\n      this.jwksCacheDuration = options.jwksCacheDuration;\n    }\n\n    this.fetcher = options.fetcher;\n    this.responseTimeout = options.responseTimeout;\n    this.trustStoreId = options.trustStoreId;\n    this.metadataResolver = options.metadataResolver;\n    this.jwksResolver = options.jwksResolver;\n    this.usesMtlsEndpoints = isMtlsClientAuthMethod(options.clientAuthMethod);\n  }\n\n  /**\n   * Fetches the authorization server metadata from the .well-known endpoint.\n   * The metadata is cached for 5 minutes by default.\n   *\n   * @param forceRefresh - If `true`, bypasses the cache and fetches fresh metadata from the server.\n   *\n   * @returns The issuer metadata for the tenant, retrieved from the OpenID Connect discovery endpoint.\n   *\n   * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n   * unexpected status code during the request or a serialization error while processing the response.\n   *\n   */\n  async getMetadata(forceRefresh = false): Promise<IssuerMetadata> {\n    if (!forceRefresh && this.metadata && this.metadataCacheExpiry > now()) {\n      return this.metadata;\n    }\n\n    let metadata: IssuerMetadata;\n\n    if (this.metadataResolver) {\n      metadata = await this.metadataResolver();\n    } else {\n      const response = await innerFetch(\n        `${this.tenantDomain}/.well-known/openid-configuration`,\n        undefined,\n        this.fetcher,\n        this.responseTimeout\n      );\n\n      if (response.status !== 200) {\n        const raw = await readRawResponse(response);\n\n        throw new MonoCloudHttpError(\n          `Error while fetching metadata. Unexpected status code: ${response.status}`,\n          raw\n        );\n      }\n\n      metadata = await deserializeJson<IssuerMetadata>(response);\n    }\n\n    this.metadata = metadata;\n    this.metadataCacheExpiry = now() + this.metadataCacheDuration;\n\n    return metadata;\n  }\n\n  /**\n   * Fetches the JSON Web Keys used to sign the ID token.\n   * The JWKS is cached for 5 minutes by default.\n   *\n   * @param forceRefresh - If `true`, bypasses the cache and fetches fresh set of JWKS from the server.\n   *\n   * @returns The JSON Web Key Set containing the public keys for token verification.\n   *\n   * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n   * unexpected status code during the request or a serialization error while processing the response.\n   *\n   */\n  async getJwks(forceRefresh = false): Promise<Jwks> {\n    if (!forceRefresh && this.jwks && this.jwksCacheExpiry > now()) {\n      return this.jwks;\n    }\n\n    let jwks: Jwks;\n\n    if (this.jwksResolver) {\n      jwks = await this.jwksResolver();\n    } else {\n      const metadata = await this.getMetadata();\n\n      assertMetadataProperty(metadata, 'jwks_uri');\n\n      const response = await innerFetch(\n        metadata.jwks_uri,\n        undefined,\n        this.fetcher,\n        this.responseTimeout\n      );\n\n      if (response.status !== 200) {\n        const raw = await readRawResponse(response);\n\n        throw new MonoCloudHttpError(\n          `Error while fetching JWKS. Unexpected status code: ${response.status}`,\n          raw\n        );\n      }\n\n      jwks = await deserializeJson<Jwks>(response);\n    }\n\n    this.jwks = jwks;\n    this.jwksCacheExpiry = now() + this.jwksCacheDuration;\n\n    return jwks;\n  }\n\n  /**\n   * Resolves an endpoint URL from the issuer metadata, preferring the mutual-TLS alias when the\n   * client authenticates over mTLS.\n   *\n   * @param metadata - The issuer metadata.\n   * @param endpoint - The endpoint to resolve.\n   *\n   * @returns The resolved endpoint URL.\n   *\n   * @throws {@link MonoCloudValidationError} - When the required endpoint is not available in the issuer metadata.\n   */\n  protected resolveEndpoint(\n    metadata: IssuerMetadata,\n    endpoint: keyof MtlsEndpointAliases\n  ): string {\n    if (this.usesMtlsEndpoints) {\n      const aliases = this.trustStoreId\n        ? metadata.mtls_additional_endpoint_aliases?.[this.trustStoreId]\n        : metadata.mtls_endpoint_aliases;\n\n      const url = aliases?.[endpoint];\n\n      if (typeof url !== 'string' || url.length === 0) {\n        throw new MonoCloudValidationError(\n          this.trustStoreId\n            ? `mTLS ${endpoint} is required but not available for trust store '${this.trustStoreId}' in the issuer metadata`\n            : `mTLS ${endpoint} is required but not available in the issuer metadata`\n        );\n      }\n\n      return url;\n    }\n\n    assertMetadataProperty(metadata, endpoint);\n\n    return metadata[endpoint];\n  }\n\n  /**\n   * Decodes the payload of a JSON Web Token (JWT) and returns it as an object.\n   *\n   * >Note: THIS METHOD DOES NOT VERIFY JWT TOKENS.\n   *\n   * @param jwt - JWT to decode.\n   *\n   * @returns Decoded payload.\n   *\n   * @throws {@link MonoCloudTokenError} - If decoding fails\n   *\n   */\n  static decodeJwt(jwt: string): JwtClaims {\n    try {\n      const [, payload] = jwt.split('.');\n\n      if (!payload?.trim()) {\n        throw new MonoCloudTokenError('JWT does not contain payload');\n      }\n\n      const decoded = decodeBase64Url(payload);\n\n      if (!decoded.startsWith('{')) {\n        throw new MonoCloudTokenError('Payload is not an object');\n      }\n\n      return JSON.parse(decoded) as JwtClaims;\n    } catch (e) {\n      if (e instanceof MonoCloudAuthBaseError) {\n        throw e;\n      }\n\n      throw new MonoCloudTokenError(\n        'Could not parse payload. Malformed payload'\n      );\n    }\n  }\n}\n","import {\n  decodeBase64Url,\n  findToken,\n  profileSync,\n  getPublicSigKeyFromIssuerJwks,\n  isPresent,\n  now,\n  parseSpaceSeparated,\n  parseSpaceSeparatedSet,\n  stringToArrayBuffer,\n} from './utils/internal';\nimport { clientAuth, keyToSubtle } from './client-auth';\nimport {\n  AccessToken,\n  AuthenticateOptions,\n  AuthorizationParams,\n  ClientAuthMethod,\n  EndSessionParameters,\n  IdTokenClaims,\n  Jwk,\n  LogoutTokenClaims,\n  SecurityAlgorithms,\n  JwsHeaderParameters,\n  MonoCloudOidcClientOptions,\n  MonoCloudSession,\n  MonoCloudUser,\n  ParResponse,\n  PushedAuthorizationParams,\n  RefetchUserInfoOptions,\n  RefreshGrantOptions,\n  RefreshSessionOptions,\n  Tokens,\n  UserinfoResponse,\n  DeviceAuthorizationParams,\n  DeviceAuthorizationResponse,\n} from './types';\nimport { MonoCloudOPError } from './errors/monocloud-op-error';\nimport { MonoCloudHttpError } from './errors/monocloud-http-error';\nimport { MonoCloudValidationError } from './errors/monocloud-validation-error';\nimport { MonoCloudTokenError } from './errors/monocloud-token-error';\nimport { MonoCloudOidcClientBase } from './monocloud-oidc-client-base';\nimport {\n  assertMetadataProperty,\n  deserializeJson,\n  readErrorResponse,\n  innerFetch,\n  JWT_ASSERTION_CLOCK_SKEW,\n} from './helper';\n\nconst FILTER_ID_TOKEN_CLAIMS = [\n  'iss',\n  'exp',\n  'nbf',\n  'aud',\n  'nonce',\n  'iat',\n  'auth_time',\n  'c_hash',\n  'at_hash',\n  's_hash',\n];\n\n/**\n * @category Classes\n */\nexport class MonoCloudOidcClient extends MonoCloudOidcClientBase {\n  private readonly clientId: string;\n\n  private readonly clientSecret?: string | Jwk;\n\n  private readonly authMethod: ClientAuthMethod;\n\n  private readonly idTokenSigningAlgorithm: SecurityAlgorithms;\n\n  /**\n   * Creates a new instance of MonoCloudOidcClient.\n   *\n   * @param tenantDomain - The tenant domain URL.\n   * @param clientId - Client id of the application registered in MonoCloud.\n   * @param options - Additional client configuration options.\n   */\n  constructor(\n    tenantDomain: string,\n    clientId: string,\n    options?: MonoCloudOidcClientOptions\n  ) {\n    super({\n      tenantDomain,\n      metadataCacheDuration: options?.metadataCacheDuration,\n      jwksCacheDuration: options?.jwksCacheDuration,\n      fetcher: options?.fetcher,\n      responseTimeout: options?.responseTimeout,\n      clientAuthMethod: options?.clientAuthMethod ?? 'client_secret_basic',\n      trustStoreId: options?.trustStoreId,\n      metadataResolver: options?.metadataResolver,\n      jwksResolver: options?.jwksResolver,\n    });\n    this.clientId = clientId;\n    this.clientSecret = options?.clientSecret;\n    this.authMethod = options?.clientAuthMethod ?? 'client_secret_basic';\n    this.idTokenSigningAlgorithm = options?.idTokenSigningAlgorithm ?? 'RS256';\n  }\n\n  /**\n   * Generates an authorization URL with specified parameters.\n   *\n   * If no values are provided for `responseType`, or `codeChallengeMethod`, they default to `code`, and `S256`, respectively.\n   *\n   * @param params - Authorization URL parameters.\n   *\n   * @returns Tenant's authorization URL.\n   *\n   * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n   * unexpected status code during the request or a serialization error while processing the response.\n   *\n   */\n  async authorizationUrl(params: AuthorizationParams): Promise<string> {\n    const queryParams = new URLSearchParams();\n\n    queryParams.set('client_id', this.clientId);\n\n    if (params.redirectUri) {\n      queryParams.set('redirect_uri', params.redirectUri);\n    }\n\n    if (params.requestUri) {\n      queryParams.set('request_uri', params.requestUri);\n    }\n\n    const scopes = parseSpaceSeparated(params.scopes) ?? [];\n\n    if (scopes.length > 0) {\n      queryParams.set('scope', scopes.join(' '));\n    }\n\n    if (params.responseType && params.responseType.length > 0) {\n      queryParams.set('response_type', params.responseType);\n    }\n\n    if (\n      (!params.responseType || params.responseType.length === 0) &&\n      !params.requestUri\n    ) {\n      queryParams.set('response_type', 'code');\n    }\n\n    if (params.authenticatorHint) {\n      queryParams.set('authenticator_hint', params.authenticatorHint);\n    }\n\n    if (params.loginHint) {\n      queryParams.set('login_hint', params.loginHint);\n    }\n\n    if (params.request) {\n      queryParams.set('request', params.request);\n    }\n\n    if (params.responseMode) {\n      queryParams.set('response_mode', params.responseMode);\n    }\n\n    if (params.acrValues && params.acrValues.length > 0) {\n      queryParams.set('acr_values', params.acrValues.join(' '));\n    }\n\n    if (params.nonce) {\n      queryParams.set('nonce', params.nonce);\n    }\n\n    if (params.uiLocales) {\n      queryParams.set('ui_locales', params.uiLocales);\n    }\n\n    if (params.display) {\n      queryParams.set('display', params.display);\n    }\n\n    if (typeof params.maxAge === 'number') {\n      queryParams.set('max_age', params.maxAge.toString());\n    }\n\n    if (params.prompt) {\n      queryParams.set('prompt', params.prompt);\n    }\n\n    if (params.audience) {\n      queryParams.set('audience', params.audience);\n    }\n\n    if (params.idTokenHint) {\n      queryParams.set('id_token_hint', params.idTokenHint);\n    }\n\n    const resource = parseSpaceSeparated(params.resource) ?? [];\n\n    if (resource.length > 0) {\n      for (const r of resource) {\n        queryParams.append('resource', r);\n      }\n    }\n\n    if (params.codeChallenge) {\n      queryParams.set('code_challenge', params.codeChallenge);\n      queryParams.set(\n        'code_challenge_method',\n        params.codeChallengeMethod ?? 'S256'\n      );\n    }\n\n    if (params.state) {\n      queryParams.set('state', params.state);\n    }\n\n    const metadata = await this.getMetadata();\n\n    assertMetadataProperty(metadata, 'authorization_endpoint');\n\n    return `${metadata.authorization_endpoint}?${queryParams.toString()}`;\n  }\n\n  /**\n   * Performs a pushed authorization request.\n   *\n   * @param params - Authorization Parameters.\n   *\n   * @returns Response from Pushed Authorization Request (PAR) endpoint.\n   *\n   * @throws {@link MonoCloudOPError} - When the request is invalid.\n   *\n   * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n   * unexpected status code during the request or a serialization error while processing the response.\n   *\n   */\n  async pushedAuthorizationRequest(\n    params: PushedAuthorizationParams\n  ): Promise<ParResponse> {\n    const body = new URLSearchParams();\n\n    body.set('client_id', this.clientId);\n\n    if (params.redirectUri) {\n      body.set('redirect_uri', params.redirectUri);\n    }\n\n    const scopes = parseSpaceSeparated(params.scopes) ?? [];\n\n    if (scopes.length > 0) {\n      body.set('scope', scopes.join(' '));\n    }\n\n    if (params.responseType && params.responseType.length > 0) {\n      body.set('response_type', params.responseType);\n    } else {\n      body.set('response_type', 'code');\n    }\n\n    if (params.authenticatorHint) {\n      body.set('authenticator_hint', params.authenticatorHint);\n    }\n\n    if (params.loginHint) {\n      body.set('login_hint', params.loginHint);\n    }\n\n    if (params.request) {\n      body.set('request', params.request);\n    }\n\n    if (params.responseMode) {\n      body.set('response_mode', params.responseMode);\n    }\n\n    if (params.acrValues && params.acrValues.length > 0) {\n      body.set('acr_values', params.acrValues.join(' '));\n    }\n\n    if (params.nonce) {\n      body.set('nonce', params.nonce);\n    }\n\n    if (params.uiLocales) {\n      body.set('ui_locales', params.uiLocales);\n    }\n\n    if (params.display) {\n      body.set('display', params.display);\n    }\n\n    if (typeof params.maxAge === 'number') {\n      body.set('max_age', params.maxAge.toString());\n    }\n\n    if (params.prompt) {\n      body.set('prompt', params.prompt);\n    }\n\n    if (params.audience) {\n      body.set('audience', params.audience);\n    }\n\n    if (params.idTokenHint) {\n      body.set('id_token_hint', params.idTokenHint);\n    }\n\n    const resource = parseSpaceSeparated(params.resource) ?? [];\n\n    if (resource.length > 0) {\n      for (const r of resource) {\n        body.append('resource', r);\n      }\n    }\n\n    if (params.codeChallenge) {\n      body.set('code_challenge', params.codeChallenge);\n      body.set('code_challenge_method', params.codeChallengeMethod ?? 'S256');\n    }\n\n    if (params.state) {\n      body.set('state', params.state);\n    }\n\n    const headers = {\n      'content-type': 'application/x-www-form-urlencoded',\n      accept: 'application/json',\n    };\n\n    await clientAuth(\n      this.clientId,\n      this.clientSecret,\n      this.authMethod,\n      this.tenantDomain,\n      headers,\n      body,\n      JWT_ASSERTION_CLOCK_SKEW\n    );\n\n    const metadata = await this.getMetadata();\n\n    const pushedAuthorizationRequestEndpoint = this.resolveEndpoint(\n      metadata,\n      'pushed_authorization_request_endpoint'\n    );\n\n    const response = await innerFetch(\n      pushedAuthorizationRequestEndpoint,\n      {\n        body: body.toString(),\n        method: 'POST',\n        headers,\n      },\n      this.fetcher,\n      this.responseTimeout\n    );\n\n    if (response.status === 400 || response.status === 401) {\n      const { raw, json } = await readErrorResponse(response);\n\n      throw new MonoCloudOPError(\n        json.error ?? 'par_request_failed',\n        json.error_description ?? 'Pushed Authorization Request Failed',\n        raw\n      );\n    }\n\n    if (response.status !== 201) {\n      const { raw } = await readErrorResponse(response);\n\n      throw new MonoCloudHttpError(\n        `Error while performing pushed authorization request. Unexpected status code: ${response.status}`,\n        raw\n      );\n    }\n\n    return await deserializeJson<ParResponse>(response);\n  }\n\n  /**\n   * Fetches userinfo associated with the provided access token.\n   *\n   * @param accessToken - A valid access token used to retrieve userinfo.\n   *\n   * @returns The authenticated user's claims.\n   *\n   * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n   * OAuth 2.0 error (e.g., 'invalid_token') in the 'WWW-Authenticate' header\n   * following a 401 Unauthorized response.\n   *\n   * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n   * unexpected status code during the request or a serialization error while processing the response.\n   *\n   * @throws {@link MonoCloudValidationError} - When the access token is invalid.\n   *\n   */\n  async userinfo(accessToken: string): Promise<UserinfoResponse> {\n    if (!accessToken.trim().length) {\n      throw new MonoCloudValidationError(\n        'Access token is required for fetching userinfo'\n      );\n    }\n\n    const metadata = await this.getMetadata();\n\n    assertMetadataProperty(metadata, 'userinfo_endpoint');\n\n    const response = await innerFetch(\n      metadata.userinfo_endpoint,\n      {\n        method: 'GET',\n        headers: {\n          authorization: `Bearer ${accessToken}`,\n        },\n      },\n      this.fetcher,\n      this.responseTimeout\n    );\n\n    if (response.status === 401 || response.status === 403) {\n      const { raw } = await readErrorResponse(response);\n\n      const authenticateError = response.headers.get('WWW-Authenticate') ?? '';\n\n      const errorMatch = /error=\"([^\"]+)\"/.exec(authenticateError);\n      const error = errorMatch ? errorMatch[1] : 'userinfo_failed';\n\n      const errorDescMatch = /error_description=\"([^\"]+)\"/.exec(\n        authenticateError\n      );\n\n      const errorDescription = errorDescMatch\n        ? errorDescMatch[1]\n        : 'Userinfo authentication error';\n\n      throw new MonoCloudTokenError(\n        `${error}: ${errorDescription}`,\n        error === 'insufficient_scope' ? 'insufficient_scope' : 'invalid_token',\n        raw\n      );\n    }\n\n    if (response.status !== 200) {\n      const { raw } = await readErrorResponse(response);\n\n      throw new MonoCloudHttpError(\n        `Error while fetching userinfo. Unexpected status code: ${response.status}`,\n        raw\n      );\n    }\n\n    return await deserializeJson<UserinfoResponse>(response);\n  }\n\n  /**\n   * Generates OpenID end session URL for signing out.\n   *\n   * Note - The `state` is added only when `postLogoutRedirectUri` is present.\n   *\n   * @param params - Parameters to build end session URL.\n   *\n   * @returns Tenant's end session URL.\n   *\n   * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n   * unexpected status code during the request or a serialization error while processing the response.\n   *\n   */\n  async endSessionUrl(params: EndSessionParameters): Promise<string> {\n    const queryParams = new URLSearchParams();\n\n    queryParams.set('client_id', this.clientId);\n\n    if (params.idTokenHint) {\n      queryParams.set('id_token_hint', params.idTokenHint);\n    }\n\n    if (params.postLogoutRedirectUri) {\n      queryParams.set('post_logout_redirect_uri', params.postLogoutRedirectUri);\n\n      if (params.state) {\n        queryParams.set('state', params.state);\n      }\n    }\n\n    const metadata = await this.getMetadata();\n\n    assertMetadataProperty(metadata, 'end_session_endpoint');\n\n    return `${metadata.end_session_endpoint}?${queryParams.toString()}`;\n  }\n\n  /**\n   * Exchanges an authorization code for tokens.\n   *\n   * @param code - The authorization code received from the authorization server.\n   * @param redirectUri - The redirect URI used in the initial authorization request.\n   * @param codeVerifier - Code verifier for PKCE.\n   * @param resource - Space-separated list of resources the access token should be scoped to.\n   *\n   * @returns Tokens obtained by exchanging an authorization code at the token endpoint.\n   *\n   * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n   * OAuth 2.0 error response.\n   *\n   * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n   * unexpected status code during the request or a serialization error while processing the response.\n   *\n   */\n  async exchangeAuthorizationCode(\n    code: string,\n    redirectUri: string,\n    codeVerifier?: string,\n    resource?: string\n  ): Promise<Tokens> {\n    const body = new URLSearchParams();\n\n    body.set('grant_type', 'authorization_code');\n    body.set('code', code);\n    body.set('redirect_uri', redirectUri);\n\n    if (codeVerifier) {\n      body.set('code_verifier', codeVerifier);\n    }\n\n    const resources = parseSpaceSeparated(resource) ?? [];\n\n    if (resources.length > 0) {\n      for (const r of resources) {\n        body.append('resource', r);\n      }\n    }\n\n    const headers = {\n      'content-type': 'application/x-www-form-urlencoded',\n      accept: 'application/json',\n    };\n\n    await clientAuth(\n      this.clientId,\n      this.clientSecret,\n      this.authMethod,\n      this.tenantDomain,\n      headers,\n      body,\n      JWT_ASSERTION_CLOCK_SKEW\n    );\n\n    const metadata = await this.getMetadata();\n\n    const tokenEndpoint = this.resolveEndpoint(metadata, 'token_endpoint');\n\n    const response = await innerFetch(\n      tokenEndpoint,\n      {\n        method: 'POST',\n        body: body.toString(),\n        headers,\n      },\n      this.fetcher,\n      this.responseTimeout\n    );\n\n    if (response.status === 400 || response.status === 401) {\n      const { raw, json } = await readErrorResponse(response);\n\n      throw new MonoCloudOPError(\n        json.error ?? 'code_grant_failed',\n        json.error_description ?? 'Authorization code grant failed',\n        raw\n      );\n    }\n\n    if (response.status !== 200) {\n      const { raw } = await readErrorResponse(response);\n\n      throw new MonoCloudHttpError(\n        `Error while performing token grant. Unexpected status code: ${response.status}`,\n        raw\n      );\n    }\n\n    return await deserializeJson<Tokens>(response);\n  }\n\n  /**\n   * Exchanges a refresh token for new tokens.\n   *\n   * @param refreshToken - The refresh token used to request new tokens.\n   * @param options - Refresh grant options.\n   *\n   * @returns Tokens obtained by exchanging a refresh token at the token endpoint.\n   *\n   * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n   * OAuth 2.0 error response.\n   *\n   * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n   * unexpected status code during the request or a serialization error while processing the response.\n   *\n   */\n  async refreshGrant(\n    refreshToken: string,\n    options?: RefreshGrantOptions\n  ): Promise<Tokens> {\n    const body = new URLSearchParams();\n\n    body.set('grant_type', 'refresh_token');\n    body.set('refresh_token', refreshToken);\n\n    const scopes = parseSpaceSeparated(options?.scopes) ?? [];\n\n    if (scopes.length > 0) {\n      body.set('scope', scopes.join(' '));\n    }\n\n    const resource = parseSpaceSeparated(options?.resource) ?? [];\n\n    if (resource.length > 0) {\n      for (const r of resource) {\n        body.append('resource', r);\n      }\n    }\n\n    const headers = {\n      'content-type': 'application/x-www-form-urlencoded',\n      accept: 'application/json',\n    };\n\n    await clientAuth(\n      this.clientId,\n      this.clientSecret,\n      this.authMethod,\n      this.tenantDomain,\n      headers,\n      body,\n      JWT_ASSERTION_CLOCK_SKEW\n    );\n\n    const metadata = await this.getMetadata();\n\n    const tokenEndpoint = this.resolveEndpoint(metadata, 'token_endpoint');\n\n    const response = await innerFetch(\n      tokenEndpoint,\n      {\n        method: 'POST',\n        body: body.toString(),\n        headers,\n      },\n      this.fetcher,\n      this.responseTimeout\n    );\n\n    if (response.status === 400 || response.status === 401) {\n      const { raw, json } = await readErrorResponse(response);\n\n      throw new MonoCloudOPError(\n        json.error ?? 'refresh_grant_failed',\n        json.error_description ?? 'Refresh token grant failed',\n        raw\n      );\n    }\n\n    if (response.status !== 200) {\n      const { raw } = await readErrorResponse(response);\n\n      throw new MonoCloudHttpError(\n        `Error while performing refresh token grant. Unexpected status code: ${response.status}`,\n        raw\n      );\n    }\n\n    return await deserializeJson<Tokens>(response);\n  }\n\n  /**\n   * Generates a session with user and tokens by exchanging authorization code from callback params.\n   *\n   * @param code - The authorization code received from the callback.\n   * @param redirectUri - The redirect URI that was used in the authorization request.\n   * @param requestedScopes - A space-separated list of scopes originally requested via the `/authorize` endpoint.\n   * This is stored in the session to ensure the correct access token can be identified and refreshed during `refreshSession()`.\n   * @param resource - A space-separated list of resource indicators originally requested via the `/authorize` endpoint.\n   * Used alongside scopes to uniquely identify and refresh the specific access token associated with these resources.\n   * @param options - Options for authenticating a user with authorization code.\n   *\n   * @returns The user's session containing authentication tokens and user information.\n   *\n   * @throws {@link MonoCloudValidationError} - When the token scope does not contain the openid scope,\n   * or if 'expires_in' or 'scope' is missing from the token response.\n   *\n   * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized.\n   * OAuth 2.0 error response.\n   *\n   * @throws {@link MonoCloudTokenError} - If ID Token validation fails.\n   *\n   * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n   * unexpected status code during the request or a serialization error while processing the response.\n   *\n   */\n  async authenticate(\n    code: string,\n    redirectUri: string,\n    requestedScopes: string,\n    resource?: string,\n    options?: AuthenticateOptions\n  ): Promise<MonoCloudSession> {\n    const tokens = await this.exchangeAuthorizationCode(\n      code,\n      redirectUri,\n      options?.codeVerifier,\n      resource\n    );\n\n    const accessTokenExpiration =\n      typeof tokens.expires_in === 'number'\n        ? now() + tokens.expires_in\n        : undefined;\n\n    if (!accessTokenExpiration) {\n      throw new MonoCloudValidationError(\"Missing required 'expires_in' field\");\n    }\n\n    if (!tokens.scope) {\n      throw new MonoCloudValidationError(\"Missing or invalid 'scope' field\");\n    }\n\n    let userinfo: MonoCloudUser | undefined;\n\n    if (\n      options?.fetchUserInfo &&\n      parseSpaceSeparatedSet(tokens.scope).has('openid')\n    ) {\n      userinfo = await this.userinfo(tokens.access_token);\n    }\n\n    let idTokenClaims: Partial<IdTokenClaims> = {};\n\n    if (tokens.id_token) {\n      if (options?.validateIdToken ?? true) {\n        const jwks = options?.jwks ?? (await this.getJwks());\n\n        idTokenClaims = await this.validateIdToken(\n          tokens.id_token,\n          jwks.keys,\n          options?.idTokenClockSkew ?? 0,\n          options?.idTokenClockTolerance ?? 60,\n          options?.idTokenMaxAge,\n          options?.idTokenNonce\n        );\n      } else {\n        idTokenClaims = MonoCloudOidcClient.decodeJwt(tokens.id_token);\n      }\n    }\n\n    (options?.filteredIdTokenClaims ?? FILTER_ID_TOKEN_CLAIMS).forEach(x => {\n      // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n      delete idTokenClaims[x];\n    });\n\n    const session: MonoCloudSession = {\n      user: profileSync(undefined, idTokenClaims, userinfo, true),\n      idToken: tokens.id_token,\n      refreshToken: tokens.refresh_token,\n      authorizedScopes: requestedScopes,\n      accessTokens: [\n        {\n          scopes: tokens.scope,\n          accessToken: tokens.access_token,\n          accessTokenExpiration,\n          resource,\n          requestedScopes,\n        },\n      ],\n    };\n\n    await options?.onSessionCreating?.(session, idTokenClaims, userinfo);\n\n    return session;\n  }\n\n  /**\n   * Refetches user information for an existing session using the userinfo endpoint.\n   * Updates the session's user object with the latest user information.\n   *\n   * @param accessToken - Access token used to fetch the userinfo.\n   * @param session - The current MonoCloudSession.\n   * @param options - Userinfo refetch options.\n   *\n   * @returns Updated session with the latest userinfo.\n   *\n   * @throws {@link MonoCloudValidationError} - When the token scope does not contain `openid` scope\n   *\n   * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n   * OAuth 2.0 error response.\n   *\n   * @throws {@link MonoCloudTokenError} - If ID Token validation fails\n   *\n   * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n   * unexpected status code during the request or a serialization error while processing the response.\n   *\n   */\n  async refetchUserInfo(\n    accessToken: AccessToken,\n    session: MonoCloudSession,\n    options?: RefetchUserInfoOptions\n  ): Promise<MonoCloudSession> {\n    if (!parseSpaceSeparatedSet(accessToken.scopes).has('openid')) {\n      throw new MonoCloudValidationError(\n        'Fetching userinfo requires the openid scope'\n      );\n    }\n\n    const userinfo = await this.userinfo(accessToken.accessToken);\n\n    const idTokenClaims =\n      session.idToken && options?.strictProfileSync\n        ? MonoCloudOidcClient.decodeJwt(session.idToken)\n        : undefined;\n\n    // eslint-disable-next-line no-param-reassign\n    session.user = profileSync(\n      session.user,\n      idTokenClaims,\n      userinfo,\n      options?.strictProfileSync\n    );\n\n    await options?.onSessionCreating?.(session, undefined, userinfo);\n\n    return session;\n  }\n\n  /**\n   * Refreshes an existing session using the refresh token.\n   * This function requests new tokens using the refresh token and optionally updates user information.\n   *\n   * @param session - The current MonoCloudSession containing the refresh token.\n   * @param options - Session refresh options.\n   *\n   * @returns User's session containing refreshed authentication tokens and user information.\n   *\n   * @throws {@link MonoCloudValidationError} - If the refresh token is not present in the session,\n   * or if 'expires_in' or 'scope' (including the openid scope) is missing from the token response.\n   *\n   * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n   * OAuth 2.0 error response.\n   *\n   * @throws {@link MonoCloudTokenError} - If ID Token validation fails\n   *\n   * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n   * unexpected status code during the request or a serialization error while processing the response.\n   *\n   */\n  async refreshSession(\n    session: MonoCloudSession,\n    options?: RefreshSessionOptions\n  ): Promise<MonoCloudSession> {\n    if (!session.refreshToken) {\n      throw new MonoCloudValidationError(\n        'Session does not contain refresh token'\n      );\n    }\n\n    const tokens = await this.refreshGrant(\n      session.refreshToken,\n      options?.refreshGrantOptions\n    );\n\n    const accessTokenExpiration =\n      typeof tokens.expires_in === 'number'\n        ? now() + tokens.expires_in\n        : undefined;\n\n    if (!accessTokenExpiration) {\n      throw new MonoCloudValidationError(\"Missing required 'expires_in' field\");\n    }\n\n    if (!tokens.scope) {\n      throw new MonoCloudValidationError(\"Missing or invalid 'scope' field\");\n    }\n\n    let userinfo: MonoCloudUser | undefined;\n\n    if (\n      options?.fetchUserInfo &&\n      parseSpaceSeparatedSet(tokens.scope).has('openid')\n    ) {\n      userinfo = await this.userinfo(tokens.access_token);\n    }\n\n    let idTokenClaims: Partial<IdTokenClaims> = {};\n\n    if (tokens.id_token) {\n      if (options?.validateIdToken ?? true) {\n        const jwks = options?.jwks ?? (await this.getJwks());\n\n        idTokenClaims = await this.validateIdToken(\n          tokens.id_token,\n          jwks.keys,\n          options?.idTokenClockSkew ?? 0,\n          options?.idTokenClockTolerance ?? 60\n        );\n      } else {\n        idTokenClaims = MonoCloudOidcClient.decodeJwt(tokens.id_token);\n      }\n    } else if (session.idToken) {\n      idTokenClaims = MonoCloudOidcClient.decodeJwt(session.idToken);\n    }\n\n    (options?.filteredIdTokenClaims ?? FILTER_ID_TOKEN_CLAIMS).forEach(x => {\n      // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n      delete idTokenClaims[x];\n    });\n\n    const resource = options?.refreshGrantOptions?.resource;\n    let scopes = options?.refreshGrantOptions?.scopes;\n\n    if (!resource && !scopes) {\n      scopes = session.authorizedScopes;\n    }\n\n    const accessToken = findToken(session.accessTokens, resource, scopes);\n\n    const user = profileSync(\n      session.user,\n      idTokenClaims,\n      userinfo,\n      options?.strictProfileSync\n    );\n\n    const newTokens =\n      session.accessTokens?.filter(t => t !== accessToken) ?? [];\n\n    newTokens.push({\n      scopes: tokens.scope,\n      accessToken: tokens.access_token,\n      accessTokenExpiration,\n      resource,\n      requestedScopes: scopes,\n    });\n\n    const updatedSession: MonoCloudSession = {\n      ...session,\n      user,\n      idToken: tokens.id_token ?? session.idToken,\n      refreshToken: tokens.refresh_token ?? session.refreshToken,\n      accessTokens: newTokens,\n    };\n\n    await options?.onSessionCreating?.(updatedSession, idTokenClaims, userinfo);\n\n    return updatedSession;\n  }\n\n  /**\n   * Revokes an access token or refresh token, rendering it invalid for future use.\n   *\n   * @param token - The token string to be revoked.\n   * @param tokenType - Hint about the token type ('access_token' or 'refresh_token').\n   *\n   * @returns If token revocation succeeded.\n   *\n   * @throws {@link MonoCloudValidationError} - If token is invalid or unsupported token type\n   *\n   * @throws {@link MonoCloudOPError} - When the OpenID Provider returns a standardized\n   * OAuth 2.0 error response.\n   *\n   * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n   * unexpected status code during the request or a serialization error while processing the response.\n   */\n  async revokeToken(token: string, tokenType?: string): Promise<void> {\n    if (!token.trim().length) {\n      throw new MonoCloudValidationError('Invalid token');\n    }\n\n    if (\n      tokenType &&\n      tokenType !== 'access_token' &&\n      tokenType !== 'refresh_token'\n    ) {\n      throw new MonoCloudValidationError(\n        'Only access_token and refresh_token types are supported.'\n      );\n    }\n\n    const body = new URLSearchParams();\n    body.set('token', token);\n    if (tokenType) {\n      body.set('token_type_hint', tokenType);\n    }\n\n    const headers = {\n      'content-type': 'application/x-www-form-urlencoded',\n    };\n\n    await clientAuth(\n      this.clientId,\n      this.clientSecret,\n      this.authMethod,\n      this.tenantDomain,\n      headers,\n      body,\n      JWT_ASSERTION_CLOCK_SKEW\n    );\n\n    const metadata = await this.getMetadata();\n\n    const revocationEndpoint = this.resolveEndpoint(\n      metadata,\n      'revocation_endpoint'\n    );\n\n    const response = await innerFetch(\n      revocationEndpoint,\n      {\n        method: 'POST',\n        body: body.toString(),\n        headers,\n      },\n      this.fetcher,\n      this.responseTimeout\n    );\n\n    if (response.status === 400 || response.status === 401) {\n      const { raw, json } = await readErrorResponse(response);\n\n      throw new MonoCloudOPError(\n        json.error ?? 'revocation_failed',\n        json.error_description ?? 'Token revocation failed',\n        raw\n      );\n    }\n\n    if (response.status !== 200) {\n      const { raw } = await readErrorResponse(response);\n\n      throw new MonoCloudHttpError(\n        `Error while performing revocation request. Unexpected status code: ${response.status}`,\n        raw\n      );\n    }\n  }\n\n  /**\n   * Validates an ID Token.\n   *\n   * @param idToken - The ID Token JWT string to validate.\n   * @param jwks - Array of JSON Web Keys (JWK) used to verify the token's signature.\n   * @param clockSkew - Number of seconds to adjust the current time to account for clock differences.\n   * @param clockTolerance - Additional time tolerance in seconds for time-based claim validation.\n   * @param maxAge - Maximum authentication age in seconds.\n   * @param nonce - Nonce value to validate against the token's nonce claim.\n   *\n   * @returns Validated ID Token claims.\n   *\n   * @throws {@link MonoCloudTokenError} - If ID Token validation fails\n   *\n   */\n  async validateIdToken(\n    idToken: string,\n    jwks: Jwk[],\n    clockSkew: number,\n    clockTolerance: number,\n    maxAge?: number,\n    nonce?: string\n  ): Promise<IdTokenClaims> {\n    if (typeof idToken !== 'string' || idToken.trim().length === 0) {\n      throw new MonoCloudTokenError(\n        'ID Token must be a valid non-empty string'\n      );\n    }\n\n    const {\n      0: protectedHeader,\n      1: payload,\n      2: encodedSignature,\n      length,\n    } = idToken.split('.');\n\n    if (length !== 3) {\n      throw new MonoCloudTokenError(\n        'ID Token must have a header, payload and signature'\n      );\n    }\n\n    let header: JwsHeaderParameters;\n    try {\n      header = JSON.parse(decodeBase64Url(protectedHeader));\n    } catch {\n      throw new MonoCloudTokenError('Failed to parse JWT Header');\n    }\n\n    if (\n      header === null ||\n      typeof header !== 'object' ||\n      Array.isArray(header)\n    ) {\n      throw new MonoCloudTokenError('JWT Header must be a top level object');\n    }\n\n    if (this.idTokenSigningAlgorithm !== header.alg) {\n      throw new MonoCloudTokenError('Invalid signing alg');\n    }\n\n    if (header.crit !== undefined) {\n      throw new MonoCloudTokenError('Unexpected JWT \"crit\" header parameter');\n    }\n\n    const binary = decodeBase64Url(encodedSignature);\n\n    const signature = new Uint8Array(binary.length);\n\n    for (let i = 0; i < binary.length; i++) {\n      signature[i] = binary.charCodeAt(i);\n    }\n\n    const key = await getPublicSigKeyFromIssuerJwks(jwks, header);\n\n    const input = `${protectedHeader}.${payload}`;\n\n    const verified = await crypto.subtle.verify(\n      keyToSubtle(key),\n      key,\n      signature,\n      stringToArrayBuffer(input) as BufferSource\n    );\n\n    if (!verified) {\n      throw new MonoCloudTokenError('JWT signature verification failed');\n    }\n\n    let claims: IdTokenClaims;\n\n    try {\n      claims = JSON.parse(decodeBase64Url(payload));\n    } catch {\n      throw new MonoCloudTokenError('Failed to parse JWT Payload');\n    }\n\n    if (\n      claims === null ||\n      typeof claims !== 'object' ||\n      Array.isArray(claims)\n    ) {\n      throw new MonoCloudTokenError('JWT Payload must be a top level object');\n    }\n\n    if ((claims.nonce || nonce) && claims.nonce !== nonce) {\n      throw new MonoCloudTokenError('Nonce mismatch');\n    }\n\n    const current = now() + clockSkew;\n\n    /* v8 ignore else -- @preserve */\n    if (claims.exp !== undefined) {\n      if (typeof claims.exp !== 'number') {\n        throw new MonoCloudTokenError(\n          'Unexpected JWT \"exp\" (expiration time) claim type'\n        );\n      }\n\n      if (claims.exp <= current - clockTolerance) {\n        throw new MonoCloudTokenError(\n          'Unexpected JWT \"exp\" (expiration time) claim value, timestamp is <= now()'\n        );\n      }\n    }\n\n    /* v8 ignore else -- @preserve */\n    if (claims.iat !== undefined) {\n      if (typeof claims.iat !== 'number') {\n        throw new MonoCloudTokenError(\n          'Unexpected JWT \"iat\" (issued at) claim type'\n        );\n      }\n    }\n\n    if (typeof maxAge === 'number') {\n      if (typeof claims.auth_time !== 'number') {\n        throw new MonoCloudTokenError(\n          'Missing or invalid JWT \"auth_time\" (authentication time) claim, required when max_age is requested'\n        );\n      }\n\n      if (claims.auth_time + maxAge < current - clockTolerance) {\n        throw new MonoCloudTokenError(\n          'Too much time has elapsed since the last End-User authentication'\n        );\n      }\n    }\n\n    if (claims.iss !== this.tenantDomain) {\n      throw new MonoCloudTokenError('Invalid Issuer');\n    }\n\n    if (claims.nbf !== undefined) {\n      if (typeof claims.nbf !== 'number') {\n        throw new MonoCloudTokenError(\n          'Unexpected JWT \"nbf\" (not before) claim type'\n        );\n      }\n\n      if (claims.nbf > current + clockTolerance) {\n        throw new MonoCloudTokenError(\n          'Unexpected JWT \"nbf\" (not before) claim value, timestamp is > now()'\n        );\n      }\n    }\n\n    const audience = Array.isArray(claims.aud) ? claims.aud : [claims.aud];\n\n    if (!audience.includes(this.clientId)) {\n      throw new MonoCloudTokenError('Invalid audience claim');\n    }\n\n    return claims;\n  }\n\n  /**\n   * Validates an OpenID Connect Back-Channel Logout Token.\n   *\n   * @param logoutToken - The Logout Token JWT string to validate.\n   * @param clockSkew - Number of seconds to adjust the current time to account for clock differences.\n   * @param clockTolerance - Additional time tolerance in seconds for time-based claim validation.\n   *\n   * @returns Validated Logout Token claims.\n   *\n   * @throws {@link MonoCloudTokenError} - If Logout Token validation fails\n   *\n   * @throws {@link MonoCloudHttpError} - Thrown if there is a network error while fetching the issuer metadata or JWKS.\n   *\n   */\n  async validateLogoutToken(\n    logoutToken: string,\n    clockSkew: number,\n    clockTolerance: number\n  ): Promise<LogoutTokenClaims> {\n    if (typeof logoutToken !== 'string' || !isPresent(logoutToken)) {\n      throw new MonoCloudTokenError(\n        'Logout Token must be a valid non-empty string'\n      );\n    }\n\n    const {\n      0: protectedHeader,\n      1: payload,\n      2: encodedSignature,\n      length,\n    } = logoutToken.split('.');\n\n    if (length !== 3) {\n      throw new MonoCloudTokenError(\n        'Logout Token must have a header, payload and signature'\n      );\n    }\n\n    let header: JwsHeaderParameters;\n    try {\n      header = JSON.parse(decodeBase64Url(protectedHeader));\n    } catch {\n      throw new MonoCloudTokenError('Failed to parse JWT Header');\n    }\n\n    if (\n      header === null ||\n      typeof header !== 'object' ||\n      Array.isArray(header)\n    ) {\n      throw new MonoCloudTokenError('JWT Header must be a top level object');\n    }\n\n    if (this.idTokenSigningAlgorithm !== header.alg) {\n      throw new MonoCloudTokenError('Invalid signing alg');\n    }\n\n    if (header.crit !== undefined) {\n      throw new MonoCloudTokenError('Unexpected JWT \"crit\" header parameter');\n    }\n\n    const binary = decodeBase64Url(encodedSignature);\n\n    const signature = new Uint8Array(binary.length);\n\n    for (let i = 0; i < binary.length; i++) {\n      signature[i] = binary.charCodeAt(i);\n    }\n\n    const jwks = await this.getJwks();\n\n    const key = await getPublicSigKeyFromIssuerJwks(jwks.keys, header);\n\n    const input = `${protectedHeader}.${payload}`;\n\n    const verified = await crypto.subtle.verify(\n      keyToSubtle(key),\n      key,\n      signature,\n      stringToArrayBuffer(input) as BufferSource\n    );\n\n    if (!verified) {\n      throw new MonoCloudTokenError('JWT signature verification failed');\n    }\n\n    let claims: LogoutTokenClaims;\n\n    try {\n      claims = JSON.parse(decodeBase64Url(payload));\n    } catch {\n      throw new MonoCloudTokenError('Failed to parse JWT Payload');\n    }\n\n    if (\n      claims === null ||\n      typeof claims !== 'object' ||\n      Array.isArray(claims)\n    ) {\n      throw new MonoCloudTokenError('JWT Payload must be a top level object');\n    }\n\n    const metadata = await this.getMetadata();\n\n    if (claims.iss !== metadata.issuer) {\n      throw new MonoCloudTokenError('Invalid Issuer');\n    }\n\n    const audience = Array.isArray(claims.aud) ? claims.aud : [claims.aud];\n\n    if (!audience.includes(this.clientId)) {\n      throw new MonoCloudTokenError('Invalid audience claim');\n    }\n\n    if (claims.iat === undefined) {\n      throw new MonoCloudTokenError('Missing JWT \"iat\" (issued at) claim');\n    }\n\n    if (typeof claims.iat !== 'number') {\n      throw new MonoCloudTokenError(\n        'Unexpected JWT \"iat\" (issued at) claim type'\n      );\n    }\n\n    const current = now() + clockSkew;\n\n    if (claims.exp !== undefined) {\n      if (typeof claims.exp !== 'number') {\n        throw new MonoCloudTokenError(\n          'Unexpected JWT \"exp\" (expiration time) claim type'\n        );\n      }\n\n      if (claims.exp <= current - clockTolerance) {\n        throw new MonoCloudTokenError(\n          'Unexpected JWT \"exp\" (expiration time) claim value, timestamp is <= now()'\n        );\n      }\n    }\n\n    if (claims.nbf !== undefined) {\n      if (typeof claims.nbf !== 'number') {\n        throw new MonoCloudTokenError(\n          'Unexpected JWT \"nbf\" (not before) claim type'\n        );\n      }\n\n      if (claims.nbf > current + clockTolerance) {\n        throw new MonoCloudTokenError(\n          'Unexpected JWT \"nbf\" (not before) claim value, timestamp is > now()'\n        );\n      }\n    }\n\n    if (!claims.sub && !claims.sid) {\n      throw new MonoCloudTokenError(\n        'Logout Token must contain a \"sub\" (subject) or \"sid\" (session ID) claim'\n      );\n    }\n\n    if (claims.nonce !== undefined) {\n      throw new MonoCloudTokenError(\n        'Logout Token must not contain a \"nonce\" claim'\n      );\n    }\n\n    const { events } = claims as Record<string, unknown>;\n\n    if (\n      events === null ||\n      typeof events !== 'object' ||\n      Array.isArray(events)\n    ) {\n      throw new MonoCloudTokenError('Invalid JWT \"events\" claim');\n    }\n\n    const event = (events as Record<string, unknown>)[\n      'http://schemas.openid.net/event/backchannel-logout'\n    ];\n\n    if (event === null || typeof event !== 'object' || Array.isArray(event)) {\n      throw new MonoCloudTokenError(\n        'Logout Token must contain the back-channel logout event'\n      );\n    }\n\n    return claims;\n  }\n\n  /**\n   * Performs a device authorization request.\n   *\n   * @param params - Device Authorization Parameters.\n   *\n   * @returns Response from Device Authorization endpoint.\n   *\n   * @throws {@link MonoCloudOPError} - When the request is invalid.\n   *\n   * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n   * unexpected status code during the request or a serialization error while processing the response.\n   *\n   */\n  async deviceAuthorizationRequest(\n    params: DeviceAuthorizationParams\n  ): Promise<DeviceAuthorizationResponse> {\n    const body = new URLSearchParams();\n\n    body.set('client_id', this.clientId);\n\n    const scopes = parseSpaceSeparated(params.scopes) ?? [];\n\n    if (scopes.length > 0) {\n      body.set('scope', scopes.join(' '));\n    }\n\n    const resource = parseSpaceSeparated(params?.resource) ?? [];\n\n    if (resource.length > 0) {\n      for (const r of resource) {\n        body.append('resource', r);\n      }\n    }\n\n    const headers = {\n      'content-type': 'application/x-www-form-urlencoded',\n      accept: 'application/json',\n    };\n\n    await clientAuth(\n      this.clientId,\n      this.clientSecret,\n      this.authMethod,\n      this.tenantDomain,\n      headers,\n      body,\n      JWT_ASSERTION_CLOCK_SKEW\n    );\n\n    const metadata = await this.getMetadata();\n\n    const deviceAuthorizationEndpoint = this.resolveEndpoint(\n      metadata,\n      'device_authorization_endpoint'\n    );\n\n    const response = await innerFetch(\n      deviceAuthorizationEndpoint,\n      {\n        body: body.toString(),\n        method: 'POST',\n        headers,\n      },\n      this.fetcher,\n      this.responseTimeout\n    );\n\n    if (response.status === 400 || response.status === 401) {\n      const { raw, json } = await readErrorResponse(response);\n\n      throw new MonoCloudOPError(\n        json.error ?? 'device_authorization_failed',\n        json.error_description ?? 'Device Authorization Request Failed',\n        raw\n      );\n    }\n\n    if (response.status !== 200) {\n      const { raw } = await readErrorResponse(response);\n\n      throw new MonoCloudHttpError(\n        `Error while performing device authorization request. Unexpected status code: ${response.status}`,\n        raw\n      );\n    }\n\n    return await deserializeJson<DeviceAuthorizationResponse>(response);\n  }\n\n  /**\n   * Exchanges a device code for tokens.\n   *\n   * @param deviceCode - The device code received from the device authorization server.\n   *\n   * @returns Tokens obtained by exchanging a device code at the token endpoint.\n   *\n   * @throws {@link MonoCloudOPError} - When the authorization server returns a standardized\n   * OAuth 2.0 error response.\n   *\n   * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n   * unexpected status code during the request or a serialization error while processing the response.\n   *\n   */\n  async deviceAuthorizationGrant(deviceCode: string): Promise<Tokens> {\n    const body = new URLSearchParams();\n\n    body.set('grant_type', 'urn:ietf:params:oauth:grant-type:device_code');\n    body.set('device_code', deviceCode);\n\n    const headers = {\n      'content-type': 'application/x-www-form-urlencoded',\n      accept: 'application/json',\n    };\n\n    await clientAuth(\n      this.clientId,\n      this.clientSecret,\n      this.authMethod,\n      this.tenantDomain,\n      headers,\n      body,\n      JWT_ASSERTION_CLOCK_SKEW\n    );\n\n    const metadata = await this.getMetadata();\n\n    const tokenEndpoint = this.resolveEndpoint(metadata, 'token_endpoint');\n\n    const response = await innerFetch(\n      tokenEndpoint,\n      {\n        method: 'POST',\n        body: body.toString(),\n        headers,\n      },\n      this.fetcher,\n      this.responseTimeout\n    );\n\n    if (response.status === 400 || response.status === 401) {\n      const { raw, json } = await readErrorResponse(response);\n\n      throw new MonoCloudOPError(\n        json.error ?? 'device_token_failed',\n        json.error_description ?? 'Device code token grant failed',\n        raw\n      );\n    }\n\n    if (response.status !== 200) {\n      const { raw } = await readErrorResponse(response);\n\n      throw new MonoCloudHttpError(\n        `Error while performing token grant. Unexpected status code: ${response.status}`,\n        raw\n      );\n    }\n\n    return await deserializeJson<Tokens>(response);\n  }\n}\n","import {\n  arrayBufferToBase64,\n  decodeBase64Url,\n  getPublicSigKeyFromIssuerJwks,\n  now,\n  parseSpaceSeparated,\n  stringToArrayBuffer,\n  timingSafeEqual,\n} from './utils/internal';\nimport { isUserInGroup } from './utils';\nimport { clientAuth, keyToSubtle } from './client-auth';\nimport {\n  AccessTokenClaims,\n  CertificateBindingValidation,\n  ClientAuthMethod,\n  IntrospectOptions,\n  IsUserInGroupOptions,\n  Jwk,\n  JwsHeaderParameters,\n  ValidateJwtAccessTokenOptions,\n  MonoCloudOidcBackendClientOptions,\n} from './types';\nimport { MonoCloudOPError } from './errors/monocloud-op-error';\nimport { MonoCloudHttpError } from './errors/monocloud-http-error';\nimport { MonoCloudValidationError } from './errors/monocloud-validation-error';\nimport { MonoCloudTokenError } from './errors/monocloud-token-error';\nimport { MonoCloudOidcClientBase } from './monocloud-oidc-client-base';\nimport {\n  deserializeJson,\n  innerFetch,\n  readErrorResponse,\n  JWT_ASSERTION_CLOCK_SKEW,\n} from './helper';\n\nconst isCertificateBoundCnf = (cnf: unknown): boolean => {\n  if (cnf === undefined || cnf === null) {\n    return false;\n  }\n\n  let value: unknown = cnf;\n\n  if (typeof value === 'string') {\n    try {\n      value = JSON.parse(value) as unknown;\n    } catch {\n      return true;\n    }\n  }\n\n  // A `cnf` that cannot be parsed is treated as certificate-bound, so that validation runs and rejects it rather than silently skipping a broken claim.\n  if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n    return true;\n  }\n\n  return 'x5t#S256' in value;\n};\n\n/**\n * @category Classes\n */\nexport class MonoCloudOidcBackendClient extends MonoCloudOidcClientBase {\n  private readonly clientId?: string;\n\n  private readonly clientSecret?: string | Jwk;\n\n  private readonly authMethod: ClientAuthMethod;\n\n  private readonly audience: string;\n\n  private readonly groupOptions?: IsUserInGroupOptions;\n\n  /**\n   * Number of seconds to adjust the current time to account for clock differences between the client and server during time-based claim validation. Defaults to 0.\n   */\n  protected clockSkew = 0;\n\n  /**\n   * Additional time tolerance in seconds applied when validating time-based claims (`exp`, `nbf`). Defaults to 60 (1 minute).\n   */\n  protected clockTolerance = 60;\n\n  /**\n   * Creates a new instance of MonoCloudOidcBackendClient.\n   *\n   * @param tenantDomain - The tenant domain URL.\n   * @param audience - The expected audience value used to validate the `aud` claim in access tokens.\n   * @param options - Additional client configuration options.\n   */\n  constructor(\n    tenantDomain: string,\n    audience: string,\n    options?: MonoCloudOidcBackendClientOptions\n  ) {\n    super({\n      tenantDomain,\n      metadataCacheDuration: options?.metadataCacheDuration,\n      jwksCacheDuration: options?.jwksCacheDuration,\n      fetcher: options?.fetcher,\n      responseTimeout: options?.responseTimeout,\n      clientAuthMethod: options?.clientAuthMethod ?? 'client_secret_basic',\n      trustStoreId: options?.trustStoreId,\n      metadataResolver: options?.metadataResolver,\n      jwksResolver: options?.jwksResolver,\n    });\n    this.audience = audience;\n\n    if (options?.clientId) {\n      this.clientId = options.clientId;\n    }\n    this.clientSecret = options?.clientSecret;\n    this.authMethod = options?.clientAuthMethod ?? 'client_secret_basic';\n    this.groupOptions = options?.groupOptions;\n\n    if (options?.clockSkew !== undefined) {\n      this.clockSkew = options.clockSkew;\n    }\n\n    if (options?.clockTolerance !== undefined) {\n      this.clockTolerance = options.clockTolerance;\n    }\n  }\n\n  /**\n   * Validates an opaque access token using the OAuth 2.0 Token Introspection endpoint (RFC 7662).\n   *\n   * @param accessToken - The access token string to introspect.\n   * @param options - Claims validation options.\n   *\n   * @returns Validated access token claims (without the `active` field).\n   *\n   * @throws {@link MonoCloudTokenError} - If the token is not active or claim validation fails.\n   *\n   * @throws {@link MonoCloudOPError} - When the introspection endpoint returns a standardized\n   * OAuth 2.0 error response.\n   *\n   * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n   * unexpected status code during the request or a serialization error while processing the response.\n   *\n   * @throws {@link MonoCloudValidationError} - When the access token is empty or the introspection\n   * endpoint is not available in the issuer metadata or claims validation fails.\n   *\n   */\n  async introspectAccessToken(\n    accessToken: string,\n    options?: IntrospectOptions\n  ): Promise<AccessTokenClaims> {\n    if (!this.clientId) {\n      throw new MonoCloudValidationError(\n        'The clientId option must be configured to introspect access tokens'\n      );\n    }\n\n    if (typeof accessToken !== 'string' || accessToken.trim().length === 0) {\n      throw new MonoCloudValidationError(\n        'Access token must be a valid non-empty string'\n      );\n    }\n\n    const metadata = await this.getMetadata();\n\n    const introspectionEndpoint = this.resolveEndpoint(\n      metadata,\n      'introspection_endpoint'\n    );\n\n    const body = new URLSearchParams();\n    body.set('token', accessToken);\n    body.set('token_type_hint', 'access_token');\n\n    const headers: Record<string, string> = {\n      'content-type': 'application/x-www-form-urlencoded',\n      accept: 'application/json',\n    };\n\n    await clientAuth(\n      this.clientId,\n      this.clientSecret,\n      this.authMethod,\n      this.tenantDomain,\n      headers,\n      body,\n      JWT_ASSERTION_CLOCK_SKEW\n    );\n\n    const response = await innerFetch(\n      introspectionEndpoint,\n      {\n        method: 'POST',\n        body: body.toString(),\n        headers,\n      },\n      this.fetcher,\n      this.responseTimeout\n    );\n\n    if (response.status === 400 || response.status === 401) {\n      const { raw, json } = await readErrorResponse(response);\n\n      const fallbackError =\n        response.status === 401 ? 'invalid_client' : 'introspection_failed';\n\n      throw new MonoCloudOPError(\n        json.error ?? fallbackError,\n        json.error_description ?? 'Token introspection failed',\n        raw\n      );\n    }\n\n    if (response.status !== 200) {\n      const { raw } = await readErrorResponse(response);\n\n      throw new MonoCloudHttpError(\n        `Error while performing token introspection. Unexpected status code: ${response.status}`,\n        raw\n      );\n    }\n\n    const introspectionResponse = await deserializeJson<\n      AccessTokenClaims & { active?: boolean }\n    >(response);\n\n    if (!introspectionResponse.active) {\n      throw new MonoCloudTokenError(\n        'Token is not active. The introspection endpoint returned active=false',\n        'inactive_token'\n      );\n    }\n\n    const { active: _, ...claims } = introspectionResponse;\n\n    this.validateAccessTokenClaims(claims, options?.scopes, options?.groups);\n\n    await this.validateCertificateBinding(\n      claims,\n      options?.validateCertificateBinding,\n      options?.clientCertificate\n    );\n\n    return claims;\n  }\n\n  /**\n   * Validates a JWT access token by verifying the signature and claims.\n   *\n   * @param accessToken - The access token JWT string to validate.\n   * @param options - Validation options.\n   *\n   * @returns Validated access token claims.\n   *\n   * @throws {@link MonoCloudTokenError} - If JWT parsing, signature verification, or claim validation fails.\n   *\n   * @throws {@link MonoCloudHttpError} - Thrown if there is a network error during the request or\n   * unexpected status code during the request or a serialization error while processing the response.\n   *\n   * @throws {@link MonoCloudValidationError} - When the access token is empty or claims validation fails.\n   *\n   */\n  async validateJwtAccessToken(\n    accessToken: string,\n    options?: ValidateJwtAccessTokenOptions\n  ): Promise<AccessTokenClaims> {\n    if (typeof accessToken !== 'string' || accessToken.trim().length === 0) {\n      throw new MonoCloudValidationError(\n        'Access token must be a valid non-empty string'\n      );\n    }\n\n    const {\n      0: protectedHeader,\n      1: payload,\n      2: encodedSignature,\n      length,\n    } = accessToken.split('.');\n\n    if (length !== 3) {\n      throw new MonoCloudTokenError(\n        'JWT access token must have a header, payload and signature'\n      );\n    }\n\n    let header: JwsHeaderParameters;\n    try {\n      header = JSON.parse(decodeBase64Url(protectedHeader));\n    } catch {\n      throw new MonoCloudTokenError('Failed to parse JWT Header');\n    }\n\n    if (\n      header === null ||\n      typeof header !== 'object' ||\n      Array.isArray(header)\n    ) {\n      throw new MonoCloudTokenError('JWT Header must be a top level object');\n    }\n\n    if (header.crit !== undefined) {\n      throw new MonoCloudTokenError('Unexpected JWT \"crit\" header parameter');\n    }\n\n    const binary = decodeBase64Url(encodedSignature);\n\n    const signature = new Uint8Array(binary.length);\n\n    for (let i = 0; i < binary.length; i++) {\n      signature[i] = binary.charCodeAt(i);\n    }\n\n    const jwks = options?.jwks ?? (await this.getJwks());\n\n    const key = await getPublicSigKeyFromIssuerJwks(jwks.keys, header);\n\n    const input = `${protectedHeader}.${payload}`;\n\n    const verified = await crypto.subtle.verify(\n      keyToSubtle(key),\n      key,\n      signature,\n      stringToArrayBuffer(input) as BufferSource\n    );\n\n    if (!verified) {\n      throw new MonoCloudTokenError('JWT signature verification failed');\n    }\n\n    let claims: AccessTokenClaims;\n\n    try {\n      claims = JSON.parse(decodeBase64Url(payload));\n    } catch {\n      throw new MonoCloudTokenError('Failed to parse JWT Payload');\n    }\n\n    if (\n      claims === null ||\n      typeof claims !== 'object' ||\n      Array.isArray(claims)\n    ) {\n      throw new MonoCloudTokenError('JWT Payload must be a top level object');\n    }\n\n    this.validateAccessTokenClaims(claims, options?.scopes, options?.groups);\n\n    await this.validateCertificateBinding(\n      claims,\n      options?.validateCertificateBinding,\n      options?.clientCertificate\n    );\n\n    return claims;\n  }\n\n  /**\n   * Sets clock skew used for access token time-based claim validation.\n   *\n   * @param clockSkew - Number of seconds to adjust the current time to account for clock differences.\n   */\n  public setClockSkew(clockSkew: number): void {\n    this.clockSkew = clockSkew;\n  }\n\n  /**\n   * Sets clock tolerance used for access token time-based claim validation.\n   *\n   * @param clockTolerance - Additional time tolerance in seconds for time-based claim validation.\n   */\n  public setClockTolerance(clockTolerance: number): void {\n    this.clockTolerance = clockTolerance;\n  }\n\n  /**\n   * Validates access token claims against the expected issuer, audience,\n   * time-based claims, and any required scopes and groups.\n   *\n   * @param claims - The access token claims to validate.\n   * @param scopes - Scopes the token must contain.\n   * @param groups - Groups the token's subject must belong to.\n   *\n   * @throws {@link MonoCloudTokenError} - If any claim validation fails.\n   */\n  protected validateAccessTokenClaims(\n    claims: AccessTokenClaims,\n    scopes?: string[],\n    groups?: string[]\n  ): void {\n    const current = now() + this.clockSkew;\n\n    if (claims.iss !== this.tenantDomain) {\n      throw new MonoCloudTokenError('Invalid Issuer');\n    }\n\n    if (claims.sub && typeof claims.sub !== 'string') {\n      throw new MonoCloudTokenError('Invalid subject');\n    }\n\n    const audience = Array.isArray(claims.aud) ? claims.aud : [claims.aud];\n\n    if (!audience.includes(this.audience)) {\n      throw new MonoCloudTokenError('Invalid audience claim');\n    }\n\n    if (claims.exp !== undefined) {\n      if (typeof claims.exp !== 'number') {\n        throw new MonoCloudTokenError(\n          'Unexpected \"exp\" (expiration time) claim type'\n        );\n      }\n\n      if (claims.exp <= current - this.clockTolerance) {\n        throw new MonoCloudTokenError(\n          'Unexpected \"exp\" (expiration time) claim value, timestamp is <= now()'\n        );\n      }\n    }\n\n    if (claims.nbf !== undefined) {\n      if (typeof claims.nbf !== 'number') {\n        throw new MonoCloudTokenError(\n          'Unexpected \"nbf\" (not before) claim type'\n        );\n      }\n\n      if (claims.nbf > current + this.clockTolerance) {\n        throw new MonoCloudTokenError(\n          'Unexpected \"nbf\" (not before) claim value, timestamp is > now()'\n        );\n      }\n    }\n\n    if (scopes && scopes.length > 0) {\n      const tokenScopes = new Set(parseSpaceSeparated(claims.scope));\n\n      for (const requiredScope of scopes) {\n        if (!tokenScopes.has(requiredScope)) {\n          throw new MonoCloudTokenError(\n            'Token is missing required scopes',\n            'insufficient_scope'\n          );\n        }\n      }\n    }\n\n    if (groups) {\n      if (\n        !isUserInGroup(\n          claims,\n          groups,\n          this.groupOptions?.groupsClaim,\n          this.groupOptions?.matchAll\n        )\n      ) {\n        throw new MonoCloudTokenError(\n          'Token is missing required groups',\n          'insufficient_groups'\n        );\n      }\n    }\n  }\n\n  /**\n   * Validates that the access token is bound to the presented client\n   * certificate by comparing the `cnf` claim's `x5t#S256` thumbprint against\n   * the certificate's SHA-256 hash.\n   *\n   * @param accessTokenClaims - The access token claims containing the `cnf` claim.\n   * @param mode - Controls whether certificate binding is validated.\n   * @param certificate - The client certificate presented with the request.\n   *\n   * @throws {@link MonoCloudTokenError} - If the certificate is missing or malformed, the `cnf` claim is missing or invalid, or the hashes do not match.\n   */\n  protected async validateCertificateBinding(\n    accessTokenClaims: AccessTokenClaims,\n    mode?: CertificateBindingValidation,\n    certificate?: string\n  ): Promise<void> {\n    if (\n      mode !== 'required' &&\n      !(mode === 'when_present' && isCertificateBoundCnf(accessTokenClaims.cnf))\n    ) {\n      return;\n    }\n\n    if (typeof certificate !== 'string' || certificate.trim().length === 0) {\n      throw new MonoCloudTokenError('Client certificate is not present');\n    }\n\n    const pemMatch =\n      /-----BEGIN CERTIFICATE-----([\\s\\S]+?)-----END CERTIFICATE-----/.exec(\n        certificate\n      );\n    const encodedCertificate = (pemMatch?.[1] ?? certificate).replace(\n      /\\s+/g,\n      ''\n    );\n\n    let certificateBinary: string;\n\n    try {\n      certificateBinary = atob(encodedCertificate);\n    } catch {\n      throw new MonoCloudTokenError('Client certificate is malformed');\n    }\n\n    const certificateBytes = new Uint8Array(certificateBinary.length);\n\n    for (let i = 0; i < certificateBinary.length; i++) {\n      certificateBytes[i] = certificateBinary.charCodeAt(i);\n    }\n\n    const certificateDigest = await crypto.subtle.digest(\n      'SHA-256',\n      certificateBytes\n    );\n\n    const clientCertHash = arrayBufferToBase64(\n      new Uint8Array(certificateDigest)\n    );\n\n    let cnfClaimValue: unknown = accessTokenClaims.cnf;\n\n    if (cnfClaimValue === undefined || cnfClaimValue === null) {\n      throw new MonoCloudTokenError(\n        \"Access token does not contain a 'cnf' (confirmation) claim for certificate binding\"\n      );\n    }\n\n    if (typeof cnfClaimValue === 'string') {\n      try {\n        cnfClaimValue = JSON.parse(cnfClaimValue) as unknown;\n      } catch {\n        throw new MonoCloudTokenError(\n          \"Malformed 'cnf' claim for certificate binding\"\n        );\n      }\n    }\n\n    if (\n      cnfClaimValue === null ||\n      typeof cnfClaimValue !== 'object' ||\n      Array.isArray(cnfClaimValue)\n    ) {\n      throw new MonoCloudTokenError(\"The 'cnf' claim could not be parsed\");\n    }\n\n    const certHash = (cnfClaimValue as Record<string, unknown>)['x5t#S256'];\n\n    if (typeof certHash !== 'string' || certHash.length === 0) {\n      throw new MonoCloudTokenError(\n        \"The 'cnf' claim does not contain an 'x5t#S256' member specifying the certificate hash for binding\"\n      );\n    }\n\n    if (!timingSafeEqual(certHash, clientCertHash)) {\n      throw new MonoCloudTokenError(\n        'The certificate hash in the access token does not match the presented client certificate (certificate binding validation failed)'\n      );\n    }\n  }\n}\n"],"mappings":";;;;;;;;;;AASA,IAAa,yBAAb,cAA4C,MAAM;CAMhD,YAAY,SAAkB,KAA4B;EACxD,MAAM,OAAO;EACb,KAAK,MAAM;CACb;AACF;;;;;;;;ACXA,IAAa,mBAAb,cAAsC,uBAAuB;CAW3D,YACE,OACA,kBACA,KACA;EACA,MAAM,OAAO,GAAG;EAChB,KAAK,QAAQ;EACb,KAAK,mBAAmB;CAC1B;AACF;;;;;;;;;;ACnBA,IAAa,qBAAb,cAAwC,uBAAuB;;;;;;CAM7D,IAAI,SAA6B;EAC/B,OAAO,KAAK,KAAK;CACnB;;;;CAKA,IAAI,aAAiC;EACnC,OAAO,KAAK,KAAK;CACnB;AACF;;;;;;;;ACjBA,IAAa,sBAAb,cAAyC,uBAAuB;CAI9D,YACE,SACA,OAAgC,iBAChC,KACA;EACA,MAAM,SAAS,GAAG;EAClB,KAAK,OAAO;CACd;AACF;;;;;;;;ACbA,IAAa,2BAAb,cAA8C,uBAAuB,CAAC;;;ACCtE,MAAa,0BAA0B,WACrC,WAAW,qBACX,WAAW,iCACX,WAAW;AAEb,MAAM,eACJ,QACiE;CACjE,QAAQ,KAAR;EACE,KAAK;E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