{"version":3,"sources":["../src/index.ts","../src/auth-client.ts","../src/errors.ts","../src/utils.ts","../src/mfa/mfa-client.ts","../src/mfa/errors.ts","../src/mfa/utils.ts","../src/types.ts","../src/passkey/errors.ts","../src/passkey/utils.ts","../src/passkey/passkey-client.ts","../src/telemetry.ts","../src/lru-cache.ts","../src/cache-provider.ts"],"sourcesContent":["export { AuthClient } from './auth-client.js';\nexport * from './errors.js';\nexport * from './types.js';\nexport * from './mfa/index.js';\nexport * from './passkey/index.js';\n","import * as client from 'openid-client';\nimport { createRemoteJWKSet, importPKCS8, jwtVerify, customFetch, jwksCache, decodeJwt } from 'jose';\nimport type { JWKSCacheInput } from 'jose';\nimport {\n  BackchannelAuthenticationError,\n  BuildAuthorizationUrlError,\n  BuildLinkUserUrlError,\n  BuildUnlinkUserUrlError,\n  TokenExchangeError,\n  MissingClientAuthError,\n  NotSupportedError,\n  NotSupportedErrorCode,\n  OAuth2Error,\n  toOAuth2Error,\n  TokenByClientCredentialsError,\n  TokenByCodeError,\n  TokenByPasswordError,\n  TokenByRefreshTokenError,\n  TokenForConnectionError,\n  VerifyLogoutTokenError,\n} from './errors.js';\nimport { stripUndefinedProperties } from './utils.js';\nimport { MfaClient } from './mfa/mfa-client.js';\nimport { PasskeyClient, PASSKEY_GRANT_TYPE } from './passkey/passkey-client.js';\nimport { createTelemetryFetch, getTelemetryConfig } from './telemetry.js';\nimport {\n  AuthClientOptions,\n  BackchannelAuthenticationOptions,\n  BuildAuthorizationUrlOptions,\n  BuildAuthorizationUrlResult,\n  BuildLinkUserUrlOptions,\n  BuildLinkUserUrlResult,\n  BuildLogoutUrlOptions,\n  BuildUnlinkUserUrlOptions,\n  BuildUnlinkUserUrlResult,\n  ExchangeProfileOptions,\n  TokenVaultExchangeOptions,\n  TokenByClientCredentialsOptions,\n  TokenByCodeOptions,\n  TokenByPasswordOptions,\n  TokenByRefreshTokenOptions,\n  TokenForConnectionOptions,\n  TokenResponse,\n  ActClaim,\n  VerifyLogoutTokenOptions,\n  VerifyLogoutTokenResult,\n} from './types.js';\nimport { resolveCacheConfig, DiscoveryCacheFactory } from './cache-provider.js';\nimport type { DiscoveryCache } from './cache-provider.js';\n\nconst DEFAULT_SCOPES = 'openid profile email offline_access';\n\ntype DiscoveryCacheEntry = {\n  serverMetadata: client.ServerMetadata;\n};\n\n/**\n * Maximum number of values allowed per parameter key in extras.\n *\n * This limit prevents potential DoS attacks from maliciously large arrays and ensures\n * reasonable payload sizes. If you have a legitimate use case requiring more than 20\n * values for a single parameter, consider:\n * - Aggregating the data into a single structured value (e.g., JSON string)\n * - Splitting the request across multiple token exchanges\n * - Using a different parameter design that doesn't require arrays\n *\n * This limit is not currently configurable. If you need a higher limit, please open\n * an issue describing your use case.\n */\nconst MAX_ARRAY_VALUES_PER_KEY = 20;\n\n/**\n * OAuth parameter denylist - parameters that cannot be overridden via extras.\n *\n * These parameters are denied to prevent security issues and maintain API contract clarity:\n *\n * - grant_type: Core protocol parameter, modifying breaks OAuth flow integrity\n * - client_id, client_secret, client_assertion, client_assertion_type: Client authentication\n *   credentials must be managed through configuration, not request parameters\n * - subject_token, subject_token_type: Core token exchange parameters, overriding creates\n *   ambiguity about which token is being exchanged\n * - actor_token, actor_token_type: Actor token parameters for delegation exchanges, must use\n *   explicit typed parameters to ensure correct delegation semantics\n * - requested_token_type: Determines the type of token returned, must be explicit\n * - audience, aud, resource, resources, resource_indicator: Target API parameters must use\n *   explicit API parameters to prevent confusion about precedence and ensure correct routing\n * - scope: Overriding via extras bypasses the explicit scope parameter and creates ambiguity\n *   about which scope takes precedence, potentially granting unintended permissions\n * - connection: Determines token source for Token Vault, must be explicit\n * - login_hint: Affects user identity resolution, must be explicit\n * - organization: Affects tenant context, must be explicit\n * - assertion: SAML assertion parameter, must be managed separately\n *\n * These restrictions ensure that security-critical and routing parameters are always\n * set through explicit, typed API parameters rather than untyped extras.\n */\nconst PARAM_DENYLIST = Object.freeze(\n  new Set([\n    'grant_type',\n    'client_id',\n    'client_secret',\n    'client_assertion',\n    'client_assertion_type',\n    'subject_token',\n    'subject_token_type',\n    'requested_token_type',\n    'actor_token',\n    'actor_token_type',\n    'audience',\n    'aud',\n    'resource',\n    'resources',\n    'resource_indicator',\n    'scope',\n    'connection',\n    'login_hint',\n    'organization',\n    'assertion',\n  ])\n);\n\n/**\n * Validates subject token input to fail fast with clear error messages.\n * Detects common footguns like whitespace, Bearer prefix, and empty values.\n */\nfunction validateSubjectToken(token: string): void {\n  if (token == null) {\n    throw new TokenExchangeError('subject_token is required');\n  }\n  if (typeof token !== 'string') {\n    throw new TokenExchangeError('subject_token must be a string');\n  }\n  // Fail fast on blank or whitespace-only\n  if (token.trim().length === 0) {\n    throw new TokenExchangeError('subject_token cannot be blank or whitespace');\n  }\n  // Be explicit about surrounding spaces\n  if (token !== token.trim()) {\n    throw new TokenExchangeError('subject_token must not include leading or trailing whitespace');\n  }\n  // Very common copy paste mistake (case-insensitive check)\n  if (/^bearer\\s+/i.test(token)) {\n    throw new TokenExchangeError(\"subject_token must not include the 'Bearer ' prefix\");\n  }\n}\n\n/**\n * Appends extra parameters to URLSearchParams while enforcing security constraints.\n */\nfunction appendExtraParams(params: URLSearchParams, extra?: Record<string, string | string[]>): void {\n  if (!extra) return;\n\n  for (const [parameterKey, parameterValue] of Object.entries(extra)) {\n    if (PARAM_DENYLIST.has(parameterKey)) continue;\n\n    if (Array.isArray(parameterValue)) {\n      if (parameterValue.length > MAX_ARRAY_VALUES_PER_KEY) {\n        throw new TokenExchangeError(\n          `Parameter '${parameterKey}' exceeds maximum array size of ${MAX_ARRAY_VALUES_PER_KEY}`\n        );\n      }\n      parameterValue.forEach((arrayItem) => {\n        params.append(parameterKey, arrayItem);\n      });\n    } else {\n      params.append(parameterKey, parameterValue);\n    }\n  }\n}\n\n/**\n * A constant representing the grant type for federated connection access token exchange.\n *\n * This grant type is used in OAuth token exchange scenarios where a federated connection\n * access token is required. It is specific to Auth0's implementation and follows the\n * \"urn:auth0:params:oauth:grant-type:token-exchange:federated-connection-access-token\" format.\n */\nconst GRANT_TYPE_FEDERATED_CONNECTION_ACCESS_TOKEN =\n  'urn:auth0:params:oauth:grant-type:token-exchange:federated-connection-access-token' as const;\n\n/**\n * RFC 8693 grant type for OAuth 2.0 Token Exchange.\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc8693 RFC 8693: OAuth 2.0 Token Exchange}\n */\nconst TOKEN_EXCHANGE_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange' as const;\n\n/**\n * Constant representing the subject type for a refresh token.\n * This is used in OAuth 2.0 token exchange to specify that the token being exchanged is a refresh token.\n *\n * @see {@link https://tools.ietf.org/html/rfc8693#section-3.1 RFC 8693 Section 3.1}\n */\nconst SUBJECT_TYPE_REFRESH_TOKEN = 'urn:ietf:params:oauth:token-type:refresh_token';\n\n/**\n * Constant representing the subject type for an access token.\n * This is used in OAuth 2.0 token exchange to specify that the token being exchanged is an access token.\n *\n * @see {@link https://tools.ietf.org/html/rfc8693#section-3.1 RFC 8693 Section 3.1}\n */\nconst SUBJECT_TYPE_ACCESS_TOKEN = 'urn:ietf:params:oauth:token-type:access_token';\n\n/**\n * A constant representing the token type for federated connection access tokens.\n * This is used to specify the type of token being requested from Auth0.\n *\n * @constant\n * @type {string}\n */\nconst REQUESTED_TOKEN_TYPE_FEDERATED_CONNECTION_ACCESS_TOKEN =\n  'http://auth0.com/oauth/token-type/federated-connection-access-token';\n\n/**\n * Wraps a fetch implementation so that the passkey (WebAuthn) token request is\n * sent as `application/json` with `authn_response` as a nested object.\n *\n * `openid-client`/`oauth4webapi` always serialize token requests as\n * `application/x-www-form-urlencoded`, which would stringify `authn_response`\n * and cause Auth0 to reject it (`\"authn_response\" must be of type object`).\n * This shim runs after client authentication has been applied to the body, so\n * any injected `client_secret`/`client_assertion` fields are preserved.\n *\n * For any other grant type — or if the body is not the expected\n * `URLSearchParams` — the request is passed through unchanged.\n */\nfunction createPasskeyFetch(customFetch: typeof fetch, grantType: string): typeof fetch {\n  return (input, init) => {\n    const body = init?.body;\n\n    if (grantType !== PASSKEY_GRANT_TYPE || !(body instanceof URLSearchParams)) {\n      return customFetch(input, init);\n    }\n\n    const jsonBody: Record<string, unknown> = {};\n    for (const [key, value] of body) {\n      // `authn_response` is serialized by PasskeyClient (JSON.stringify) to fit\n      // through URLSearchParams; restore it to a nested object for the JSON body.\n      jsonBody[key] = key === 'authn_response' ? JSON.parse(value) : value;\n    }\n\n    const headers = new Headers(init?.headers);\n    headers.set('Content-Type', 'application/json');\n\n    return customFetch(input, {\n      ...init,\n      headers,\n      body: JSON.stringify(jsonBody),\n    });\n  };\n}\n\n/**\n * Auth0 authentication client for handling OAuth 2.0 and OIDC flows.\n *\n * Provides methods for authorization, token exchange, token refresh, and verification\n * of tokens issued by Auth0. Supports multiple authentication methods including\n * client_secret_post, private_key_jwt, and mTLS.\n */\nexport class AuthClient {\n  #configuration: client.Configuration | undefined;\n  #serverMetadata: client.ServerMetadata | undefined;\n  #clientAuthPromise: Promise<client.ClientAuth> | undefined;\n  readonly #options: AuthClientOptions;\n  readonly #customFetch: typeof fetch;\n  #jwks?: ReturnType<typeof createRemoteJWKSet>;\n  readonly #discoveryCache: DiscoveryCache<string, DiscoveryCacheEntry>;\n  readonly #inFlightDiscovery: Map<string, Promise<DiscoveryCacheEntry>>;\n  readonly #jwksCache: JWKSCacheInput;\n  public mfa: MfaClient;\n  public passkey: PasskeyClient;\n\n  constructor(options: AuthClientOptions) {\n    this.#options = options;\n\n    // When mTLS is being used, a custom fetch implementation is required.\n    if (options.useMtls && !options.customFetch) {\n      throw new NotSupportedError(\n        NotSupportedErrorCode.MTLS_WITHOUT_CUSTOMFETCH_NOT_SUPPORT,\n        'Using mTLS without a custom fetch implementation is not supported'\n      );\n    }\n\n    this.#customFetch = createTelemetryFetch(\n      options.customFetch ?? ((...args) => fetch(...args)),\n      getTelemetryConfig(options.telemetry)\n    );\n\n    // Use factory to create appropriate cache implementations\n    const cacheConfig = resolveCacheConfig(options.discoveryCache);\n    this.#discoveryCache = DiscoveryCacheFactory.createDiscoveryCache<string, DiscoveryCacheEntry>(cacheConfig);\n    this.#inFlightDiscovery = new Map<string, Promise<DiscoveryCacheEntry>>();\n    this.#jwksCache = DiscoveryCacheFactory.createJwksCache();\n\n    this.mfa = new MfaClient({\n      domain: this.#options.domain,\n      clientId: this.#options.clientId,\n      clientSecret: this.#options.clientSecret,\n      customFetch: this.#customFetch,\n      getConfiguration: async () => (await this.#discover()).configuration,\n    });\n\n    this.passkey = new PasskeyClient({\n      domain: this.#options.domain,\n      clientId: this.#options.clientId,\n      customFetch: this.#customFetch,\n      grantRequest: async (grantType, params) => {\n        // The passkey token exchange authenticates the client like any other\n        // grant; `#discover()` throws `MissingClientAuthError` for public\n        // clients that have no credentials configured.\n        const { serverMetadata } = await this.#discover();\n\n        // Build a dedicated configuration so the passkey JSON fetch shim is not\n        // applied to the shared configuration used by other grants. The passkey\n        // token endpoint requires a JSON body with `authn_response` as a nested\n        // object; the shim rewrites the form-encoded request accordingly.\n        const configuration = await this.#createConfiguration(serverMetadata);\n        configuration[client.customFetch] = createPasskeyFetch(this.#customFetch, grantType);\n\n        const tokenEndpointResponse = await client.genericGrantRequest(configuration, grantType, params);\n        return TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);\n      },\n    });\n  }\n\n  #getDiscoveryCacheKey(): string {\n    const domain = this.#options.domain.toLowerCase();\n    return `${domain}|mtls:${this.#options.useMtls ? '1' : '0'}`;\n  }\n\n  async #createConfiguration(serverMetadata: client.ServerMetadata): Promise<client.Configuration> {\n    const clientAuth = await this.#getClientAuth();\n    const configuration = new client.Configuration(\n      serverMetadata,\n      this.#options.clientId,\n      this.#options.clientSecret,\n      clientAuth\n    );\n    configuration[client.customFetch] = this.#customFetch;\n    return configuration;\n  }\n\n  /**\n   * Initializes the SDK by performing Metadata Discovery.\n   *\n   * Discovers and caches the OAuth 2.0 Authorization Server metadata from the\n   * Auth0 tenant's well-known endpoint. This metadata is required for subsequent\n   * operations and is cached for the lifetime of the AuthClient instance.\n   *\n   * @private\n   * @returns Promise resolving to the cached configuration and server metadata\n   */\n  async #discover() {\n    if (this.#configuration && this.#serverMetadata) {\n      return {\n        configuration: this.#configuration,\n        serverMetadata: this.#serverMetadata,\n      };\n    }\n\n    const cacheKey = this.#getDiscoveryCacheKey();\n    const cached = this.#discoveryCache.get(cacheKey);\n\n    if (cached) {\n      this.#serverMetadata = cached.serverMetadata;\n      this.#configuration = await this.#createConfiguration(cached.serverMetadata);\n      return {\n        configuration: this.#configuration,\n        serverMetadata: this.#serverMetadata,\n      };\n    }\n\n    const inFlight = this.#inFlightDiscovery.get(cacheKey);\n    if (inFlight) {\n      const entry = await inFlight;\n      this.#serverMetadata = entry.serverMetadata;\n      this.#configuration = await this.#createConfiguration(entry.serverMetadata);\n      return {\n        configuration: this.#configuration,\n        serverMetadata: this.#serverMetadata,\n      };\n    }\n\n    const discoveryPromise = (async () => {\n      const clientAuth = await this.#getClientAuth();\n\n      const configuration = await client.discovery(\n        new URL(`https://${this.#options.domain}`),\n        this.#options.clientId,\n        { use_mtls_endpoint_aliases: this.#options.useMtls },\n        clientAuth,\n        {\n          [client.customFetch]: this.#customFetch,\n        }\n      );\n\n      const serverMetadata = configuration.serverMetadata();\n      this.#discoveryCache.set(cacheKey, { serverMetadata });\n      return { configuration, serverMetadata };\n    })();\n\n    const inFlightEntry = discoveryPromise.then(({ serverMetadata }) => ({\n      serverMetadata,\n    }));\n    // Prevent unhandled rejection warnings when discovery fails.\n    void inFlightEntry.catch(() => undefined);\n    this.#inFlightDiscovery.set(cacheKey, inFlightEntry);\n\n    try {\n      const { configuration, serverMetadata } = await discoveryPromise;\n      this.#configuration = configuration;\n      this.#serverMetadata = serverMetadata;\n      this.#configuration[client.customFetch] = this.#customFetch;\n    } finally {\n      this.#inFlightDiscovery.delete(cacheKey);\n    }\n\n    return {\n      configuration: this.#configuration,\n      serverMetadata: this.#serverMetadata,\n    };\n  }\n\n  /**\n   * Returns the discovered server metadata for the configured domain.\n   */\n  public async getServerMetadata(): Promise<client.ServerMetadata> {\n    const { serverMetadata } = await this.#discover();\n    return serverMetadata;\n  }\n\n  /**\n   * Builds the URL to redirect the user-agent to to request authorization at Auth0.\n   * @param options Options used to configure the authorization URL.\n   *\n   * @throws {BuildAuthorizationUrlError} If there was an issue when building the Authorization URL.\n   *\n   * @returns A promise resolving to an object, containing the authorizationUrl and codeVerifier.\n   */\n  async buildAuthorizationUrl(options?: BuildAuthorizationUrlOptions): Promise<BuildAuthorizationUrlResult> {\n    const { serverMetadata } = await this.#discover();\n\n    if (options?.pushedAuthorizationRequests && !serverMetadata.pushed_authorization_request_endpoint) {\n      throw new NotSupportedError(\n        NotSupportedErrorCode.PAR_NOT_SUPPORTED,\n        'The Auth0 tenant does not have pushed authorization requests enabled. Learn how to enable it here: https://auth0.com/docs/get-started/applications/configure-par'\n      );\n    }\n\n    try {\n      return await this.#buildAuthorizationUrl(options);\n    } catch (e) {\n      throw new BuildAuthorizationUrlError(e as OAuth2Error);\n    }\n  }\n\n  /**\n   * Builds the URL to redirect the user-agent to to link a user account at Auth0.\n   * @param options Options used to configure the link user URL.\n   *\n   * @throws {BuildLinkUserUrlError} If there was an issue when building the Link User URL.\n   *\n   * @returns A promise resolving to an object, containing the linkUserUrl and codeVerifier.\n   */\n  public async buildLinkUserUrl(options: BuildLinkUserUrlOptions): Promise<BuildLinkUserUrlResult> {\n    try {\n      const result = await this.#buildAuthorizationUrl({\n        authorizationParams: {\n          ...options.authorizationParams,\n          requested_connection: options.connection,\n          requested_connection_scope: options.connectionScope,\n          scope: 'openid link_account offline_access',\n          id_token_hint: options.idToken,\n        },\n      });\n\n      return {\n        linkUserUrl: result.authorizationUrl,\n        codeVerifier: result.codeVerifier,\n      };\n    } catch (e) {\n      throw new BuildLinkUserUrlError(e as OAuth2Error);\n    }\n  }\n\n  /**\n   * Builds the URL to redirect the user-agent to to unlink a user account at Auth0.\n   * @param options Options used to configure the unlink user URL.\n   *\n   * @throws {BuildUnlinkUserUrlError} If there was an issue when building the Unlink User URL.\n   *\n   * @returns A promise resolving to an object, containing the unlinkUserUrl and codeVerifier.\n   */\n  public async buildUnlinkUserUrl(options: BuildUnlinkUserUrlOptions): Promise<BuildUnlinkUserUrlResult> {\n    try {\n      const result = await this.#buildAuthorizationUrl({\n        authorizationParams: {\n          ...options.authorizationParams,\n          requested_connection: options.connection,\n          scope: 'openid unlink_account',\n          id_token_hint: options.idToken,\n        },\n      });\n\n      return {\n        unlinkUserUrl: result.authorizationUrl,\n        codeVerifier: result.codeVerifier,\n      };\n    } catch (e) {\n      throw new BuildUnlinkUserUrlError(e as OAuth2Error);\n    }\n  }\n\n  /**\n   * Authenticates using Client-Initiated Backchannel Authentication.\n   *\n   * This method will initialize the backchannel authentication process with Auth0, and poll the token endpoint until the authentication is complete.\n   *\n   * Using Client-Initiated Backchannel Authentication requires the feature to be enabled in the Auth0 dashboard.\n   * @see https://auth0.com/docs/get-started/authentication-and-authorization-flow/client-initiated-backchannel-authentication-flow\n   * @param options Options used to configure the backchannel authentication process.\n   *\n   * @throws {BackchannelAuthenticationError} If there was an issue when doing backchannel authentication.\n   *\n   * @returns A Promise, resolving to the TokenResponse as returned from Auth0.\n   */\n  async backchannelAuthentication(options: BackchannelAuthenticationOptions): Promise<TokenResponse> {\n    const { configuration, serverMetadata } = await this.#discover();\n\n    const additionalParams = stripUndefinedProperties({\n      ...this.#options.authorizationParams,\n      ...options?.authorizationParams,\n    });\n\n    const params = new URLSearchParams({\n      scope: DEFAULT_SCOPES,\n      ...additionalParams,\n      client_id: this.#options.clientId,\n      binding_message: options.bindingMessage,\n      login_hint: JSON.stringify({\n        format: 'iss_sub',\n        iss: serverMetadata.issuer,\n        sub: options.loginHint.sub,\n      }),\n    });\n\n    if (options.requestedExpiry) {\n      params.append('requested_expiry', options.requestedExpiry.toString());\n    }\n\n    if (options.authorizationDetails) {\n      params.append('authorization_details', JSON.stringify(options.authorizationDetails));\n    }\n\n    try {\n      const backchannelAuthenticationResponse = await client.initiateBackchannelAuthentication(configuration, params);\n\n      const tokenEndpointResponse = await client.pollBackchannelAuthenticationGrant(\n        configuration,\n        backchannelAuthenticationResponse\n      );\n\n      return TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);\n    } catch (e) {\n      throw new BackchannelAuthenticationError(e as OAuth2Error);\n    }\n  }\n\n  /**\n   * Initiates Client-Initiated Backchannel Authentication flow by calling the `/bc-authorize` endpoint.\n   * This method only initiates the authentication request and returns the `auth_req_id` to be used in subsequent calls to `backchannelAuthenticationGrant`.\n   *\n   * Typically, you would call this method to start the authentication process, then use the returned `auth_req_id` to poll for the token using `backchannelAuthenticationGrant`.\n   *\n   * @param options Options used to configure the backchannel authentication initiation.\n   *\n   * @throws {BackchannelAuthenticationError} If there was an issue when initiating backchannel authentication.\n   *\n   * @returns An object containing `authReqId`, `expiresIn`, and `interval` for polling.\n   */\n  async initiateBackchannelAuthentication(options: BackchannelAuthenticationOptions) {\n    const { configuration, serverMetadata } = await this.#discover();\n\n    const additionalParams = stripUndefinedProperties({\n      ...this.#options.authorizationParams,\n      ...options?.authorizationParams,\n    });\n\n    const params = new URLSearchParams({\n      scope: DEFAULT_SCOPES,\n      ...additionalParams,\n      client_id: this.#options.clientId,\n      binding_message: options.bindingMessage,\n      login_hint: JSON.stringify({\n        format: 'iss_sub',\n        iss: serverMetadata.issuer,\n        sub: options.loginHint.sub,\n      }),\n    });\n\n    if (options.requestedExpiry) {\n      params.append('requested_expiry', options.requestedExpiry.toString());\n    }\n\n    if (options.authorizationDetails) {\n      params.append('authorization_details', JSON.stringify(options.authorizationDetails));\n    }\n\n    try {\n      const backchannelAuthenticationResponse = await client.initiateBackchannelAuthentication(configuration, params);\n\n      return {\n        authReqId: backchannelAuthenticationResponse.auth_req_id,\n        expiresIn: backchannelAuthenticationResponse.expires_in,\n        interval: backchannelAuthenticationResponse.interval,\n      };\n    } catch (e) {\n      throw new BackchannelAuthenticationError(e as OAuth2Error);\n    }\n  }\n\n  /**\n   * Exchanges the `auth_req_id` obtained from `initiateBackchannelAuthentication` for tokens.\n   *\n   * @param authReqId The `auth_req_id` obtained from `initiateBackchannelAuthentication`.\n   *\n   * @throws {BackchannelAuthenticationError} If there was an issue when exchanging the `auth_req_id` for tokens.\n   *\n   * @returns A Promise, resolving to the TokenResponse as returned from Auth0.\n   */\n  async backchannelAuthenticationGrant({ authReqId }: { authReqId: string }) {\n    const { configuration } = await this.#discover();\n    const params = new URLSearchParams({\n      auth_req_id: authReqId,\n    });\n\n    try {\n      const tokenEndpointResponse = await client.genericGrantRequest(\n        configuration,\n        'urn:openid:params:grant-type:ciba',\n        params\n      );\n\n      return TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);\n    } catch (e) {\n      throw new BackchannelAuthenticationError(e as OAuth2Error);\n    }\n  }\n\n  /**\n   * Retrieves a token for a connection using Token Vault.\n   *\n   * @deprecated Since v1.2.0. Use {@link exchangeToken} with a Token Vault payload:\n   *   `exchangeToken({ connection, subjectToken, subjectTokenType, loginHint?, scope?, extra? })`.\n   * This method remains for backward compatibility and is planned for removal in v2.0.\n   *\n   * This is a convenience wrapper around exchangeToken() for Token Vault scenarios,\n   * providing a simpler API for the common use case of exchanging Auth0 tokens for\n   * federated access tokens.\n   *\n   * Either a refresh token or access token must be provided, but not both. The method\n   * automatically determines the correct subject_token_type based on which token is provided.\n   *\n   * @param options Options for retrieving an access token for a connection.\n   *\n   * @throws {TokenForConnectionError} If there was an issue requesting the access token,\n   *                                    or if both/neither token types are provided.\n   *\n   * @returns The access token for the connection\n   *\n   * @see {@link exchangeToken} for the unified token exchange method with more options\n   *\n   * @example Using an access token (deprecated, use exchangeToken instead)\n   * ```typescript\n   * const response = await authClient.getTokenForConnection({\n   *   connection: 'google-oauth2',\n   *   accessToken: auth0AccessToken,\n   *   loginHint: 'user@example.com'\n   * });\n   * ```\n   *\n   * @example Using a refresh token (deprecated, use exchangeToken instead)\n   * ```typescript\n   * const response = await authClient.getTokenForConnection({\n   *   connection: 'salesforce',\n   *   refreshToken: auth0RefreshToken\n   * });\n   * ```\n   */\n  public async getTokenForConnection(options: TokenForConnectionOptions): Promise<TokenResponse> {\n    if (options.refreshToken && options.accessToken) {\n      throw new TokenForConnectionError('Either a refresh or access token should be specified, but not both.');\n    }\n\n    const subjectTokenValue = options.accessToken ?? options.refreshToken;\n    if (!subjectTokenValue) {\n      throw new TokenForConnectionError('Either a refresh or access token must be specified.');\n    }\n\n    try {\n      return await this.exchangeToken({\n        connection: options.connection,\n        subjectToken: subjectTokenValue,\n        subjectTokenType: options.accessToken ? SUBJECT_TYPE_ACCESS_TOKEN : SUBJECT_TYPE_REFRESH_TOKEN,\n        loginHint: options.loginHint,\n      } as TokenVaultExchangeOptions);\n    } catch (e) {\n      // Wrap TokenExchangeError in TokenForConnectionError for backward compatibility\n      if (e instanceof TokenExchangeError) {\n        throw new TokenForConnectionError(e.message, e.cause);\n      }\n      throw e;\n    }\n  }\n\n  /**\n   * Internal implementation for Access Token Exchange with Token Vault.\n   *\n   * Exchanges an Auth0 token (access token or refresh token) for an external provider's access token\n   * from a third-party provider configured in Token Vault. The external provider's refresh token\n   * is securely stored in Auth0 and never exposed to the client.\n   *\n   * This method constructs the appropriate request for Auth0's proprietary Token Vault\n   * grant type and handles the exchange with proper validation and error handling.\n   *\n   * @private\n   * @param options Access Token Exchange with Token Vault configuration including connection and optional hints\n   * @returns Promise resolving to TokenResponse containing the external provider's access token\n   * @throws {TokenExchangeError} When validation fails, audience/resource are provided,\n   *                               or the exchange operation fails\n   */\n  async #exchangeTokenVaultToken(options: TokenVaultExchangeOptions): Promise<TokenResponse> {\n    const { configuration } = await this.#discover();\n\n    if ('audience' in options || 'resource' in options) {\n      throw new TokenExchangeError('audience and resource parameters are not supported for Token Vault exchanges');\n    }\n\n    validateSubjectToken(options.subjectToken);\n\n    const tokenRequestParams = new URLSearchParams({\n      connection: options.connection,\n      subject_token: options.subjectToken,\n      subject_token_type: options.subjectTokenType ?? SUBJECT_TYPE_ACCESS_TOKEN,\n      requested_token_type: options.requestedTokenType ?? REQUESTED_TOKEN_TYPE_FEDERATED_CONNECTION_ACCESS_TOKEN,\n    });\n\n    if (options.loginHint) {\n      tokenRequestParams.append('login_hint', options.loginHint);\n    }\n    if (options.scope) {\n      tokenRequestParams.append('scope', options.scope);\n    }\n\n    appendExtraParams(tokenRequestParams, options.extra);\n\n    try {\n      const tokenEndpointResponse = await client.genericGrantRequest(\n        configuration,\n        GRANT_TYPE_FEDERATED_CONNECTION_ACCESS_TOKEN,\n        tokenRequestParams\n      );\n\n      return TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);\n    } catch (e) {\n      throw new TokenExchangeError(\n        `Failed to exchange token for connection '${options.connection}'.`,\n        toOAuth2Error(e)\n      );\n    }\n  }\n\n  /**\n   * Internal implementation for Token Exchange via Token Exchange Profile (RFC 8693).\n   *\n   * Exchanges a custom token for Auth0 tokens targeting a specific API audience,\n   * preserving user identity. This enables first-party on-behalf-of flows where\n   * a custom token (e.g., from an MCP server, legacy system, or partner service)\n   * is exchanged for Auth0 tokens.\n   *\n   * Requires a Token Exchange Profile configured in Auth0 that defines the\n   * subject_token_type, validation logic, and user mapping.\n   *\n   * @private\n   * @param options Token Exchange Profile configuration including token type and target API\n   * @returns Promise resolving to TokenResponse containing Auth0 tokens\n   * @throws {TokenExchangeError} When validation fails or the exchange operation fails\n   */\n  async #exchangeProfileToken(options: ExchangeProfileOptions): Promise<TokenResponse> {\n    const { configuration } = await this.#discover();\n\n    validateSubjectToken(options.subjectToken);\n\n    if (options.actorToken !== undefined && options.actorTokenType === undefined) {\n      throw new TokenExchangeError('actorTokenType is required when actorToken is provided');\n    }\n\n    const tokenRequestParams = new URLSearchParams({\n      subject_token_type: options.subjectTokenType,\n      subject_token: options.subjectToken,\n    });\n\n    if (options.audience) {\n      tokenRequestParams.append('audience', options.audience);\n    }\n    if (options.scope) {\n      tokenRequestParams.append('scope', options.scope);\n    }\n    if (options.requestedTokenType) {\n      tokenRequestParams.append('requested_token_type', options.requestedTokenType);\n    }\n    if (options.organization) {\n      tokenRequestParams.append('organization', options.organization);\n    }\n    if (options.actorToken) {\n      tokenRequestParams.append('actor_token', options.actorToken);\n    }\n    if (options.actorTokenType) {\n      tokenRequestParams.append('actor_token_type', options.actorTokenType);\n    }\n\n    appendExtraParams(tokenRequestParams, options.extra);\n\n    try {\n      const tokenEndpointResponse = await client.genericGrantRequest(\n        configuration,\n        TOKEN_EXCHANGE_GRANT_TYPE,\n        tokenRequestParams\n      );\n\n      const tokenResponse = TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);\n      if (options.actorToken) {\n        if (tokenResponse.claims?.act) {\n          tokenResponse.act = tokenResponse.claims.act as ActClaim;\n        } else {\n          try {\n            tokenResponse.act = decodeJwt(tokenEndpointResponse.access_token).act as ActClaim | undefined;\n          } catch {\n            // opaque access token — act claim not available\n          }\n        }\n      }\n      return tokenResponse;\n    } catch (e) {\n      throw new TokenExchangeError(\n        `Failed to exchange token of type '${options.subjectTokenType}'${options.audience ? ` for audience '${options.audience}'` : ''}.`,\n        toOAuth2Error(e)\n      );\n    }\n  }\n\n  /**\n   * @overload\n   * Exchanges a custom token for Auth0 tokens using RFC 8693 Token Exchange via Token Exchange Profile.\n   *\n   * This overload is used when you DON'T provide a `connection` parameter.\n   * It enables exchanging custom tokens (from MCP servers, legacy systems, or partner\n   * services) for Auth0 tokens targeting a specific API audience. Requires a Token\n   * Exchange Profile configured in Auth0.\n   *\n   * @param options Token Exchange Profile configuration (without `connection` parameter)\n   * @returns Promise resolving to TokenResponse with Auth0 tokens\n   * @throws {TokenExchangeError} When exchange fails or validation errors occur\n   * @throws {MissingClientAuthError} When client authentication is not configured\n   *\n   * @example\n   * ```typescript\n   * // Exchange custom token (organization is optional)\n   * const response = await authClient.exchangeToken({\n   *   subjectTokenType: 'urn:acme:mcp-token',\n   *   subjectToken: mcpServerToken,\n   *   audience: 'https://api.example.com',\n   *   organization: 'org_abc123', // Optional - Organization ID or name\n   *   scope: 'openid profile read:data'\n   * });\n   * // The resulting access token will include the organization ID in its payload\n   * ```\n   */\n  public exchangeToken(options: ExchangeProfileOptions): Promise<TokenResponse>;\n\n  /**\n   * @overload\n   * Exchanges an Auth0 token for an external provider's access token using Token Vault.\n   *\n   * This overload is used when you DO provide a `connection` parameter.\n   * It exchanges Auth0 tokens (access or refresh) for external provider's access tokens\n   * (Google, Facebook, etc.). The external provider's refresh token is securely stored in\n   * Auth0's Token Vault.\n   *\n   * @param options Token Vault exchange configuration (with `connection` parameter)\n   * @returns Promise resolving to TokenResponse with external provider's access token\n   * @throws {TokenExchangeError} When exchange fails or validation errors occur\n   * @throws {MissingClientAuthError} When client authentication is not configured\n   *\n   * @example\n   * ```typescript\n   * const response = await authClient.exchangeToken({\n   *   connection: 'google-oauth2',\n   *   subjectToken: auth0AccessToken,\n   *   loginHint: 'user@example.com'\n   * });\n   * ```\n   */\n  public exchangeToken(options: TokenVaultExchangeOptions): Promise<TokenResponse>;\n\n  /**\n   * Exchanges a token using either Token Exchange via Token Exchange Profile (RFC 8693) or Access Token Exchange with Token Vault.\n   *\n   * **Method routing is determined by the presence of the `connection` parameter:**\n   * - **Without `connection`**: Token Exchange via Token Exchange Profile (RFC 8693)\n   * - **With `connection`**: Access Token Exchange with Token Vault\n   *\n   * Both flows require a confidential client (client credentials must be configured).\n   *\n   * @see {@link ExchangeProfileOptions} for Token Exchange Profile parameters\n   * @see {@link TokenVaultExchangeOptions} for Token Vault parameters\n   * @see {@link https://auth0.com/docs/authenticate/custom-token-exchange Custom Token Exchange Docs}\n   * @see {@link https://auth0.com/docs/secure/tokens/token-vault Token Vault Docs}\n   *\n   * @example Token Exchange with validation context\n   * ```typescript\n   * const response = await authClient.exchangeToken({\n   *   subjectTokenType: 'urn:acme:legacy-token',\n   *   subjectToken: legacySystemToken,\n   *   audience: 'https://api.acme.com',\n   *   scope: 'openid offline_access',\n   *   extra: {\n   *     device_id: 'device-12345',\n   *     session_id: 'sess-abc',\n   *     migration_context: 'legacy-system-v1'\n   *   }\n   * });\n   * ```\n   */\n  public async exchangeToken(options: ExchangeProfileOptions | TokenVaultExchangeOptions): Promise<TokenResponse> {\n    return 'connection' in options ? this.#exchangeTokenVaultToken(options) : this.#exchangeProfileToken(options);\n  }\n\n  /**\n   * Retrieves a token by exchanging an authorization code.\n   * @param url The URL containing the authorization code.\n   * @param options Options for exchanging the authorization code, containing the expected code verifier.\n   *\n   * @throws {TokenByCodeError} If there was an issue requesting the access token.\n   *\n   * @returns A Promise, resolving to the TokenResponse as returned from Auth0.\n   */\n  public async getTokenByCode(url: URL, options: TokenByCodeOptions): Promise<TokenResponse> {\n    const { configuration } = await this.#discover();\n    try {\n      const tokenEndpointResponse = await client.authorizationCodeGrant(configuration, url, {\n        pkceCodeVerifier: options.codeVerifier,\n      });\n\n      return TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);\n    } catch (e) {\n      throw new TokenByCodeError('There was an error while trying to request a token.', toOAuth2Error(e));\n    }\n  }\n\n  /**\n   * Retrieves a token by exchanging a refresh token.\n   * @param options Options for exchanging the refresh token.\n   *\n   * @throws {TokenByRefreshTokenError} If there was an issue requesting the access token.\n   *\n   * @returns A Promise, resolving to the TokenResponse as returned from Auth0.\n   */\n  public async getTokenByRefreshToken(options: TokenByRefreshTokenOptions) {\n    const { configuration } = await this.#discover();\n\n    const additionalParameters = new URLSearchParams();\n\n    if (options.audience) {\n      additionalParameters.append('audience', options.audience);\n    }\n\n    if (options.scope) {\n      additionalParameters.append('scope', options.scope);\n    }\n\n    try {\n      const tokenEndpointResponse = await client.refreshTokenGrant(\n        configuration,\n        options.refreshToken,\n        additionalParameters\n      );\n\n      return TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);\n    } catch (e) {\n      throw new TokenByRefreshTokenError(\n        'The access token has expired and there was an error while trying to refresh it.',\n        toOAuth2Error(e)\n      );\n    }\n  }\n\n  /**\n   * Retrieves a token using Resource Owner Password Grant.\n   * @param options Options for authenticating with username and password.\n   *\n   * @throws {TokenByPasswordError} If there was an issue requesting the access token.\n   *\n   * @returns A Promise, resolving to the TokenResponse as returned from Auth0.\n   */\n  public async getTokenByPassword(\n    options: TokenByPasswordOptions\n  ): Promise<TokenResponse> {\n    const { configuration } = await this.#discover();\n\n    const params = new URLSearchParams({\n      username: options.username,\n      password: options.password,\n    });\n\n    if (options.audience) {\n      params.append('audience', options.audience);\n    }\n\n    if (options.scope) {\n      params.append('scope', options.scope);\n    }\n\n    if (options.realm) {\n      params.append('realm', options.realm);\n    }\n\n    // When auth0ForwardedFor is needed, create a separate configuration with a\n    // wrapped fetch so we never mutate the shared cached configuration.\n    let requestConfig = configuration;\n\n    if (options.auth0ForwardedFor) {\n      const clientAuth = await this.#getClientAuth();\n      requestConfig = new client.Configuration(\n        configuration.serverMetadata(),\n        this.#options.clientId,\n        this.#options.clientSecret,\n        clientAuth,\n      );\n\n      requestConfig[client.customFetch] = ((url: string, init: client.CustomFetchOptions) => {\n        return (this.#customFetch as client.CustomFetch)(url, {\n          ...init,\n          headers: {\n            ...init.headers,\n            'auth0-forwarded-for': options.auth0ForwardedFor!,\n          },\n        } as client.CustomFetchOptions);\n      }) as client.CustomFetch;\n    }\n\n    try {\n      const tokenEndpointResponse = await client.genericGrantRequest(\n        requestConfig,\n        'password',\n        params\n      );\n\n      return TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);\n    } catch (e) {\n      throw new TokenByPasswordError(\n        'There was an error while trying to request a token.',\n        toOAuth2Error(e)\n      );\n    }\n  }\n\n  /**\n   * Retrieves a token by exchanging client credentials.\n   * @param options Options for retrieving the token.\n   *\n   * @throws {TokenByClientCredentialsError} If there was an issue requesting the access token.\n   *\n   * @returns A Promise, resolving to the TokenResponse as returned from Auth0.\n   */\n  public async getTokenByClientCredentials(options: TokenByClientCredentialsOptions): Promise<TokenResponse> {\n    const { configuration } = await this.#discover();\n\n    try {\n      const params = new URLSearchParams({\n        audience: options.audience,\n      });\n\n      if (options.organization) {\n        params.append('organization', options.organization);\n      }\n\n      const tokenEndpointResponse = await client.clientCredentialsGrant(configuration, params);\n\n      return TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);\n    } catch (e) {\n      throw new TokenByClientCredentialsError('There was an error while trying to request a token.', toOAuth2Error(e));\n    }\n  }\n\n  /**\n   * Builds the URL to redirect the user-agent to to request logout at Auth0.\n   * @param options Options used to configure the logout URL.\n   * @returns A promise resolving to the URL to redirect the user-agent to.\n   */\n  public async buildLogoutUrl(options: BuildLogoutUrlOptions): Promise<URL> {\n    const { configuration, serverMetadata } = await this.#discover();\n\n    // We should not call `client.buildEndSessionUrl` when we do not have an `end_session_endpoint`\n    // In that case, we rely on the v2 logout endpoint.\n    // This can happen for tenants that do not have RP-Initiated Logout enabled.\n    if (!serverMetadata.end_session_endpoint) {\n      const url = new URL(`https://${this.#options.domain}/v2/logout`);\n      url.searchParams.set('returnTo', options.returnTo);\n      url.searchParams.set('client_id', this.#options.clientId);\n      return url;\n    }\n\n    return client.buildEndSessionUrl(configuration, {\n      post_logout_redirect_uri: options.returnTo,\n    });\n  }\n\n  /**\n   * Verifies whether a logout token is valid.\n   * @param options Options used to verify the logout token.\n   *\n   * @throws {VerifyLogoutTokenError} If there was an issue verifying the logout token.\n   *\n   * @returns An object containing the `sid` and `sub` claims from the logout token.\n   */\n  async verifyLogoutToken(options: VerifyLogoutTokenOptions): Promise<VerifyLogoutTokenResult> {\n    const { serverMetadata } = await this.#discover();\n    const cacheConfig = resolveCacheConfig(this.#options.discoveryCache);\n    const jwksUri = serverMetadata!.jwks_uri!;\n\n    this.#jwks ||= createRemoteJWKSet(new URL(jwksUri), {\n      cacheMaxAge: cacheConfig.ttlMs,\n      [customFetch]: this.#customFetch,\n      [jwksCache]: this.#jwksCache,\n    });\n\n    const { payload } = await jwtVerify(options.logoutToken, this.#jwks, {\n      issuer: serverMetadata!.issuer,\n      audience: this.#options.clientId,\n      algorithms: ['RS256'],\n      requiredClaims: ['iat'],\n    });\n\n    if (!('sid' in payload) && !('sub' in payload)) {\n      throw new VerifyLogoutTokenError('either \"sid\" or \"sub\" (or both) claims must be present');\n    }\n\n    if ('sid' in payload && typeof payload.sid !== 'string') {\n      throw new VerifyLogoutTokenError('\"sid\" claim must be a string');\n    }\n\n    if ('sub' in payload && typeof payload.sub !== 'string') {\n      throw new VerifyLogoutTokenError('\"sub\" claim must be a string');\n    }\n\n    if ('nonce' in payload) {\n      throw new VerifyLogoutTokenError('\"nonce\" claim is prohibited');\n    }\n\n    if (!('events' in payload)) {\n      throw new VerifyLogoutTokenError('\"events\" claim is missing');\n    }\n\n    if (typeof payload.events !== 'object' || payload.events === null) {\n      throw new VerifyLogoutTokenError('\"events\" claim must be an object');\n    }\n\n    if (!('http://schemas.openid.net/event/backchannel-logout' in payload.events)) {\n      throw new VerifyLogoutTokenError(\n        '\"http://schemas.openid.net/event/backchannel-logout\" member is missing in the \"events\" claim'\n      );\n    }\n\n    if (typeof payload.events['http://schemas.openid.net/event/backchannel-logout'] !== 'object') {\n      throw new VerifyLogoutTokenError(\n        '\"http://schemas.openid.net/event/backchannel-logout\" member in the \"events\" claim must be an object'\n      );\n    }\n\n    return {\n      sid: payload.sid as string,\n      sub: payload.sub as string,\n    };\n  }\n\n  /**\n   * Gets the client authentication method based on the provided options.\n   *\n   * Supports three authentication methods in order of preference:\n   * 1. mTLS (mutual TLS) - requires customFetch with client certificate\n   * 2. private_key_jwt - requires clientAssertionSigningKey\n   * 3. client_secret_post - requires clientSecret\n   *\n   * @private\n   * @returns The ClientAuth object to use for client authentication.\n   * @throws {MissingClientAuthError} When no valid authentication method is configured\n   */\n  async #getClientAuth(): Promise<client.ClientAuth> {\n    if (!this.#clientAuthPromise) {\n      this.#clientAuthPromise = (async () => {\n        if (!this.#options.clientSecret && !this.#options.clientAssertionSigningKey && !this.#options.useMtls) {\n          throw new MissingClientAuthError();\n        }\n\n        if (this.#options.useMtls) {\n          return client.TlsClientAuth();\n        }\n\n        let clientPrivateKey = this.#options.clientAssertionSigningKey as CryptoKey | undefined;\n\n        if (clientPrivateKey && !(clientPrivateKey instanceof CryptoKey)) {\n          clientPrivateKey = await importPKCS8(\n            clientPrivateKey,\n            this.#options.clientAssertionSigningAlg || 'RS256'\n          );\n        }\n\n        return clientPrivateKey\n          ? client.PrivateKeyJwt(clientPrivateKey)\n          : client.ClientSecretPost(this.#options.clientSecret!);\n      })().catch((error) => {\n        this.#clientAuthPromise = undefined;\n        throw error;\n      });\n    }\n\n    return this.#clientAuthPromise;\n  }\n\n  /**\n   * Builds the URL to redirect the user-agent to to request authorization at Auth0.\n   * @param options Options used to configure the authorization URL.\n   * @returns A promise resolving to an object, containing the authorizationUrl and codeVerifier.\n   */\n  async #buildAuthorizationUrl(options?: BuildAuthorizationUrlOptions): Promise<BuildAuthorizationUrlResult> {\n    const { configuration } = await this.#discover();\n\n    const codeChallengeMethod = 'S256';\n    const codeVerifier = client.randomPKCECodeVerifier();\n    const codeChallenge = await client.calculatePKCECodeChallenge(codeVerifier);\n\n    const additionalParams = stripUndefinedProperties({\n      ...this.#options.authorizationParams,\n      ...options?.authorizationParams,\n    });\n\n    const params = new URLSearchParams({\n      scope: DEFAULT_SCOPES,\n      ...additionalParams,\n      client_id: this.#options.clientId,\n      code_challenge: codeChallenge,\n      code_challenge_method: codeChallengeMethod,\n    });\n\n    const authorizationUrl = options?.pushedAuthorizationRequests\n      ? await client.buildAuthorizationUrlWithPAR(configuration, params)\n      : await client.buildAuthorizationUrl(configuration, params);\n\n    return {\n      authorizationUrl,\n      codeVerifier,\n    };\n  }\n}\n","/**\n * Factor types that can appear in an `mfa_required` error's `mfa_requirements` payload.\n */\nexport type MfaRequiredFactorType =\n  | 'otp'\n  | 'oob'\n  | 'email'\n  | 'webauthn-roaming'\n  | 'webauthn-platform'\n  | 'push-notification'\n  | 'phone';\n\n/**\n * Describes which MFA factors the user must challenge or enroll.\n */\nexport interface MfaRequirements {\n  challenge?: Array<{ type: MfaRequiredFactorType }>;\n  enroll?: Array<{ type: MfaRequiredFactorType }>;\n}\n\n/**\n * Interface to represent an OAuth2 error.\n * When the error is `mfa_required`, `mfa_token` and `mfa_requirements` will be populated.\n */\nexport interface OAuth2Error {\n  error: string;\n  error_description: string;\n  message?: string;\n  mfa_token?: string;\n  mfa_requirements?: MfaRequirements;\n}\n\n/**\n * Normalizes an unknown error (typically thrown by `openid-client`) into an\n * {@link OAuth2Error}.\n *\n * On an `mfa_required` response, `openid-client` nests the server's `mfa_token`\n * and `mfa_requirements` under `error.cause`; this lifts them to the top level\n * so {@link isMfaRequiredError} can detect the error and callers can continue\n * with the MFA APIs.\n *\n * @internal\n */\nexport function toOAuth2Error(e: unknown): OAuth2Error {\n  if (typeof e !== 'object' || e === null) {\n    return { error: 'unknown_error', error_description: String(e) };\n  }\n  const err = e as { error?: string; error_description?: string; cause?: Record<string, unknown>; message?: string };\n  const base: OAuth2Error = {\n    error: err.error ?? '',\n    error_description: err.error_description ?? '',\n    message: err.message,\n  };\n  if (err.error === 'mfa_required' && err.cause) {\n    base.mfa_token = typeof err.cause.mfa_token === 'string' ? err.cause.mfa_token : undefined;\n    const req = err.cause.mfa_requirements;\n    if (typeof req === 'object' && req !== null) {\n      base.mfa_requirements = req as OAuth2Error['mfa_requirements'];\n    }\n  }\n  return base;\n}\n\n/**\n * Error codes used for {@link NotSupportedError}\n */\nexport enum NotSupportedErrorCode {\n  PAR_NOT_SUPPORTED = 'par_not_supported_error',\n  MTLS_WITHOUT_CUSTOMFETCH_NOT_SUPPORT = 'mtls_without_custom_fetch_not_supported',\n}\n\n/**\n * Error thrown when a feature is not supported.\n * For example, when trying to use Pushed Authorization Requests (PAR) but the Auth0 tenant was not configured to support it.\n */\nexport class NotSupportedError extends Error {\n  public code: string;\n\n  constructor(code: string, message: string) {\n    super(message);\n    this.name = 'NotSupportedError';\n    this.code = code;\n  }\n}\n\n/**\n * Base class for API errors, containing the error, error_description and message (if available).\n */\nabstract class ApiError extends Error {\n  public cause?: OAuth2Error;\n  public code: string;\n\n  constructor(code: string, message: string, cause?: OAuth2Error) {\n    super(message);\n\n    this.code = code;\n    this.cause = cause && {\n      error: cause.error,\n      error_description: cause.error_description,\n      message: cause.message,\n      mfa_token: cause.mfa_token,\n      mfa_requirements: cause.mfa_requirements,\n    };\n  }\n}\n\n/**\n * Error thrown when trying to get an access token.\n */\nexport class TokenByCodeError extends ApiError {\n  constructor(message: string, cause?: OAuth2Error) {\n    super('token_by_code_error', message, cause);\n    this.name = 'TokenByCodeError';\n  }\n}\n\n/**\n * Error thrown when trying to get an access token.\n */\nexport class TokenByClientCredentialsError extends ApiError {\n  constructor(message: string, cause?: OAuth2Error) {\n    super('token_by_client_credentials_error', message, cause);\n    this.name = 'TokenByClientCredentialsError';\n  }\n}\n\n/**\n * Error thrown when trying to get an access token.\n */\nexport class TokenByRefreshTokenError extends ApiError {\n  constructor(message: string, cause?: OAuth2Error) {\n    super('token_by_refresh_token_error', message, cause);\n    this.name = 'TokenByRefreshTokenError';\n  }\n}\n\n/**\n * Error thrown when trying to get an access token using Resource Owner Password Grant.\n */\nexport class TokenByPasswordError extends ApiError {\n  constructor(message: string, cause?: OAuth2Error) {\n    super('token_by_password_error', message, cause);\n    this.name = 'TokenByPasswordError';\n  }\n}\n\n/**\n * Error thrown when trying to get an access token for a connection.\n *\n * @deprecated Since v1.2.0, using {@link AuthClient#getTokenForConnection} is deprecated and we recommend to use {@link AuthClient#exchangeToken}.\n * When doing so, use {@link TokenExchangeError} instead of {@link TokenForConnectionError}.\n * This error class remains for backward compatibility and is planned for removal in v2.0.\n */\nexport class TokenForConnectionError extends ApiError {\n  constructor(message: string, cause?: OAuth2Error) {\n    super('token_for_connection_error', message, cause);\n    // NOTE: The name is 'TokenForConnectionErrorCode' (not 'TokenForConnectionError')\n    // for backward compatibility. Consumers may branch on err.name in their error handling.\n    this.name = 'TokenForConnectionErrorCode';\n  }\n}\n\n/**\n * Error thrown when a Token Exchange flow fails. This can occur due to misconfiguration,\n * an invalid subject_token, or if the exchange is denied by the server.\n */\nexport class TokenExchangeError extends ApiError {\n  constructor(message: string, cause?: OAuth2Error) {\n    super('token_exchange_error', message, cause);\n    this.name = 'TokenExchangeError';\n  }\n}\n\n/**\n * Error thrown when verifying the logout token.\n */\nexport class VerifyLogoutTokenError extends Error {\n  public code: string = 'verify_logout_token_error';\n\n  constructor(message: string) {\n    super(message);\n    this.name = 'VerifyLogoutTokenError';\n  }\n}\n\n/**\n * Error thrown when trying to use Client-Initiated Backchannel Authentication.\n */\nexport class BackchannelAuthenticationError extends ApiError {\n  public code: string = 'backchannel_authentication_error';\n\n  constructor(cause?: OAuth2Error) {\n    super(\n      'backchannel_authentication_error',\n      'There was an error when trying to use Client-Initiated Backchannel Authentication.',\n      cause\n    );\n    this.name = 'BackchannelAuthenticationError';\n  }\n}\n\n/**\n * Error thrown when trying to build the authorization URL.\n */\nexport class BuildAuthorizationUrlError extends ApiError {\n  constructor(cause?: OAuth2Error) {\n    super('build_authorization_url_error', 'There was an error when trying to build the authorization URL.', cause);\n    this.name = 'BuildAuthorizationUrlError';\n  }\n}\n\n/**\n * Error thrown when trying to build the Link User URL.\n */\nexport class BuildLinkUserUrlError extends ApiError {\n  constructor(cause?: OAuth2Error) {\n    super('build_link_user_url_error', 'There was an error when trying to build the Link User URL.', cause);\n    this.name = 'BuildLinkUserUrlError';\n  }\n}\n\n/**\n * Error thrown when trying to build the Unlink User URL.\n */\nexport class BuildUnlinkUserUrlError extends ApiError {\n  constructor(cause?: OAuth2Error) {\n    super('build_unlink_user_url_error', 'There was an error when trying to build the Unlink User URL.', cause);\n    this.name = 'BuildUnlinkUserUrlError';\n  }\n}\n\n/**\n * Narrows an error thrown by a token request method to one caused by an `mfa_required` response.\n *\n * When the Auth0 server requires multi-factor authentication, token request methods\n * (`getTokenByPassword`, `getTokenByRefreshToken`, `exchangeToken`, `passkey.getTokenByPasskey`)\n * throw their usual error (e.g. `TokenByPasswordError`, `PasskeyGetTokenError`) with\n * `cause.error` set to `'mfa_required'`.\n * The `cause` will also contain:\n * - `mfa_token` — the token needed to proceed with enrollment or challenge MFA APIs\n * - `mfa_requirements` — (optional) describes which factors to challenge or enroll\n *\n * This type guard checks whether an error was caused by an `mfa_required` response and\n * narrows the type so that `cause` and `cause.mfa_token` are guaranteed to be defined.\n *\n * @param error - The error caught from a token request method\n * @returns `true` if the error was caused by an `mfa_required` server response\n *\n * @example\n * ```typescript\n * import { AuthClient, isMfaRequiredError } from '@auth0/auth0-auth-js';\n *\n * try {\n *   await authClient.getTokenByPassword({ username, password });\n * } catch (error) {\n *   if (isMfaRequiredError(error)) {\n *     // error.cause.mfa_token is guaranteed to be defined here\n *     const challenge = await authClient.mfa.challengeAuthenticator({\n *       mfaToken: error.cause.mfa_token,\n *       challengeType: 'otp',\n *     });\n *   }\n * }\n * ```\n */\nexport interface MfaRequiredError extends Error {\n  code: string;\n  cause: OAuth2Error & { error: 'mfa_required'; mfa_token: string; mfa_requirements?: MfaRequirements };\n}\n\nexport function isMfaRequiredError(error: unknown): error is MfaRequiredError {\n  return (\n    error instanceof Error &&\n    (error as { cause?: OAuth2Error }).cause?.error === 'mfa_required' &&\n    typeof (error as { cause?: OAuth2Error }).cause?.mfa_token === 'string'\n  );\n}\n\n/**\n * Error thrown when Client Secret or Client Assertion Signing Key is missing.\n */\nexport class MissingClientAuthError extends Error {\n  public code: string = 'missing_client_auth_error';\n\n  constructor() {\n    super('The client secret or client assertion signing key must be provided.');\n    this.name = 'MissingClientAuthError';\n  }\n}\n","/**\n * Helper function that removes properties from an object when the value is undefined.\n * @returns The object, without the properties whose values are undefined.\n */\nexport function stripUndefinedProperties<T extends object>(value: T): Partial<T> {\n  return Object.entries(value)\n    .filter(([, value]) => typeof value !== 'undefined')\n    .reduce((acc, curr) => ({ ...acc, [curr[0]]: curr[1] }), {});\n}\n","import * as client from 'openid-client';\nimport type {\n  MfaClientOptions,\n  AuthenticatorResponse,\n  AuthenticatorApiResponse,\n  ListAuthenticatorsOptions,\n  DeleteAuthenticatorOptions,\n  EnrollAuthenticatorOptions,\n  EnrollmentResponse,\n  EnrollmentApiResponse,\n  ChallengeOptions,\n  ChallengeResponse,\n  ChallengeApiResponse,\n  MfaVerifyOptions,\n} from './types.js';\nimport {\n  MfaListAuthenticatorsError,\n  MfaEnrollmentError,\n  MfaDeleteAuthenticatorError,\n  MfaChallengeError,\n  MfaVerifyError,\n  type MfaApiErrorResponse,\n} from './errors.js';\nimport { transformAuthenticatorResponse, transformEnrollmentResponse, transformChallengeResponse } from './utils.js';\nimport { TokenResponse } from '../types.js';\n\nconst GRANT_TYPE_MAP = {\n  otp: 'http://auth0.com/oauth/grant-type/mfa-otp',\n  oob: 'http://auth0.com/oauth/grant-type/mfa-oob',\n  'recovery-code': 'http://auth0.com/oauth/grant-type/mfa-recovery-code',\n} as const;\n\nexport class MfaClient {\n  #baseUrl: string;\n  #clientId: string;\n  #clientSecret?: string;\n  #customFetch: typeof fetch;\n  #getConfiguration?: () => Promise<client.Configuration>;\n\n  /**\n   * @internal\n   */\n  constructor(options: MfaClientOptions) {\n    this.#baseUrl = `https://${options.domain}`;\n    this.#clientId = options.clientId;\n    this.#clientSecret = options.clientSecret;\n    this.#customFetch = options.customFetch ?? ((...args) => fetch(...args));\n    this.#getConfiguration = options.getConfiguration;\n  }\n\n  /**\n   * Lists all MFA authenticators enrolled by the user.\n   *\n   * Retrieves a list of all multi-factor authentication methods that have been\n   * enrolled for the user, including OTP (TOTP), SMS, voice, email, and recovery codes.\n   *\n   * @param options - Options for listing authenticators\n   * @param options.mfaToken - MFA token obtained from an MFA challenge response\n   * @returns Promise resolving to an array of enrolled authenticators\n   * @throws {MfaListAuthenticatorsError} When the request fails (e.g., invalid token, network error)\n   *\n   * @example\n   * ```typescript\n   * const authenticators = await authClient.mfa.listAuthenticators({\n   *   mfaToken: 'your_mfa_token_here'\n   * });\n   *\n   * // authenticators is an array of enrolled authenticators\n   * // Each has: id, authenticatorType, active, name, oobChannels (for OOB types), type\n   * ```\n   */\n  async listAuthenticators(options: ListAuthenticatorsOptions): Promise<AuthenticatorResponse[]> {\n    const url = `${this.#baseUrl}/mfa/authenticators`;\n    const { mfaToken } = options;\n\n    const response = await this.#customFetch(url, {\n      method: 'GET',\n      headers: {\n        Authorization: `Bearer ${mfaToken}`,\n        'Content-Type': 'application/json',\n      },\n    });\n\n    if (!response.ok) {\n      let error: MfaApiErrorResponse;\n      try {\n        error = (await response.json()) as MfaApiErrorResponse;\n      } catch {\n        throw new MfaListAuthenticatorsError('Failed to list authenticators');\n      }\n      throw new MfaListAuthenticatorsError(error.error_description || 'Failed to list authenticators', error);\n    }\n\n    const apiResponse = (await response.json()) as AuthenticatorApiResponse[];\n    return apiResponse.map(transformAuthenticatorResponse);\n  }\n\n  /**\n   * Enrolls a new MFA authenticator for the user.\n   *\n   * Initiates the enrollment process for a new multi-factor authentication method.\n   * Supports OTP (TOTP apps like Google Authenticator), SMS, voice, and email authenticators.\n   *\n   * For OTP enrollment, the response includes a secret and QR code URI that the user\n   * can scan with their authenticator app. For SMS/voice enrollment, a phone number\n   * must be provided. For email enrollment, an optional email address can be specified.\n   *\n   * @param options - Enrollment options (type depends on authenticator being enrolled)\n   * @param options.mfaToken - MFA token obtained from an MFA challenge response\n   * @param options.authenticatorTypes - Array with one authenticator type: 'otp', 'oob', or 'email'\n   * @param options.oobChannels - (OOB only) Delivery channels: 'sms', 'voice', or 'auth0'\n   * @param options.phoneNumber - (OOB only) Phone number in E.164 format (e.g., +1234567890)\n   * @param options.email - (Email only) Email address (optional, uses user's email if not provided)\n   * @returns Promise resolving to enrollment response with authenticator details\n   * @throws {MfaEnrollmentError} When enrollment fails (e.g., invalid parameters, network error)\n   *\n   * @example\n   * ```typescript\n   * // Enroll OTP authenticator (Google Authenticator, etc.)\n   * const otpEnrollment = await authClient.mfa.enrollAuthenticator({\n   *   authenticatorTypes: ['otp'],\n   *   mfaToken: 'your_mfa_token_here'\n   * });\n   * // otpEnrollment.secret - Base32-encoded secret for TOTP\n   * // otpEnrollment.barcodeUri - URI for generating QR code\n   *\n   * // Enroll SMS authenticator\n   * const smsEnrollment = await authClient.mfa.enrollAuthenticator({\n   *   authenticatorTypes: ['oob'],\n   *   oobChannels: ['sms'],\n   *   phoneNumber: '+1234567890',\n   *   mfaToken: 'your_mfa_token_here'\n   * });\n   * ```\n   */\n  async enrollAuthenticator(options: EnrollAuthenticatorOptions): Promise<EnrollmentResponse> {\n    const url = `${this.#baseUrl}/mfa/associate`;\n    const { mfaToken, ...sdkParams } = options;\n\n    // Transform camelCase SDK params to snake_case for API\n    const apiParams: Record<string, unknown> = {\n      authenticator_types: sdkParams.authenticatorTypes,\n    };\n\n    if ('oobChannels' in sdkParams) {\n      apiParams.oob_channels = sdkParams.oobChannels;\n    }\n\n    if ('phoneNumber' in sdkParams && sdkParams.phoneNumber) {\n      apiParams.phone_number = sdkParams.phoneNumber;\n    }\n\n    if ('email' in sdkParams && sdkParams.email) {\n      apiParams.email = sdkParams.email;\n    }\n\n    const response = await this.#customFetch(url, {\n      method: 'POST',\n      headers: {\n        Authorization: `Bearer ${mfaToken}`,\n        'Content-Type': 'application/json',\n      },\n      body: JSON.stringify(apiParams),\n    });\n\n    if (!response.ok) {\n      let error: MfaApiErrorResponse;\n      try {\n        error = (await response.json()) as MfaApiErrorResponse;\n      } catch {\n        throw new MfaEnrollmentError('Failed to enroll authenticator');\n      }\n      throw new MfaEnrollmentError(error.error_description || 'Failed to enroll authenticator', error);\n    }\n\n    const apiResponse = (await response.json()) as EnrollmentApiResponse;\n    return transformEnrollmentResponse(apiResponse);\n  }\n\n  /**\n   * Deletes an enrolled MFA authenticator.\n   *\n   * Removes a previously enrolled multi-factor authentication method from the user's account.\n   * The authenticator ID can be obtained from the listAuthenticators() method.\n   *\n   * @param options - Options for deleting an authenticator\n   * @param options.authenticatorId - ID of the authenticator to delete (e.g., 'totp|dev_abc123')\n   * @param options.mfaToken - MFA token obtained from an MFA challenge response\n   * @returns Promise that resolves when the authenticator is successfully deleted\n   * @throws {MfaDeleteAuthenticatorError} When deletion fails (e.g., invalid ID, network error)\n   *\n   * @example\n   * ```typescript\n   * // First, list authenticators to get the ID\n   * const authenticators = await authClient.mfa.listAuthenticators({\n   *   mfaToken: 'your_mfa_token_here'\n   * });\n   *\n   * // Delete a specific authenticator\n   * await authClient.mfa.deleteAuthenticator({\n   *   authenticatorId: authenticators[0].id,\n   *   mfaToken: 'your_mfa_token_here'\n   * });\n   * ```\n   */\n  async deleteAuthenticator(options: DeleteAuthenticatorOptions): Promise<void> {\n    const { authenticatorId, mfaToken } = options;\n    const url = `${this.#baseUrl}/mfa/authenticators/${encodeURIComponent(authenticatorId)}`;\n\n    const response = await this.#customFetch(url, {\n      method: 'DELETE',\n      headers: {\n        Authorization: `Bearer ${mfaToken}`,\n        'Content-Type': 'application/json',\n      },\n    });\n\n    if (!response.ok) {\n      let error: MfaApiErrorResponse;\n      try {\n        error = (await response.json()) as MfaApiErrorResponse;\n      } catch {\n        throw new MfaDeleteAuthenticatorError('Failed to delete authenticator');\n      }\n      throw new MfaDeleteAuthenticatorError(error.error_description || 'Failed to delete authenticator', error);\n    }\n  }\n\n  /**\n   * Initiates an MFA challenge for user verification.\n   *\n   * Creates a challenge that the user must complete to verify their identity using\n   * one of their enrolled MFA factors. For OTP challenges, the user enters a code\n   * from their authenticator app. For OOB (out-of-band) challenges like SMS, a code\n   * is sent to the user's device.\n   *\n   * @param options - Challenge options\n   * @param options.mfaToken - MFA token obtained from an MFA challenge response\n   * @param options.challengeType - Type of challenge: 'otp' for TOTP apps, 'oob' for SMS/voice/push\n   * @param options.authenticatorId - (Optional) Specific authenticator to challenge\n   * @returns Promise resolving to challenge response with challenge details\n   * @throws {MfaChallengeError} When the challenge fails (e.g., invalid parameters, network error)\n   *\n   * @example\n   * ```typescript\n   * // Challenge with OTP (user enters code from their app)\n   * const otpChallenge = await authClient.mfa.challengeAuthenticator({\n   *   challengeType: 'otp',\n   *   mfaToken: 'your_mfa_token_here'\n   * });\n   *\n   * // Challenge with SMS (code sent to user's phone)\n   * const smsChallenge = await authClient.mfa.challengeAuthenticator({\n   *   challengeType: 'oob',\n   *   authenticatorId: 'sms|dev_abc123',\n   *   mfaToken: 'your_mfa_token_here'\n   * });\n   * // smsChallenge.oobCode - Out-of-band code for verification\n   * ```\n   */\n  async challengeAuthenticator(options: ChallengeOptions): Promise<ChallengeResponse> {\n    const url = `${this.#baseUrl}/mfa/challenge`;\n    const { mfaToken, ...challengeParams } = options;\n\n    const body: Record<string, string | undefined> = {\n      mfa_token: mfaToken,\n      client_id: this.#clientId,\n      challenge_type: challengeParams.challengeType,\n    };\n\n    if (this.#clientSecret) {\n      body.client_secret = this.#clientSecret;\n    }\n\n    if (challengeParams.authenticatorId) {\n      body.authenticator_id = challengeParams.authenticatorId;\n    }\n\n    const response = await this.#customFetch(url, {\n      method: 'POST',\n      headers: {\n        'Content-Type': 'application/json',\n      },\n      body: JSON.stringify(body),\n    });\n\n    if (!response.ok) {\n      let error: MfaApiErrorResponse;\n      try {\n        error = (await response.json()) as MfaApiErrorResponse;\n      } catch {\n        throw new MfaChallengeError('Failed to challenge authenticator');\n      }\n      throw new MfaChallengeError(error.error_description || 'Failed to challenge authenticator', error);\n    }\n\n    const apiResponse = (await response.json()) as ChallengeApiResponse;\n    return transformChallengeResponse(apiResponse);\n  }\n\n  /**\n   * Verifies an MFA challenge by exchanging the MFA token and code for access tokens.\n   *\n   * @param options - The MFA token, factor type (otp / oob / recovery-code), and the code to verify\n   * @returns Promise resolving to a TokenResponse containing the issued tokens\n   * @throws {MfaVerifyError} When verification fails (e.g. invalid token, wrong code, malformed response)\n   */\n  async verify(options: MfaVerifyOptions): Promise<TokenResponse> {\n    if (!this.#getConfiguration) {\n      throw new Error('MFA verify requires a configuration provider (getConfiguration was not set)');\n    }\n\n    const configuration = await this.#getConfiguration();\n\n    const params: Record<string, string> = {\n      mfa_token: options.mfaToken,\n    };\n\n    if (options.audience) {\n      params.audience = options.audience;\n    }\n\n    if (options.factorType === 'otp') {\n      params.otp = options.otp;\n    } else if (options.factorType === 'oob') {\n      params.oob_code = options.oobCode;\n      if (options.bindingCode) {\n        params.binding_code = options.bindingCode;\n      }\n    } else if (options.factorType === 'recovery-code') {\n      params.recovery_code = options.recoveryCode;\n    }\n\n    try {\n      const tokenEndpointResponse = await client.genericGrantRequest(\n        configuration,\n        GRANT_TYPE_MAP[options.factorType],\n        params\n      );\n\n      const tokenResponse = TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);\n\n      if ((tokenEndpointResponse as Record<string, unknown>).recovery_code) {\n        tokenResponse.recoveryCode = (tokenEndpointResponse as Record<string, unknown>).recovery_code as string;\n      }\n\n      return tokenResponse;\n    } catch (e) {\n      if (e instanceof MfaVerifyError) {\n        throw e;\n      }\n      const err = e as { error?: string; error_description?: string; message?: string };\n      throw new MfaVerifyError(err.error_description || err.message || 'Failed to verify MFA challenge', {\n        error: err.error ?? 'mfa_verify_error',\n        error_description: err.error_description ?? err.message ?? 'Failed to verify MFA challenge',\n      });\n    }\n  }\n}\n","/**\n * Interface to represent an MFA API error response.\n */\nexport interface MfaApiErrorResponse {\n  error: string;\n  error_description: string;\n  message?: string;\n}\n\n/**\n * Base class for MFA-related errors.\n */\nabstract class MfaError extends Error {\n  public cause?: MfaApiErrorResponse;\n  public code: string;\n\n  constructor(code: string, message: string, cause?: MfaApiErrorResponse) {\n    super(message);\n\n    this.code = code;\n    this.cause = cause && {\n      error: cause.error,\n      error_description: cause.error_description,\n      message: cause.message,\n    };\n  }\n}\n\n/**\n * Error thrown when listing authenticators fails.\n */\nexport class MfaListAuthenticatorsError extends MfaError {\n  constructor(message: string, cause?: MfaApiErrorResponse) {\n    super('mfa_list_authenticators_error', message, cause);\n    this.name = 'MfaListAuthenticatorsError';\n  }\n}\n\n/**\n * Error thrown when enrolling an authenticator fails.\n */\nexport class MfaEnrollmentError extends MfaError {\n  constructor(message: string, cause?: MfaApiErrorResponse) {\n    super('mfa_enrollment_error', message, cause);\n    this.name = 'MfaEnrollmentError';\n  }\n}\n\n/**\n * Error thrown when deleting an authenticator fails.\n */\nexport class MfaDeleteAuthenticatorError extends MfaError {\n  constructor(message: string, cause?: MfaApiErrorResponse) {\n    super('mfa_delete_authenticator_error', message, cause);\n    this.name = 'MfaDeleteAuthenticatorError';\n  }\n}\n\n/**\n * Error thrown when initiating an MFA challenge fails.\n */\nexport class MfaChallengeError extends MfaError {\n  constructor(message: string, cause?: MfaApiErrorResponse) {\n    super('mfa_challenge_error', message, cause);\n    this.name = 'MfaChallengeError';\n  }\n}\n\n/**\n * Error thrown when MFA verification fails (e.g., invalid OTP, invalid MFA token).\n */\nexport class MfaVerifyError extends MfaError {\n  constructor(message: string, cause?: MfaApiErrorResponse) {\n    super('mfa_verify_error', message, cause);\n    this.name = 'MfaVerifyError';\n  }\n}\n","import type {\n  AuthenticatorResponse,\n  AuthenticatorApiResponse,\n  EnrollmentResponse,\n  EnrollmentApiResponse,\n  ChallengeResponse,\n  ChallengeApiResponse,\n} from './types.js';\n\n/**\n * Transforms API authenticator response (snake_case) to SDK format (camelCase).\n * @internal\n */\nexport function transformAuthenticatorResponse(api: AuthenticatorApiResponse): AuthenticatorResponse {\n  return {\n    id: api.id,\n    authenticatorType: api.authenticator_type,\n    active: api.active,\n    name: api.name,\n    oobChannels: api.oob_channels,\n    type: api.type,\n  };\n}\n\n/**\n * Transforms API enrollment response (snake_case) to SDK format (camelCase).\n * @internal\n */\nexport function transformEnrollmentResponse(api: EnrollmentApiResponse): EnrollmentResponse {\n  if (api.authenticator_type === 'otp') {\n    return {\n      authenticatorType: 'otp',\n      secret: api.secret,\n      barcodeUri: api.barcode_uri,\n      recoveryCodes: api.recovery_codes,\n      id: api.id,\n    };\n  }\n  \n  // OOB - covers SMS, Voice, Auth0, and Email channels\n  if (api.authenticator_type === 'oob') {\n    return {\n      authenticatorType: 'oob',\n      oobChannel: api.oob_channel,\n      oobCode: api.oob_code,\n      bindingMethod: api.binding_method,\n      id: api.id,\n      barcodeUri: api.barcode_uri,\n      recoveryCodes: api.recovery_codes,\n    };\n  }\n\n  throw new Error(`Unexpected authenticator type: ${(api as { authenticator_type: string }).authenticator_type}`);\n}\n\n/**\n * Transforms API challenge response (snake_case) to SDK format (camelCase).\n * Only includes optional fields when they have values.\n * @internal\n */\nexport function transformChallengeResponse(api: ChallengeApiResponse): ChallengeResponse {\n  const result: ChallengeResponse = {\n    challengeType: api.challenge_type,\n  };\n\n  if (api.oob_code !== undefined) {\n    result.oobCode = api.oob_code;\n  }\n\n  if (api.binding_method !== undefined) {\n    result.bindingMethod = api.binding_method;\n  }\n\n  return result;\n}\n","import { IDToken, TokenEndpointResponse, TokenEndpointResponseHelpers } from 'openid-client';\n\nimport type { TelemetryConfig } from './telemetry.js';\nexport type { TelemetryConfig } from './telemetry.js';\n\nexport interface AuthClientOptions {\n  /**\n   * The Auth0 domain to use for authentication.\n   * @example 'example.auth0.com' (without https://)\n   */\n  domain: string;\n  /**\n   * The client ID of the application.\n   */\n  clientId: string;\n  /**\n   * The client secret of the application.\n   */\n  clientSecret?: string;\n  /**\n   * The client assertion signing key to use.\n   */\n  clientAssertionSigningKey?: string | CryptoKey;\n  /**\n   * The client assertion signing algorithm to use.\n   */\n  clientAssertionSigningAlg?: string;\n  /**\n   * Authorization Parameters to be sent with the authorization request.\n   */\n  authorizationParams?: AuthorizationParameters;\n  /**\n   * Optional, custom Fetch implementation to use.\n   */\n  customFetch?: typeof fetch;\n\n  /**\n   * Optional cache configuration for discovery and JWKS lookups.\n   *\n   * Allows:\n   * - Configuring TTL and entry limits\n   *\n   * @example\n   * ```typescript\n   * // Custom cache with longer TTL (per-instance)\n   * { discoveryCache: { ttl: 1800, maxEntries: 200 } }\n   * ```\n   */\n  discoveryCache?: DiscoveryCacheOptions;\n\n  /**\n   * Indicates whether the SDK should use the mTLS endpoints if they are available.\n   *\n   * When set to `true`, using a `customFetch` is required.\n   */\n  useMtls?: boolean;\n\n  /**\n   * Optional telemetry configuration.\n   * Telemetry is enabled by default and sends the Auth0-Client header with package name and version.\n   */\n  telemetry?: TelemetryConfig;\n}\n\nexport interface DiscoveryCacheOptions {\n  /**\n   * Cache time-to-live in seconds.\n   * Each cached entry expires after this duration.\n   *\n   * @default 600\n   */\n  ttl?: number;\n\n  /**\n   * Maximum number of cache entries to keep.\n   * When exceeded, oldest entries (LRU) are evicted.\n   *\n   * @default 100\n   */\n  maxEntries?: number;\n}\n\nexport interface AuthorizationParameters {\n  /**\n   * The scope to use for the authentication request.\n   */\n  scope?: string;\n  /**\n   * The audience to use for the authentication request.\n   */\n  audience?: string;\n  /**\n   * The redirect URI to use for the authentication request, to which Auth0 will redirect the browser after the user has authenticated.\n   * @example 'https://example.com/callback'\n   */\n  redirect_uri?: string;\n\n  [key: string]: unknown;\n}\n\nexport interface BuildAuthorizationUrlOptions {\n  /**\n   * Indicates whether the authorization request should be done using a Pushed Authorization Request.\n   */\n  pushedAuthorizationRequests?: boolean;\n  /**\n   * Authorization Parameters to be sent with the authorization request.\n   */\n  authorizationParams?: AuthorizationParameters;\n}\n\nexport interface BuildAuthorizationUrlResult {\n  /**\n   * The URL to use to authenticate the user, including the query parameters.\n   * Redirect the user to this URL to authenticate.\n   * @example 'https://example.auth0.com/authorize?client_id=...&scope=...'\n   */\n  authorizationUrl: URL;\n  /**\n   * The code verifier that is used for the authorization request.\n   */\n  codeVerifier: string;\n}\n\nexport interface BuildLinkUserUrlOptions {\n  /**\n   * The connection for the user to link.\n   */\n  connection: string;\n  /**\n   * The scope for the connection.\n   */\n  connectionScope: string;\n  /**\n   * The id token of the user initiating the link.\n   */\n  idToken: string;\n  /**\n   * Additional authorization parameters to be sent with the link user request.\n   */\n  authorizationParams?: AuthorizationParameters;\n}\n\nexport interface BuildLinkUserUrlResult {\n  /**\n   * The URL to use to link the user, including the query parameters.\n   * Redirect the user to this URL to link the user.\n   * @example 'https://example.auth0.com/authorize?request_uri=urn:ietf:params:oauth:request_uri&client_id=...'\n   */\n  linkUserUrl: URL;\n  /**\n   * The code verifier that is used for the link user request.\n   */\n  codeVerifier: string;\n}\n\nexport interface BuildUnlinkUserUrlOptions {\n  /**\n   * The connection for the user to unlink.\n   */\n  connection: string;\n  /**\n   * The id token of the user initiating the unlink.\n   */\n  idToken: string;\n  /**\n   * Additional authorization parameters to be sent with the unlink user request.\n   */\n  authorizationParams?: AuthorizationParameters;\n}\n\nexport interface BuildUnlinkUserUrlResult {\n  /**\n   * The URL to use to unlink the user, including the query parameters.\n   * Redirect the user to this URL to unlink the user.\n   * @example 'https://example.auth0.com/authorize?request_uri=urn:ietf:params:oauth:request_uri&client_id=...'\n   */\n  unlinkUserUrl: URL;\n  /**\n   * The code verifier that is used for the unlink user request.\n   */\n  codeVerifier: string;\n}\n\nexport interface TokenByClientCredentialsOptions {\n  /**\n   * The audience for which the token should be requested.\n   */\n  audience: string;\n  /**\n   * The organization for which the token should be requested.\n   */\n  organization?: string;\n}\n\nexport interface TokenByRefreshTokenOptions {\n  /**\n   * The refresh token to use to get a token.\n   */\n  refreshToken: string;\n\n  /**\n   * Optional audience for multi-resource refresh token support.\n   * When specified, requests an access token for this audience.\n   *\n   * @example 'https://api.example.com'\n   */\n  audience?: string;\n\n  /**\n   * When specified, requests an access token with these scopes.\n   * Space-separated scope string.\n   *\n   * @example 'read:data write:data'\n   */\n  scope?: string;\n}\n\nexport interface TokenByPasswordOptions {\n  /**\n   * The username of the user.\n   */\n  username: string;\n  /**\n   * The password of the user.\n   */\n  password: string;\n  /**\n   * The audience for which the token should be requested.\n   */\n  audience?: string;\n  /**\n   * The scope for which the token should be requested.\n   */\n  scope?: string;\n  /**\n   * The realm to use for the authentication request.\n   * \n   * Specifies which database connection or identity provider to authenticate against\n   * when using the password-realm grant type. This is useful when your tenant has\n   * multiple database connections and you need to authenticate against a specific one\n   * instead of using the tenant's default directory.\n   * \n   * @see {@link https://auth0.com/docs/api/authentication/resource-owner-password-flow/get-token Resource Owner Password Flow}\n   * @see {@link https://auth0.com/docs/authenticate/database-connections Database Connections}\n   * @example 'Username-Password-Authentication'\n   */\n  realm?: string;\n  /**\n   * The end-user's IP address.\n   * \n   * When provided, Auth0 uses this IP address for rate limiting and anomaly detection\n   * instead of the IP address of your server. This is particularly useful when your\n   * application acts as a proxy between the end-user and Auth0.\n   * \n   * @see {@link https://auth0.com/docs/api/authentication/resource-owner-password-flow/get-token Authentication API Reference}\n   * @example '203.0.113.42'\n   */\n  auth0ForwardedFor?: string;\n}\n\nexport interface TokenByCodeOptions {\n  /**\n   * The code verifier that is used for the authorization request.\n   */\n  codeVerifier: string;\n}\n\n/**\n * @deprecated Since v1.2.0. Use {@link TokenVaultExchangeOptions} with {@link AuthClient#exchangeToken}.\n * This interface remains for backward compatibility and is planned for removal in v2.0.\n */\nexport interface TokenForConnectionOptions {\n  /**\n   * The connection for which a token should be requested.\n   */\n  connection: string;\n  /**\n   * Login hint to inform which connection account to use, can be useful when multiple accounts for the connection exist for the same user.\n   */\n  loginHint?: string;\n  /**\n   * The refresh token to use to get an access token for the connection.\n   */\n  refreshToken?: string;\n  /**\n   * The access token to use to get an access token for the connection.\n   */\n  accessToken?: string;\n}\n\n/**\n * Configuration options for Token Exchange via Token Exchange Profile (RFC 8693).\n *\n * Token Exchange Profiles enable first-party on-behalf-of flows where you exchange\n * a custom token for Auth0 tokens targeting a different API, while preserving user identity.\n *\n * **Requirements:**\n * - Requires a confidential client (client_secret or client_assertion must be configured)\n * - Requires a Token Exchange Profile to be created in Auth0 via the Management API\n * - The subject_token_type must match a profile configured in your tenant\n * - Reserved namespaces are validated by the Auth0 platform; the SDK does not pre-validate\n * - The organization parameter is not supported during Early Access\n *\n * @see {@link https://auth0.com/docs/authenticate/custom-token-exchange Custom Token Exchange Documentation}\n * @see {@link https://auth0.com/docs/api/management/v2/token-exchange-profiles Token Exchange Profiles API}\n * @see {@link https://www.rfc-editor.org/rfc/rfc8693 RFC 8693: OAuth 2.0 Token Exchange}\n *\n * @example Basic usage\n * ```typescript\n * const response = await authClient.exchangeToken({\n *   subjectTokenType: 'urn:acme:custom-token',\n *   subjectToken: userProvidedToken,\n *   audience: 'https://api.example.com',\n *   scope: 'openid profile read:data'\n * });\n * ```\n *\n * @example With custom parameters for Action validation\n * ```typescript\n * const response = await authClient.exchangeToken({\n *   subjectTokenType: 'urn:acme:legacy-token',\n *   subjectToken: legacyToken,\n *   audience: 'https://api.example.com',\n *   scope: 'openid offline_access',\n *   extra: {\n *     device_id: 'device-12345',\n *     session_token: 'sess-abc'\n *   }\n * });\n * ```\n */\nexport interface ExchangeProfileOptions {\n  /**\n   * A URI that identifies the type of the subject token being exchanged.\n   * Must match a subject_token_type configured in a Token Exchange Profile.\n   *\n   * For custom token types, this must be a URI scoped under your own ownership.\n   *\n   * **Reserved namespaces** (validated by Auth0 platform):\n   * - http://auth0.com, https://auth0.com\n   * - http://okta.com, https://okta.com\n   * - urn:ietf, urn:auth0, urn:okta\n   *\n   * @example \"urn:acme:legacy-token\"\n   * @example \"http://acme.com/mcp-token\"\n   */\n  subjectTokenType: string;\n\n  /**\n   * The token to be exchanged.\n   */\n  subjectToken: string;\n\n  /**\n   * The unique identifier (audience) of the target API.\n   * Must match an API identifier configured in your Auth0 tenant.\n   *\n   * @example \"https://api.example.com\"\n   */\n  audience?: string;\n\n  /**\n   * Space-separated list of OAuth 2.0 scopes to request.\n   * Scopes must be allowed by the target API and token exchange profile configuration.\n   *\n   * @example \"openid profile email\"\n   * @example \"openid profile read:data write:data\"\n   */\n  scope?: string;\n\n  /**\n   * Type of token being requested (RFC 8693).\n   * Defaults to access_token if not specified.\n   *\n   * @see {@link https://datatracker.ietf.org/doc/html/rfc8693#section-2.1 RFC 8693 Section 2.1}\n   * @example \"urn:ietf:params:oauth:token-type:access_token\"\n   * @example \"urn:ietf:params:oauth:token-type:refresh_token\"\n   */\n  requestedTokenType?: string;\n\n  /**\n   * ID or name of the organization to use when authenticating a user.\n   * When provided, the user will be authenticated within the organization context,\n   * and the organization ID will be present in the access token payload.\n   *\n   * @see https://auth0.com/docs/manage-users/organizations\n   */\n  organization?: string;\n\n  /**\n   * The actor token to include in the delegation exchange (RFC 8693).\n   *\n   * When provided, identifies the acting party (the intermediate service or agent)\n   * on whose behalf the exchange is being performed. The resulting token will carry\n   * an `act` claim describing the actor.\n   *\n   * Must be used together with `actorTokenType`.\n   *\n   * @see {@link https://www.rfc-editor.org/rfc/rfc8693#section-2.1 RFC 8693 Section 2.1}\n   */\n  actorToken?: string;\n\n  /**\n   * A URI that identifies the type of the actor token (RFC 8693).\n   *\n   * Must be a syntactically valid URI. Reserved namespaces are validated by the\n   * Auth0 platform, not the SDK.\n   *\n   * Must be used together with `actorToken`.\n   *\n   * @example \"urn:acme:actor-token\"\n   * @example \"http://acme.com/service-token\"\n   */\n  actorTokenType?: string;\n\n  /**\n   * Additional custom parameters accessible in Auth0 Actions via event.request.body.\n   *\n   * Use for context like device fingerprints, session IDs, or business metadata.\n   * Cannot override reserved OAuth parameters.\n   *\n   * Array values are limited to 20 items per key to prevent DoS attacks.\n   *\n   * **Security Warning**: Never include PII (Personally Identifiable Information),\n   * secrets, passwords, or sensitive data in extra parameters. These values may be\n   * logged by Auth0, stored in audit trails, or visible in network traces. Use only\n   * for non-sensitive metadata like device IDs, session identifiers, or request context.\n   *\n   * @example\n   * ```typescript\n   * {\n   *   device_fingerprint: 'a3d8f7b2c1e4...',\n   *   session_id: 'sess_abc123',\n   *   risk_score: '0.95'\n   * }\n   * ```\n   */\n  extra?: Record<string, string | string[]>;\n}\n\n/**\n * Configuration options for Access Token Exchange with Token Vault.\n *\n * Access Token Exchange with Token Vault enables secure access to third-party APIs (e.g., Google Calendar, Salesforce)\n * by exchanging an Auth0 token for an external provider's access token without the client handling\n * the external provider's refresh tokens.\n *\n * **Requirements:**\n * - Requires a confidential client (client credentials must be configured)\n * - Token Vault must be enabled for the specified connection\n * - The connection must support the requested token type\n *\n * @see {@link https://auth0.com/docs/secure/tokens/token-vault Token Vault Documentation}\n * @see {@link https://auth0.com/docs/secure/tokens/token-vault/configure-token-vault Configure Token Vault}\n *\n * @example Using an access token\n * ```typescript\n * const response = await authClient.exchangeToken({\n *   connection: 'google-oauth2',\n *   subjectToken: auth0AccessToken,\n *   subjectTokenType: 'urn:ietf:params:oauth:token-type:access_token',\n *   loginHint: 'user@example.com'\n * });\n * ```\n *\n * @example Using a refresh token\n * ```typescript\n * const response = await authClient.exchangeToken({\n *   connection: 'google-oauth2',\n *   subjectToken: auth0RefreshToken,\n *   subjectTokenType: 'urn:ietf:params:oauth:token-type:refresh_token'\n * });\n * ```\n */\nexport interface TokenVaultExchangeOptions {\n  /**\n   * The name of the connection configured in Auth0 with Token Vault enabled.\n   *\n   * @example \"google-oauth2\"\n   * @example \"salesforce\"\n   */\n  connection: string;\n\n  /**\n   * The Auth0 token to exchange (access token or refresh token).\n   */\n  subjectToken: string;\n\n  /**\n   * Type of the Auth0 token being exchanged.\n   *\n   * **Important**: Defaults to `urn:ietf:params:oauth:token-type:access_token` if not specified.\n   * If you're passing a refresh token, you MUST explicitly set this to\n   * `urn:ietf:params:oauth:token-type:refresh_token` to avoid token type mismatch errors.\n   *\n   * @default 'urn:ietf:params:oauth:token-type:access_token'\n   */\n  subjectTokenType?: 'urn:ietf:params:oauth:token-type:access_token' | 'urn:ietf:params:oauth:token-type:refresh_token';\n\n  /**\n   * Type of token being requested from the external provider.\n   * Typically defaults to the external provider's access token type.\n   */\n  requestedTokenType?: string;\n\n  /**\n   * Hint about which external provider account to use.\n   * Useful when multiple accounts for the connection exist for the same user.\n   *\n   * @example \"user@example.com\"\n   * @example \"external_user_id_123\"\n   */\n  loginHint?: string;\n\n  /**\n   * Space-separated list of scopes to request from the external provider.\n   *\n   * @example \"https://www.googleapis.com/auth/calendar.readonly\"\n   */\n  scope?: string;\n\n  /**\n   * Additional custom parameters.\n   * Cannot override reserved OAuth parameters.\n   *\n   * Array values are limited to 20 items per key to prevent DoS attacks.\n   */\n  extra?: Record<string, string | string[]>;\n}\n\nexport interface BuildLogoutUrlOptions {\n  /**\n   * The URL to which the user should be redirected after the logout.\n   * @example 'https://example.com'\n   */\n  returnTo: string;\n}\n\nexport interface VerifyLogoutTokenOptions {\n  /**\n   * The logout token to verify.\n   */\n  logoutToken: string;\n}\n\nexport interface VerifyLogoutTokenResult {\n  /**\n   * The sid claim of the logout token.\n   */\n  sid: string;\n  /**\n   * The sub claim of the logout token.\n   */\n  sub: string;\n}\n\nexport interface AuthorizationDetails {\n  readonly type: string;\n  readonly [parameter: string]: unknown;\n}\n\n/**\n * Represents the `act` (actor) claim in a token response (RFC 8693).\n *\n * Present when a token was issued via a delegation exchange, identifying the\n * acting party (e.g., an intermediate service) that performed the exchange on\n * behalf of the subject.\n *\n * @see {@link https://www.rfc-editor.org/rfc/rfc8693#section-4.1 RFC 8693 Section 4.1}\n */\nexport interface ActClaim {\n  /**\n   * The subject identifier of the actor.\n   */\n  sub: string;\n  [key: string]: unknown;\n}\n\n/**\n * Represents a successful token response from Auth0.\n *\n * Contains all tokens and metadata returned from Auth0 token endpoints,\n * including standard OAuth 2.0 tokens and optional OIDC tokens.\n */\nexport class TokenResponse {\n  /**\n   * The access token retrieved from Auth0.\n   */\n  accessToken: string;\n  /**\n   * The id token retrieved from Auth0.\n   */\n  idToken?: string;\n  /**\n   * The refresh token retrieved from Auth0.\n   */\n  refreshToken?: string;\n  /**\n   * The time at which the access token expires (Unix timestamp in seconds).\n   */\n  expiresAt: number;\n  /**\n   * The scope of the access token.\n   */\n  scope?: string;\n  /**\n   * The claims of the id token.\n   */\n  claims?: IDToken;\n  /**\n   * The authorization details of the token response.\n   */\n  authorizationDetails?: AuthorizationDetails[];\n\n  /**\n   * The type of the token (typically \"Bearer\").\n   */\n  tokenType?: string;\n\n  /**\n   * A URI that identifies the type of the issued token (RFC 8693).\n   *\n   * @see {@link https://datatracker.ietf.org/doc/html/rfc8693#section-3 RFC 8693 Section 3}\n   * @example \"urn:ietf:params:oauth:token-type:access_token\"\n   */\n  issuedTokenType?: string;\n\n  /**\n   * A new recovery code returned after verifying with a recovery code.\n   * Only present when using the recovery-code MFA factor.\n   */\n  recoveryCode?: string;\n\n  /**\n   * The actor claim from a delegation token exchange (RFC 8693).\n   *\n   * Present when an `actorToken` was provided. Sourced from the ID token when\n   * one is issued, or from the JWT access token in M2M flows where no ID token\n   * is returned. Identifies the acting party on whose behalf the subject token\n   * was exchanged.\n   *\n   * @see {@link https://www.rfc-editor.org/rfc/rfc8693#section-4.1 RFC 8693 Section 4.1}\n   */\n  act?: ActClaim;\n\n  constructor(\n    accessToken: string,\n    expiresAt: number,\n    idToken?: string,\n    refreshToken?: string,\n    scope?: string,\n    claims?: IDToken,\n    authorizationDetails?: AuthorizationDetails[]\n  ) {\n    this.accessToken = accessToken;\n    this.idToken = idToken;\n    this.refreshToken = refreshToken;\n    this.expiresAt = expiresAt;\n    this.scope = scope;\n    this.claims = claims;\n    this.authorizationDetails = authorizationDetails;\n  }\n\n  /**\n   * Create a TokenResponse from a TokenEndpointResponse (openid-client).\n   *\n   * Populates all standard OAuth 2.0 token response fields plus RFC 8693 extensions.\n   * Safely handles responses that may not include all optional fields (e.g., ID token,\n   * refresh token, issued_token_type).\n   *\n   * @param response The TokenEndpointResponse from the token endpoint.\n   * @returns A TokenResponse instance with all available token data.\n   */\n  static fromTokenEndpointResponse(response: TokenEndpointResponse & TokenEndpointResponseHelpers): TokenResponse {\n    const claims = response.id_token ? response.claims() : undefined;\n\n    const tokenResponse = new TokenResponse(\n      response.access_token,\n      Math.floor(Date.now() / 1000) + Number(response.expires_in),\n      response.id_token,\n      response.refresh_token,\n      response.scope,\n      claims,\n      response.authorization_details\n    );\n\n    tokenResponse.tokenType = response.token_type;\n    tokenResponse.issuedTokenType = (response as typeof response & { issued_token_type?: string }).issued_token_type;\n\n    return tokenResponse;\n  }\n}\n\nexport interface BackchannelAuthenticationOptions {\n  /**\n   * Human-readable message to be displayed at the consumption device and authentication device.\n   * This allows the user to ensure the transaction initiated by the consumption device is the same that triggers the action on the authentication device.\n   */\n  bindingMessage: string;\n  /**\n   * The login hint to inform which user to use.\n   */\n  loginHint: {\n    /**\n     * The `sub` claim of the user that is trying to login using Client-Initiated Backchannel Authentication, and to which a push notification to authorize the login will be sent.\n     */\n    sub: string;\n  };\n  /**\n   * Set a custom expiry time for the CIBA flow in seconds. Defaults to 300 seconds (5 minutes) if not set.\n   */\n  requestedExpiry?: number;\n  /**\n   * Optional authorization details to use Rich Authorization Requests (RAR).\n   * @see https://auth0.com/docs/get-started/apis/configure-rich-authorization-requests\n   */\n  authorizationDetails?: AuthorizationDetails[];\n  /**\n   * Authorization Parameters to be sent with the authorization request.\n   */\n  authorizationParams?: AuthorizationParameters;\n}\n","import type { MfaRequirements } from '../errors.js';\n\n/**\n * Interface to represent a Passkey API error response.\n */\nexport interface PasskeyApiErrorResponse {\n  error: string;\n  error_description: string;\n  message?: string;\n}\n\n/**\n * Passkey token exchange (`getTokenByPasskey`) error response.\n *\n * In addition to the common fields, an `mfa_required` response carries\n * `mfa_token` and `mfa_requirements` (mirroring {@link OAuth2Error}). Only the\n * token exchange can require MFA; the signup/login challenge requests cannot.\n * Use {@link isMfaRequiredError} to detect this case and continue with the MFA APIs.\n */\nexport interface PasskeyGetTokenApiErrorResponse extends PasskeyApiErrorResponse {\n  mfa_token?: string;\n  mfa_requirements?: MfaRequirements;\n}\n\n/**\n * Base class for Passkey-related errors.\n */\nexport abstract class PasskeyError extends Error {\n  public cause?: PasskeyApiErrorResponse;\n  public code: string;\n\n  constructor(code: string, message: string, cause?: PasskeyApiErrorResponse) {\n    super(message);\n\n    this.code = code;\n    this.cause = cause && {\n      error: cause.error,\n      error_description: cause.error_description,\n      message: cause.message,\n    };\n  }\n}\n\n/**\n * Error thrown when requesting a passkey register challenge fails.\n */\nexport class PasskeyRegisterError extends PasskeyError {\n  constructor(message: string, cause?: PasskeyApiErrorResponse) {\n    super('passkey_register_error', message, cause);\n    this.name = 'PasskeyRegisterError';\n  }\n}\n\n/**\n * Error thrown when requesting a passkey login challenge fails.\n */\nexport class PasskeyChallengeError extends PasskeyError {\n  constructor(message: string, cause?: PasskeyApiErrorResponse) {\n    super('passkey_challenge_error', message, cause);\n    this.name = 'PasskeyChallengeError';\n  }\n}\n\n/**\n * Error thrown when exchanging a passkey credential for tokens fails.\n *\n * Unlike the challenge errors, this carries `mfa_token` / `mfa_requirements` on\n * its `cause` when the server responds with `mfa_required`.\n */\nexport class PasskeyGetTokenError extends PasskeyError {\n  declare public cause?: PasskeyGetTokenApiErrorResponse;\n\n  constructor(message: string, cause?: PasskeyGetTokenApiErrorResponse) {\n    super('passkey_get_token_error', message, cause);\n    this.name = 'PasskeyGetTokenError';\n\n    // The base constructor intentionally drops `mfa_token` / `mfa_requirements`\n    // (the challenge errors must not expose them). This error is the only one\n    // that can carry them, so set the full cause here rather than relying on\n    // the base's narrowed copy.\n    this.cause = cause && {\n      error: cause.error,\n      error_description: cause.error_description,\n      message: cause.message,\n      mfa_token: cause.mfa_token,\n      mfa_requirements: cause.mfa_requirements,\n    };\n  }\n}\n","import type {\n  PasskeySignupChallengeResponse,\n  PasskeySignupChallengeApiResponse,\n  PasskeyLoginChallengeResponse,\n  PasskeyLoginChallengeApiResponse,\n} from './types.js';\n\n/**\n * Transforms API signup challenge response to SDK format.\n * @internal\n */\nexport function transformSignupChallengeResponse(\n  api: PasskeySignupChallengeApiResponse\n): PasskeySignupChallengeResponse {\n  return {\n    authSession: api.auth_session,\n    authnParamsPublicKey: { ...api.authn_params_public_key },\n  };\n}\n\n/**\n * Transforms API login challenge response to SDK format.\n * @internal\n */\nexport function transformLoginChallengeResponse(\n  api: PasskeyLoginChallengeApiResponse\n): PasskeyLoginChallengeResponse {\n  return {\n    authSession: api.auth_session,\n    authnParamsPublicKey: { ...api.authn_params_public_key },\n  };\n}\n","import type {\n  PasskeyClientOptions,\n  PasskeySignupChallengeOptions,\n  PasskeySignupChallengeResponse,\n  PasskeySignupChallengeApiResponse,\n  PasskeyLoginChallengeOptions,\n  PasskeyLoginChallengeResponse,\n  PasskeyLoginChallengeApiResponse,\n  GetTokenByPasskeyOptions,\n  GrantRequestFn,\n} from './types.js';\nimport type { TokenResponse } from '../types.js';\nimport { toOAuth2Error } from '../errors.js';\nimport {\n  PasskeyRegisterError,\n  PasskeyChallengeError,\n  PasskeyGetTokenError,\n  type PasskeyApiErrorResponse,\n} from './errors.js';\nimport {\n  transformSignupChallengeResponse,\n  transformLoginChallengeResponse,\n} from './utils.js';\n\n/**\n * Grant type for the Auth0 native passkey (WebAuthn) token exchange.\n *\n * @internal\n */\nexport const PASSKEY_GRANT_TYPE = 'urn:okta:params:oauth:grant-type:webauthn';\n\nexport class PasskeyClient {\n  #baseUrl: string;\n  #clientId: string;\n  #customFetch: typeof fetch;\n  #grantRequest: GrantRequestFn;\n\n  /**\n   * @internal\n   */\n  constructor(options: PasskeyClientOptions) {\n    this.#baseUrl = `https://${options.domain}`;\n    this.#clientId = options.clientId;\n    this.#customFetch = options.customFetch ?? ((...args) => fetch(...args));\n    this.#grantRequest = options.grantRequest;\n  }\n\n  async #parseErrorResponse(response: Response): Promise<PasskeyApiErrorResponse> {\n    try {\n      return (await response.json()) as PasskeyApiErrorResponse;\n    } catch {\n      return {\n        error: 'unknown_error',\n        error_description: `HTTP ${response.status} ${response.statusText}`,\n      };\n    }\n  }\n\n  /**\n   * Requests a passkey signup challenge for a new user.\n   *\n   * Returns the WebAuthn public key creation options that should be passed to\n   * the platform's credential manager (e.g., `navigator.credentials.create()`)\n   * to register a new passkey.\n   *\n   * @param options - User profile data and optional realm\n   * @returns Promise resolving to the signup challenge with auth session and public key creation options\n   * @throws {PasskeyRegisterError} When the challenge request fails\n   *\n   * @example\n   * ```typescript\n   * const challenge = await authClient.passkey.register({\n   *   email: 'user@example.com',\n   *   name: 'Jane Doe',\n   *   realm: 'Username-Password-Authentication'\n   * });\n   * ```\n   */\n  async register(options: PasskeySignupChallengeOptions): Promise<PasskeySignupChallengeResponse> {\n    const url = `${this.#baseUrl}/passkey/register`;\n\n    const userProfile: Record<string, unknown> = {\n      ...(options.email && { email: options.email }),\n      ...(options.name && { name: options.name }),\n      ...(options.phoneNumber && { phone_number: options.phoneNumber }),\n      ...(options.username && { username: options.username }),\n      ...(options.givenName && { given_name: options.givenName }),\n      ...(options.familyName && { family_name: options.familyName }),\n      ...(options.nickname && { nickname: options.nickname }),\n      ...(options.picture && { picture: options.picture }),\n    };\n\n    const body: Record<string, unknown> = {\n      client_id: this.#clientId,\n      user_profile: userProfile,\n    };\n\n    if (options.realm) body.realm = options.realm;\n    if (options.organization) body.organization = options.organization;\n    if (options.userMetadata) body.user_metadata = options.userMetadata;\n\n    const response = await this.#customFetch(url, {\n      method: 'POST',\n      headers: { 'Content-Type': 'application/json' },\n      body: JSON.stringify(body),\n    });\n\n    if (!response.ok) {\n      const error = await this.#parseErrorResponse(response);\n      throw new PasskeyRegisterError(error.error_description || 'Failed to request signup challenge', error);\n    }\n\n    const apiResponse = (await response.json()) as PasskeySignupChallengeApiResponse;\n    return transformSignupChallengeResponse(apiResponse);\n  }\n\n  /**\n   * Requests a passkey login challenge for an existing user.\n   *\n   * Returns the WebAuthn public key request options that should be passed to\n   * the platform's credential manager (e.g., `navigator.credentials.get()`)\n   * to retrieve an existing passkey.\n   *\n   * @param options - Optional realm configuration\n   * @returns Promise resolving to the login challenge with auth session and public key request options\n   * @throws {PasskeyChallengeError} When the challenge request fails\n   *\n   * @example\n   * ```typescript\n   * const challenge = await authClient.passkey.challenge({\n   *   realm: 'Username-Password-Authentication'\n   * });\n   * ```\n   */\n  async challenge(options?: PasskeyLoginChallengeOptions): Promise<PasskeyLoginChallengeResponse> {\n    const url = `${this.#baseUrl}/passkey/challenge`;\n\n    const body: Record<string, unknown> = {\n      client_id: this.#clientId,\n    };\n\n    if (options?.realm) body.realm = options.realm;\n    if (options?.organization) body.organization = options.organization;\n\n    const response = await this.#customFetch(url, {\n      method: 'POST',\n      headers: { 'Content-Type': 'application/json' },\n      body: JSON.stringify(body),\n    });\n\n    if (!response.ok) {\n      const error = await this.#parseErrorResponse(response);\n      throw new PasskeyChallengeError(error.error_description || 'Failed to request login challenge', error);\n    }\n\n    const apiResponse = (await response.json()) as PasskeyLoginChallengeApiResponse;\n    return transformLoginChallengeResponse(apiResponse);\n  }\n\n  /**\n   * Exchanges a passkey credential for tokens using the WebAuthn grant type.\n   *\n   * This method should be called after obtaining a credential response from the\n   * platform's WebAuthn API (via `navigator.credentials.create()` for signup or\n   * `navigator.credentials.get()` for login), using the challenge obtained from\n   * `register()` or `challenge()`.\n   *\n   * Unlike `register()` and `challenge()` (which work with public clients), this\n   * token exchange requires a **confidential client** — the `AuthClient` must be\n   * configured with a `clientSecret` or a `clientAssertionSigningKey`. Without\n   * client credentials it throws a `PasskeyGetTokenError` whose `cause` reports\n   * that a client secret or client assertion signing key is required.\n   *\n   * @param options - The auth session and serialized credential response\n   * @returns Promise resolving to a TokenResponse with access token, ID token, and optional refresh token\n   * @throws {PasskeyGetTokenError} When the token exchange fails, or when no client credentials are configured\n   *\n   * @example\n   * ```typescript\n   * const challenge = await authClient.passkey.challenge();\n   * // Pass challenge.authnParamsPublicKey to navigator.credentials.get()\n   * // Then serialize the credential response and exchange for tokens:\n   * const tokens = await authClient.passkey.getTokenByPasskey({\n   *   authSession: challenge.authSession,\n   *   credential: serializedCredential,\n   *   scope: 'openid profile email',\n   *   audience: 'https://api.example.com',\n   * });\n   * ```\n   */\n  async getTokenByPasskey(options: GetTokenByPasskeyOptions): Promise<TokenResponse> {\n    const params = new URLSearchParams({\n      auth_session: options.authSession,\n      authn_response: JSON.stringify(options.credential),\n    });\n\n    if (options.realm) params.append('realm', options.realm);\n    if (options.scope) params.append('scope', options.scope);\n    if (options.audience) params.append('audience', options.audience);\n    if (options.organization) params.append('organization', options.organization);\n\n    try {\n      return await this.#grantRequest(PASSKEY_GRANT_TYPE, params);\n    } catch (e) {\n      const apiError = toOAuth2Error(e);\n      throw new PasskeyGetTokenError(\n        apiError.error_description || 'Failed to exchange passkey credential for tokens.',\n        apiError,\n      );\n    }\n  }\n}\n","export interface TelemetryData {\n  /**\n   * Override the package name in the telemetry header.\n   */\n  name: string;\n  /**\n   * Override the package version in the telemetry header.\n   */\n  version: string;\n}\n\nexport type TelemetryConfig = { enabled: false } | ({ enabled?: true } & TelemetryData);\n\n/**\n * Creates a fetch wrapper that adds the Auth0-Client telemetry header to all requests.\n *\n * @param baseFetch The base fetch implementation to wrap\n * @param config telemetry configuration\n * @returns A wrapped fetch function that adds the Auth0-Client header\n */\nexport function createTelemetryFetch(baseFetch: typeof fetch, config: TelemetryConfig): typeof fetch {\n  // If telemetry disabled, return original fetch\n  if (config.enabled === false) {\n    return baseFetch;\n  }\n\n  // Create header value\n  const telemetryData = {\n    name: config.name,\n    version: config.version,\n  };\n\n  const headerValue = btoa(JSON.stringify(telemetryData));\n\n  // Return wrapped fetch that adds header\n  return async (input: RequestInfo | URL, init?: RequestInit) => {\n    // Start with headers from Request object if input is a Request\n    const headers = input instanceof Request ? new Headers(input.headers) : new Headers();\n\n    // Merge headers from init (these override Request headers)\n    if (init?.headers) {\n      const initHeaders = new Headers(init.headers);\n      initHeaders.forEach((value, key) => {\n        headers.set(key, value);\n      });\n    }\n\n    // Add telemetry header\n    headers.set('Auth0-Client', headerValue);\n\n    return baseFetch(input, { ...init, headers });\n  };\n}\n\n// These constants are injected at build time via tsup\ndeclare const __AUTH0_AUTH_JS_PACKAGE_NAME__: string;\ndeclare const __AUTH0_AUTH_JS_PACKAGE_VERSION__: string;\n\nexport function getTelemetryConfig(config?: TelemetryConfig): TelemetryConfig {\n  if (config?.enabled === false) {\n    return config;\n  }\n\n  return {\n    enabled: true,\n    name: config?.name ?? __AUTH0_AUTH_JS_PACKAGE_NAME__,\n    version: config?.version ?? __AUTH0_AUTH_JS_PACKAGE_VERSION__,\n  };\n}\n","import type { DiscoveryCache } from './cache-provider.js';\n\n/**\n * LRU (Least Recently Used) Cache implementation.\n *\n * Provides in-memory caching with:\n * - TTL (Time-To-Live) support for automatic expiration\n * - LRU eviction when capacity is exceeded\n * - O(1) get/set operations\n *\n * The cache is generic over key and value types for type safety.\n *\n * @template K - Cache key type (typically string)\n * @template V - Cache value type\n *\n * @example\n * ```typescript\n * // Create a cache with 100 entries and 10 minute TTL\n * const cache = new LruCache<string, MyData>(100, 600_000);\n *\n * // Store data\n * cache.set('key1', data);\n *\n * // Retrieve data (returns undefined if expired)\n * const value = cache.get('key1');\n * ```\n */\nexport class LruCache<K, V> implements DiscoveryCache<K, V> {\n  readonly #entries = new Map<K, { value: V; expiresAt: number }>();\n  readonly #ttlMs: number;\n  readonly #maxEntries: number;\n\n  /**\n   * Create a new LRU cache.\n   *\n   * @param maxEntries - Maximum number of entries. Minimum 1.\n   * @param ttlMs - Time-to-live in milliseconds for each entry. Minimum 0.\n   */\n  constructor(maxEntries: number, ttlMs: number) {\n    this.#maxEntries = Math.max(1, Math.floor(maxEntries));\n    this.#ttlMs = Math.max(0, Math.floor(ttlMs));\n  }\n\n  /**\n   * Retrieves a value from the cache.\n   *\n   * Returns undefined if:\n   * - Key doesn't exist\n   * - Entry has expired\n   *\n   * Automatically deletes expired entries.\n   * Updates LRU order by moving accessed entries to the end.\n   *\n   * @param key - Cache key\n   * @returns Cached value or undefined\n   */\n  get(key: K): V | undefined {\n    const entry = this.#entries.get(key);\n    if (!entry) {\n      return;\n    }\n\n    // Check if expired\n    if (Date.now() >= entry.expiresAt) {\n      this.#entries.delete(key);\n      return;\n    }\n\n    // Update LRU order by moving to end\n    this.#entries.delete(key);\n    this.#entries.set(key, entry);\n    return entry.value;\n  }\n\n  /**\n   * Stores a value in the cache.\n   *\n   * If entry already exists, updates it and moves it to the end (most recently used).\n   * If cache is full, evicts the least recently used entry.\n   *\n   * @param key - Cache key\n   * @param value - Value to cache\n   */\n  set(key: K, value: V): void {\n    if (this.#entries.has(key)) {\n      this.#entries.delete(key);\n    }\n\n    this.#entries.set(key, {\n      value,\n      expiresAt: Date.now() + this.#ttlMs,\n    });\n\n    // Evict LRU when over capacity\n    while (this.#entries.size > this.#maxEntries) {\n      const oldestKey = this.#entries.keys().next().value;\n      if (oldestKey === undefined) {\n        break;\n      }\n      this.#entries.delete(oldestKey);\n    }\n  }\n}\n","/**\n * Cache provider factory and utilities.\n *\n * This module handles cache instantiation based on user configuration.\n * It abstracts away the complexity of choosing between built-in and custom implementations.\n *\n * @module cache-provider\n */\n\nimport type { DiscoveryCacheOptions } from './types.js';\nimport type { JWKSCacheInput } from 'jose';\nimport { LruCache } from './lru-cache.js';\n\n/**\n * Internal cache contract used by cache implementations in this package.\n *\n * Not part of the public API surface.\n */\nexport interface DiscoveryCache<K = string, V = unknown> {\n  get(key: K): V | undefined;\n  set(key: K, value: V, ttlMs?: number): void;\n}\n\n/**\n * Global cache storage for shared caches across all AuthClient instances.\n * Key format: \"${maxEntries}:${ttlMs}\"\n */\nconst globalCaches = new Map<string, DiscoveryCache>();\n\nfunction getGlobalCache<K, V>(key: string): DiscoveryCache<K, V> | undefined {\n  return globalCaches.get(key) as DiscoveryCache<K, V> | undefined;\n}\n\n/**\n * Creates a cache key for global cache lookup.\n * @param maxEntries - Maximum cache entries\n * @param ttlMs - Time to live in milliseconds\n * @returns Cache key string\n */\nfunction getGlobalCacheKey(maxEntries: number, ttlMs: number): string {\n  return `${maxEntries}:${ttlMs}`;\n}\n\n/**\n * Resolved cache configuration combining TTL and provider strategy.\n */\nexport interface ResolvedCacheConfig {\n  ttlMs: number;\n  maxEntries: number;\n}\n\n/**\n * Resolves cache configuration to a consistent format.\n *\n * Handles:\n * - Default values for TTL and maxEntries\n * - Validation of cache options\n * - Provider strategy selection\n *\n * @param options - User-provided cache options\n * @returns Resolved cache configuration\n *\n * @throws {Error} If configuration is invalid\n */\nexport function resolveCacheConfig(options?: DiscoveryCacheOptions): ResolvedCacheConfig {\n  const ttlSeconds = typeof options?.ttl === 'number' ? options.ttl : 600; // Default 10 minutes\n\n  const maxEntries = typeof options?.maxEntries === 'number' && options.maxEntries > 0 ? options.maxEntries : 100;\n\n  const ttlMs = ttlSeconds * 1000;\n\n  return {\n    ttlMs,\n    maxEntries,\n  };\n}\n\n/**\n * Discovery cache factory.\n *\n * Creates appropriate cache implementation based on provider strategy.\n */\nexport class DiscoveryCacheFactory {\n  /**\n   * Create a discovery cache instance.\n   *\n   * @param config - Resolved cache configuration\n   * @returns Discovery cache instance, or null-like object if caching disabled\n   */\n  static createDiscoveryCache<K = string, V = unknown>(config: ResolvedCacheConfig): DiscoveryCache<K, V> {\n    // Get or create global cache for this configuration\n    const cacheKey = getGlobalCacheKey(config.maxEntries, config.ttlMs);\n    let cache = getGlobalCache(cacheKey);\n\n    if (!cache) {\n      cache = new LruCache<K, V>(config.maxEntries, config.ttlMs);\n      globalCaches.set(cacheKey, cache);\n    }\n\n    return cache as DiscoveryCache<K, V>;\n  }\n\n  /**\n   * Create a JWKS cache instance.\n   *\n   * @param config - Resolved cache configuration\n   * @returns JWKS cache instance\n   */\n  static createJwksCache(): JWKSCacheInput {\n    return {};\n  }\n}\n\n/**\n * Clears all global caches.\n * Useful for testing or when you need to reset cache state.\n *\n * @internal\n */\nexport function clearGlobalCaches(): void {\n  globalCaches.clear();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,UAAwB;AACxB,kBAA8F;;;AC0CvF,SAAS,cAAc,GAAyB;AACrD,MAAI,OAAO,MAAM,YAAY,MAAM,MAAM;AACvC,WAAO,EAAE,OAAO,iBAAiB,mBAAmB,OAAO,CAAC,EAAE;AAAA,EAChE;AACA,QAAM,MAAM;AACZ,QAAM,OAAoB;AAAA,IACxB,OAAO,IAAI,SAAS;AAAA,IACpB,mBAAmB,IAAI,qBAAqB;AAAA,IAC5C,SAAS,IAAI;AAAA,EACf;AACA,MAAI,IAAI,UAAU,kBAAkB,IAAI,OAAO;AAC7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