@auth0/auth0-spa-js 2.15.0 → 2.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"auth0-spa-js.development.js","sources":["../src/version.ts","../src/constants.ts","../src/errors.ts","../src/utils.ts","../node_modules/browser-tabs-lock/processLock.js","../node_modules/browser-tabs-lock/index.js","../src/lock.ts","../node_modules/dpop/src/index.ts","../src/dpop/utils.ts","../src/worker/worker.utils.ts","../src/http.ts","../src/api.ts","../src/scope.ts","../src/cache/shared.ts","../src/cache/cache-localstorage.ts","../src/cache/cache-memory.ts","../src/cache/cache-manager.ts","../src/transaction-manager.ts","../src/jwt.ts","../node_modules/es-cookie/src/es-cookie.js","../src/storage.ts","../src/global.ts","../src/promise-utils.ts","../src/cache/key-manifest.ts","../src/Auth0Client.utils.ts","../src/dpop/storage.ts","../src/dpop/dpop.ts","../src/fetcher.ts","../src/MyAccountApiClient.ts","../src/mfa/constants.ts","../src/mfa/utils.ts","../node_modules/oauth4webapi/src/index.ts","../node_modules/jose/dist/webapi/lib/buffer_utils.js","../node_modules/jose/dist/webapi/lib/base64.js","../node_modules/jose/dist/webapi/util/base64url.js","../node_modules/jose/dist/webapi/util/errors.js","../node_modules/jose/dist/webapi/lib/crypto_key.js","../node_modules/jose/dist/webapi/lib/invalid_key_input.js","../node_modules/jose/dist/webapi/lib/is_key_like.js","../node_modules/jose/dist/webapi/lib/is_disjoint.js","../node_modules/jose/dist/webapi/lib/is_object.js","../node_modules/jose/dist/webapi/lib/check_key_length.js","../node_modules/jose/dist/webapi/lib/asn1.js","../node_modules/jose/dist/webapi/lib/jwk_to_key.js","../node_modules/jose/dist/webapi/key/import.js","../node_modules/jose/dist/webapi/lib/validate_crit.js","../node_modules/jose/dist/webapi/lib/validate_algorithms.js","../node_modules/jose/dist/webapi/lib/is_jwk.js","../node_modules/jose/dist/webapi/lib/normalize_key.js","../node_modules/jose/dist/webapi/lib/check_key_type.js","../node_modules/openid-client/src/index.ts","../node_modules/jose/dist/webapi/lib/subtle_dsa.js","../node_modules/jose/dist/webapi/lib/get_sign_verify_key.js","../node_modules/jose/dist/webapi/lib/verify.js","../node_modules/jose/dist/webapi/jws/flattened/verify.js","../node_modules/jose/dist/webapi/jws/compact/verify.js","../node_modules/jose/dist/webapi/lib/jwt_claims_set.js","../node_modules/jose/dist/webapi/jwt/verify.js","../node_modules/jose/dist/webapi/jwks/local.js","../node_modules/jose/dist/webapi/jwks/remote.js","../node_modules/@auth0/auth0-auth-js/src/errors.ts","../node_modules/@auth0/auth0-auth-js/src/utils.ts","../node_modules/@auth0/auth0-auth-js/src/mfa/errors.ts","../node_modules/@auth0/auth0-auth-js/src/mfa/utils.ts","../node_modules/@auth0/auth0-auth-js/src/mfa/mfa-client.ts","../node_modules/@auth0/auth0-auth-js/src/types.ts","../node_modules/@auth0/auth0-auth-js/src/auth-client.ts","../src/mfa/errors.ts","../src/mfa/MfaContextManager.ts","../src/mfa/MfaApiClient.ts","../src/Auth0Client.ts","../src/index.ts"],"sourcesContent":["export default '2.15.0';\n","import { PopupConfigOptions } from './global';\nimport version from './version';\n\n/**\n * @ignore\n */\nexport const DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS = 60;\n\n/**\n * @ignore\n */\nexport const DEFAULT_POPUP_CONFIG_OPTIONS: PopupConfigOptions = {\n timeoutInSeconds: DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS\n};\n\n/**\n * @ignore\n */\nexport const DEFAULT_SILENT_TOKEN_RETRY_COUNT = 3;\n\n/**\n * @ignore\n */\nexport const CLEANUP_IFRAME_TIMEOUT_IN_SECONDS = 2;\n\n/**\n * @ignore\n */\nexport const DEFAULT_FETCH_TIMEOUT_MS = 10000;\n\nexport const CACHE_LOCATION_MEMORY = 'memory';\nexport const CACHE_LOCATION_LOCAL_STORAGE = 'localstorage';\n\n/**\n * @ignore\n */\nexport const MISSING_REFRESH_TOKEN_ERROR_MESSAGE = 'Missing Refresh Token';\n\n/**\n * @ignore\n */\nexport const INVALID_REFRESH_TOKEN_ERROR_MESSAGE = 'invalid refresh token';\n\n/**\n * @ignore\n */\nexport const USER_BLOCKED_ERROR_MESSAGE = 'user is blocked';\n\n/**\n * @ignore\n */\nexport const DEFAULT_SCOPE = 'openid profile email';\n\n/**\n * @ignore\n */\nexport const DEFAULT_SESSION_CHECK_EXPIRY_DAYS = 1;\n\n/**\n * @ignore\n */\nexport const DEFAULT_AUTH0_CLIENT = {\n name: 'auth0-spa-js',\n version: version\n};\n\nexport const DEFAULT_NOW_PROVIDER = () => Date.now();\n\nexport const DEFAULT_AUDIENCE = 'default';\n","/**\n * MFA requirements from an mfa_required error response\n */\nexport interface MfaRequirements {\n /** Required enrollment types */\n enroll?: Array<{ type: string }>;\n /** Required challenge types */\n challenge?: Array<{ type: string }>;\n}\n\n/**\n * Thrown when network requests to the Auth server fail.\n */\nexport class GenericError extends Error {\n constructor(public error: string, public error_description: string) {\n super(error_description);\n Object.setPrototypeOf(this, GenericError.prototype);\n }\n\n static fromPayload({\n error,\n error_description\n }: {\n error: string;\n error_description: string;\n }) {\n return new GenericError(error, error_description);\n }\n}\n\n/**\n * Thrown when handling the redirect callback fails, will be one of Auth0's\n * Authentication API's Standard Error Responses: https://auth0.com/docs/api/authentication?javascript#standard-error-responses\n */\nexport class AuthenticationError extends GenericError {\n constructor(\n error: string,\n error_description: string,\n public state: string,\n public appState: any = null\n ) {\n super(error, error_description);\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, AuthenticationError.prototype);\n }\n}\n\n/**\n * Thrown when handling the redirect callback for the connect flow fails, will be one of Auth0's\n * Authentication API's Standard Error Responses: https://auth0.com/docs/api/authentication?javascript#standard-error-responses\n */\nexport class ConnectError extends GenericError {\n constructor(\n error: string,\n error_description: string,\n public connection: string,\n public state: string,\n public appState: any = null\n ) {\n super(error, error_description);\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, ConnectError.prototype);\n }\n}\n\n/**\n * Thrown when silent auth times out (usually due to a configuration issue) or\n * when network requests to the Auth server timeout.\n */\nexport class TimeoutError extends GenericError {\n constructor() {\n super('timeout', 'Timeout');\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, TimeoutError.prototype);\n }\n}\n\n/**\n * Error thrown when the login popup times out (if the user does not complete auth)\n */\nexport class PopupTimeoutError extends TimeoutError {\n constructor(public popup: Window) {\n super();\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, PopupTimeoutError.prototype);\n }\n}\n\nexport class PopupCancelledError extends GenericError {\n constructor(public popup: Window) {\n super('cancelled', 'Popup closed');\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, PopupCancelledError.prototype);\n }\n}\n\nexport class PopupOpenError extends GenericError {\n constructor() {\n super('popup_open', 'Unable to open a popup for loginWithPopup - window.open returned `null`');\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, PopupOpenError.prototype);\n }\n}\n\n/**\n * Error thrown when the token exchange results in a `mfa_required` error\n */\nexport class MfaRequiredError extends GenericError {\n constructor(\n error: string,\n error_description: string,\n public mfa_token: string,\n public mfa_requirements: MfaRequirements\n ) {\n super(error, error_description);\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, MfaRequiredError.prototype);\n }\n}\n\n/**\n * Error thrown when there is no refresh token to use\n */\nexport class MissingRefreshTokenError extends GenericError {\n constructor(public audience: string, public scope: string) {\n super(\n 'missing_refresh_token',\n `Missing Refresh Token (audience: '${valueOrEmptyString(audience, [\n 'default'\n ])}', scope: '${valueOrEmptyString(scope)}')`\n );\n Object.setPrototypeOf(this, MissingRefreshTokenError.prototype);\n }\n}\n\n/**\n * Error thrown when there are missing scopes after refreshing a token\n */\nexport class MissingScopesError extends GenericError {\n constructor(public audience: string, public scope: string) {\n super(\n 'missing_scopes',\n `Missing requested scopes after refresh (audience: '${valueOrEmptyString(audience, [\n 'default'\n ])}', missing scope: '${valueOrEmptyString(scope)}')`\n );\n Object.setPrototypeOf(this, MissingScopesError.prototype);\n }\n}\n\n/**\n * Error thrown when the wrong DPoP nonce is used and a potential subsequent retry wasn't able to fix it.\n */\nexport class UseDpopNonceError extends GenericError {\n constructor(public newDpopNonce: string | undefined) {\n super('use_dpop_nonce', 'Server rejected DPoP proof: wrong nonce');\n\n Object.setPrototypeOf(this, UseDpopNonceError.prototype);\n }\n}\n\n/**\n * Returns an empty string when value is falsy, or when it's value is included in the exclude argument.\n * @param value The value to check\n * @param exclude An array of values that should result in an empty string.\n * @returns The value, or an empty string when falsy or included in the exclude argument.\n */\nfunction valueOrEmptyString(value: string, exclude: string[] = []) {\n return value && !exclude.includes(value) ? value : '';\n}\n","import { AuthenticationResult, PopupConfigOptions } from './global';\n\nimport {\n DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS,\n CLEANUP_IFRAME_TIMEOUT_IN_SECONDS\n} from './constants';\n\nimport {\n PopupTimeoutError,\n TimeoutError,\n GenericError,\n PopupCancelledError\n} from './errors';\n\nexport const parseAuthenticationResult = (\n queryString: string\n): AuthenticationResult => {\n if (queryString.indexOf('#') > -1) {\n queryString = queryString.substring(0, queryString.indexOf('#'));\n }\n\n const searchParams = new URLSearchParams(queryString);\n\n return {\n state: searchParams.get('state')!,\n code: searchParams.get('code') || undefined,\n connect_code: searchParams.get('connect_code') || undefined,\n error: searchParams.get('error') || undefined,\n error_description: searchParams.get('error_description') || undefined\n };\n};\n\nexport const runIframe = (\n authorizeUrl: string,\n eventOrigin: string,\n timeoutInSeconds: number = DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS\n) => {\n return new Promise<AuthenticationResult>((res, rej) => {\n const iframe = window.document.createElement('iframe');\n\n iframe.setAttribute('width', '0');\n iframe.setAttribute('height', '0');\n iframe.style.display = 'none';\n\n const removeIframe = () => {\n if (window.document.body.contains(iframe)) {\n window.document.body.removeChild(iframe);\n window.removeEventListener('message', iframeEventHandler, false);\n }\n };\n\n let iframeEventHandler: (e: MessageEvent) => void;\n\n const timeoutSetTimeoutId = setTimeout(() => {\n rej(new TimeoutError());\n removeIframe();\n }, timeoutInSeconds * 1000);\n\n iframeEventHandler = function (e: MessageEvent) {\n if (e.origin != eventOrigin) return;\n if (!e.data || e.data.type !== 'authorization_response') return;\n\n const eventSource = e.source;\n\n if (eventSource) {\n (eventSource as any).close();\n }\n\n e.data.response.error\n ? rej(GenericError.fromPayload(e.data.response))\n : res(e.data.response);\n\n clearTimeout(timeoutSetTimeoutId);\n window.removeEventListener('message', iframeEventHandler, false);\n\n // Delay the removal of the iframe to prevent hanging loading status\n // in Chrome: https://github.com/auth0/auth0-spa-js/issues/240\n setTimeout(removeIframe, CLEANUP_IFRAME_TIMEOUT_IN_SECONDS * 1000);\n };\n\n window.addEventListener('message', iframeEventHandler, false);\n window.document.body.appendChild(iframe);\n iframe.setAttribute('src', authorizeUrl);\n });\n};\n\nexport const openPopup = (url: string) => {\n const width = 400;\n const height = 600;\n const left = window.screenX + (window.innerWidth - width) / 2;\n const top = window.screenY + (window.innerHeight - height) / 2;\n\n return window.open(\n url,\n 'auth0:authorize:popup',\n `left=${left},top=${top},width=${width},height=${height},resizable,scrollbars=yes,status=1`\n );\n};\n\nexport const runPopup = (config: PopupConfigOptions) => {\n return new Promise<AuthenticationResult>((resolve, reject) => {\n let popupEventListener: (e: MessageEvent) => void;\n\n // Check each second if the popup is closed triggering a PopupCancelledError\n const popupTimer = setInterval(() => {\n if (config.popup && config.popup.closed) {\n clearInterval(popupTimer);\n clearTimeout(timeoutId);\n window.removeEventListener('message', popupEventListener, false);\n reject(new PopupCancelledError(config.popup));\n }\n }, 1000);\n\n const timeoutId = setTimeout(() => {\n clearInterval(popupTimer);\n reject(new PopupTimeoutError(config.popup));\n window.removeEventListener('message', popupEventListener, false);\n }, (config.timeoutInSeconds || DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS) * 1000);\n\n popupEventListener = function (e: MessageEvent) {\n if (!e.data || e.data.type !== 'authorization_response') {\n return;\n }\n\n clearTimeout(timeoutId);\n clearInterval(popupTimer);\n window.removeEventListener('message', popupEventListener, false);\n\n // Close popup automatically unless closePopup is explicitly set to false\n if (config.closePopup !== false) {\n config.popup.close();\n }\n\n if (e.data.response.error) {\n return reject(GenericError.fromPayload(e.data.response));\n }\n\n resolve(e.data.response);\n };\n\n window.addEventListener('message', popupEventListener);\n });\n};\n\nexport const getCrypto = () => {\n return window.crypto;\n};\n\nexport const createRandomString = () => {\n const charset =\n '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.';\n let random = '';\n const randomValues = Array.from(\n getCrypto().getRandomValues(new Uint8Array(43))\n );\n randomValues.forEach(v => (random += charset[v % charset.length]));\n return random;\n};\n\nexport const encode = (value: string) => btoa(value);\nexport const decode = (value: string) => atob(value);\n\nconst stripUndefined = (params: any) => {\n return Object.keys(params)\n .filter(k => typeof params[k] !== 'undefined')\n .reduce((acc, key) => ({ ...acc, [key]: params[key] }), {});\n};\n\nconst ALLOWED_AUTH0CLIENT_PROPERTIES = [\n {\n key: 'name',\n type: ['string']\n },\n {\n key: 'version',\n type: ['string', 'number']\n },\n {\n key: 'env',\n type: ['object']\n }\n];\n\n/**\n * Strips any property that is not present in ALLOWED_AUTH0CLIENT_PROPERTIES\n * @param auth0Client - The full auth0Client object\n * @param excludeEnv - If true, excludes the 'env' property from the result\n * @returns The stripped auth0Client object\n */\nexport const stripAuth0Client = (auth0Client: any, excludeEnv = false) => {\n return Object.keys(auth0Client).reduce((acc: any, key: string) => {\n // Exclude 'env' if requested (for /authorize query params to prevent truncation)\n if (excludeEnv && key === 'env') {\n return acc;\n }\n\n const allowedProperty = ALLOWED_AUTH0CLIENT_PROPERTIES.find(\n p => p.key === key\n );\n if (\n allowedProperty &&\n allowedProperty.type.includes(typeof auth0Client[key])\n ) {\n acc[key] = auth0Client[key];\n }\n\n return acc;\n }, {});\n};\n\nexport const createQueryParams = ({ clientId: client_id, ...params }: any) => {\n return new URLSearchParams(\n stripUndefined({ client_id, ...params })\n ).toString();\n};\n\nexport const sha256 = async (s: string) => {\n const digestOp: any = getCrypto().subtle.digest(\n { name: 'SHA-256' },\n new TextEncoder().encode(s)\n );\n\n return await digestOp;\n};\n\nconst urlEncodeB64 = (input: string) => {\n const b64Chars: { [index: string]: string } = { '+': '-', '/': '_', '=': '' };\n return input.replace(/[+/=]/g, (m: string) => b64Chars[m]);\n};\n\n// https://stackoverflow.com/questions/30106476/\nconst decodeB64 = (input: string) =>\n decodeURIComponent(\n atob(input)\n .split('')\n .map(c => {\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);\n })\n .join('')\n );\n\nexport const urlDecodeB64 = (input: string) =>\n decodeB64(input.replace(/_/g, '/').replace(/-/g, '+'));\n\nexport const bufferToBase64UrlEncoded = (input: number[] | Uint8Array) => {\n const ie11SafeInput = new Uint8Array(input);\n return urlEncodeB64(\n window.btoa(String.fromCharCode(...Array.from(ie11SafeInput)))\n );\n};\n\nexport const validateCrypto = () => {\n if (!getCrypto()) {\n throw new Error(\n 'For security reasons, `window.crypto` is required to run `auth0-spa-js`.'\n );\n }\n if (typeof getCrypto().subtle === 'undefined') {\n throw new Error(`\n auth0-spa-js must run on a secure origin. See https://github.com/auth0/auth0-spa-js/blob/main/FAQ.md#why-do-i-get-auth0-spa-js-must-run-on-a-secure-origin for more information.\n `);\n }\n};\n\n/**\n * @ignore\n */\nexport const getDomain = (domainUrl: string) => {\n if (!/^https?:\\/\\//.test(domainUrl)) {\n return `https://${domainUrl}`;\n }\n\n return domainUrl;\n};\n\n/**\n * @ignore\n */\nexport const getTokenIssuer = (\n issuer: string | undefined,\n domainUrl: string\n) => {\n if (issuer) {\n return issuer.startsWith('https://') ? issuer : `https://${issuer}/`;\n }\n\n return `${domainUrl}/`;\n};\n\nexport const parseNumber = (value: any): number | undefined => {\n if (typeof value !== 'string') {\n return value;\n }\n return parseInt(value, 10) || undefined;\n};\n\n/**\n * Ponyfill for `Object.fromEntries()`, which is not available until ES2020.\n *\n * When the target of this project reaches ES2020, this can be removed.\n */\nexport const fromEntries = <T = any>(\n iterable: Iterable<[PropertyKey, T]>\n): Record<PropertyKey, T> => {\n return [...iterable].reduce((obj, [key, val]) => {\n obj[key] = val;\n\n return obj;\n }, {} as Record<PropertyKey, T>);\n};\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ProcessLocking = /** @class */ (function () {\n function ProcessLocking() {\n var _this = this;\n this.locked = new Map();\n this.addToLocked = function (key, toAdd) {\n var callbacks = _this.locked.get(key);\n if (callbacks === undefined) {\n if (toAdd === undefined) {\n _this.locked.set(key, []);\n }\n else {\n _this.locked.set(key, [toAdd]);\n }\n }\n else {\n if (toAdd !== undefined) {\n callbacks.unshift(toAdd);\n _this.locked.set(key, callbacks);\n }\n }\n };\n this.isLocked = function (key) {\n return _this.locked.has(key);\n };\n this.lock = function (key) {\n return new Promise(function (resolve, reject) {\n if (_this.isLocked(key)) {\n _this.addToLocked(key, resolve);\n }\n else {\n _this.addToLocked(key);\n resolve();\n }\n });\n };\n this.unlock = function (key) {\n var callbacks = _this.locked.get(key);\n if (callbacks === undefined || callbacks.length === 0) {\n _this.locked.delete(key);\n return;\n }\n var toCall = callbacks.pop();\n _this.locked.set(key, callbacks);\n if (toCall !== undefined) {\n setTimeout(toCall, 0);\n }\n };\n }\n ProcessLocking.getInstance = function () {\n if (ProcessLocking.instance === undefined) {\n ProcessLocking.instance = new ProcessLocking();\n }\n return ProcessLocking.instance;\n };\n return ProcessLocking;\n}());\nfunction getLock() {\n return ProcessLocking.getInstance();\n}\nexports.default = getLock;\n","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nvar _this = this;\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar processLock_1 = require(\"./processLock\");\n/**\n * @author: SuperTokens (https://github.com/supertokens)\n * This library was created as a part of a larger project, SuperTokens(https://supertokens.io) - the best session management solution.\n * You can also check out our other projects on https://github.com/supertokens\n *\n * To contribute to this package visit https://github.com/supertokens/browser-tabs-lock\n * If you face any problems you can file an issue on https://github.com/supertokens/browser-tabs-lock/issues\n *\n * If you have any questions or if you just want to say hi visit https://supertokens.io/discord\n */\n/**\n * @constant\n * @type {string}\n * @default\n * @description All the locks taken by this package will have this as prefix\n*/\nvar LOCK_STORAGE_KEY = 'browser-tabs-lock-key';\nvar DEFAULT_STORAGE_HANDLER = {\n key: function (index) { return __awaiter(_this, void 0, void 0, function () {\n return __generator(this, function (_a) {\n throw new Error(\"Unsupported\");\n });\n }); },\n getItem: function (key) { return __awaiter(_this, void 0, void 0, function () {\n return __generator(this, function (_a) {\n throw new Error(\"Unsupported\");\n });\n }); },\n clear: function () { return __awaiter(_this, void 0, void 0, function () {\n return __generator(this, function (_a) {\n return [2 /*return*/, window.localStorage.clear()];\n });\n }); },\n removeItem: function (key) { return __awaiter(_this, void 0, void 0, function () {\n return __generator(this, function (_a) {\n throw new Error(\"Unsupported\");\n });\n }); },\n setItem: function (key, value) { return __awaiter(_this, void 0, void 0, function () {\n return __generator(this, function (_a) {\n throw new Error(\"Unsupported\");\n });\n }); },\n keySync: function (index) {\n return window.localStorage.key(index);\n },\n getItemSync: function (key) {\n return window.localStorage.getItem(key);\n },\n clearSync: function () {\n return window.localStorage.clear();\n },\n removeItemSync: function (key) {\n return window.localStorage.removeItem(key);\n },\n setItemSync: function (key, value) {\n return window.localStorage.setItem(key, value);\n },\n};\n/**\n * @function delay\n * @param {number} milliseconds - How long the delay should be in terms of milliseconds\n * @returns {Promise<void>}\n */\nfunction delay(milliseconds) {\n return new Promise(function (resolve) { return setTimeout(resolve, milliseconds); });\n}\n/**\n * @function generateRandomString\n * @params {number} length - How long the random string should be\n * @returns {string}\n * @description returns random string whose length is equal to the length passed as parameter\n */\nfunction generateRandomString(length) {\n var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz';\n var randomstring = '';\n for (var i = 0; i < length; i++) {\n var INDEX = Math.floor(Math.random() * CHARS.length);\n randomstring += CHARS[INDEX];\n }\n return randomstring;\n}\n/**\n * @function getLockId\n * @returns {string}\n * @description Generates an id which will be unique for the browser tab\n */\nfunction getLockId() {\n return Date.now().toString() + generateRandomString(15);\n}\nvar SuperTokensLock = /** @class */ (function () {\n function SuperTokensLock(storageHandler) {\n this.acquiredIatSet = new Set();\n this.storageHandler = undefined;\n this.id = getLockId();\n this.acquireLock = this.acquireLock.bind(this);\n this.releaseLock = this.releaseLock.bind(this);\n this.releaseLock__private__ = this.releaseLock__private__.bind(this);\n this.waitForSomethingToChange = this.waitForSomethingToChange.bind(this);\n this.refreshLockWhileAcquired = this.refreshLockWhileAcquired.bind(this);\n this.storageHandler = storageHandler;\n if (SuperTokensLock.waiters === undefined) {\n SuperTokensLock.waiters = [];\n }\n }\n /**\n * @async\n * @memberOf Lock\n * @function acquireLock\n * @param {string} lockKey - Key for which the lock is being acquired\n * @param {number} [timeout=5000] - Maximum time for which the function will wait to acquire the lock\n * @returns {Promise<boolean>}\n * @description Will return true if lock is being acquired, else false.\n * Also the lock can be acquired for maximum 10 secs\n */\n SuperTokensLock.prototype.acquireLock = function (lockKey, timeout) {\n if (timeout === void 0) { timeout = 5000; }\n return __awaiter(this, void 0, void 0, function () {\n var iat, MAX_TIME, STORAGE_KEY, STORAGE, lockObj, TIMEOUT_KEY, lockObjPostDelay, parsedLockObjPostDelay;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n iat = Date.now() + generateRandomString(4);\n MAX_TIME = Date.now() + timeout;\n STORAGE_KEY = LOCK_STORAGE_KEY + \"-\" + lockKey;\n STORAGE = this.storageHandler === undefined ? DEFAULT_STORAGE_HANDLER : this.storageHandler;\n _a.label = 1;\n case 1:\n if (!(Date.now() < MAX_TIME)) return [3 /*break*/, 8];\n return [4 /*yield*/, delay(30)];\n case 2:\n _a.sent();\n lockObj = STORAGE.getItemSync(STORAGE_KEY);\n if (!(lockObj === null)) return [3 /*break*/, 5];\n TIMEOUT_KEY = this.id + \"-\" + lockKey + \"-\" + iat;\n // there is a problem if setItem happens at the exact same time for 2 different processes.. so we add some random delay here.\n return [4 /*yield*/, delay(Math.floor(Math.random() * 25))];\n case 3:\n // there is a problem if setItem happens at the exact same time for 2 different processes.. so we add some random delay here.\n _a.sent();\n STORAGE.setItemSync(STORAGE_KEY, JSON.stringify({\n id: this.id,\n iat: iat,\n timeoutKey: TIMEOUT_KEY,\n timeAcquired: Date.now(),\n timeRefreshed: Date.now()\n }));\n return [4 /*yield*/, delay(30)];\n case 4:\n _a.sent(); // this is to prevent race conditions. This time must be more than the time it takes for storage.setItem\n lockObjPostDelay = STORAGE.getItemSync(STORAGE_KEY);\n if (lockObjPostDelay !== null) {\n parsedLockObjPostDelay = JSON.parse(lockObjPostDelay);\n if (parsedLockObjPostDelay.id === this.id && parsedLockObjPostDelay.iat === iat) {\n this.acquiredIatSet.add(iat);\n this.refreshLockWhileAcquired(STORAGE_KEY, iat);\n return [2 /*return*/, true];\n }\n }\n return [3 /*break*/, 7];\n case 5:\n SuperTokensLock.lockCorrector(this.storageHandler === undefined ? DEFAULT_STORAGE_HANDLER : this.storageHandler);\n return [4 /*yield*/, this.waitForSomethingToChange(MAX_TIME)];\n case 6:\n _a.sent();\n _a.label = 7;\n case 7:\n iat = Date.now() + generateRandomString(4);\n return [3 /*break*/, 1];\n case 8: return [2 /*return*/, false];\n }\n });\n });\n };\n SuperTokensLock.prototype.refreshLockWhileAcquired = function (storageKey, iat) {\n return __awaiter(this, void 0, void 0, function () {\n var _this = this;\n return __generator(this, function (_a) {\n setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {\n var STORAGE, lockObj, parsedLockObj;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, processLock_1.default().lock(iat)];\n case 1:\n _a.sent();\n if (!this.acquiredIatSet.has(iat)) {\n processLock_1.default().unlock(iat);\n return [2 /*return*/];\n }\n STORAGE = this.storageHandler === undefined ? DEFAULT_STORAGE_HANDLER : this.storageHandler;\n lockObj = STORAGE.getItemSync(storageKey);\n if (lockObj !== null) {\n parsedLockObj = JSON.parse(lockObj);\n parsedLockObj.timeRefreshed = Date.now();\n STORAGE.setItemSync(storageKey, JSON.stringify(parsedLockObj));\n processLock_1.default().unlock(iat);\n }\n else {\n processLock_1.default().unlock(iat);\n return [2 /*return*/];\n }\n this.refreshLockWhileAcquired(storageKey, iat);\n return [2 /*return*/];\n }\n });\n }); }, 1000);\n return [2 /*return*/];\n });\n });\n };\n SuperTokensLock.prototype.waitForSomethingToChange = function (MAX_TIME) {\n return __awaiter(this, void 0, void 0, function () {\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, new Promise(function (resolve) {\n var resolvedCalled = false;\n var startedAt = Date.now();\n var MIN_TIME_TO_WAIT = 50; // ms\n var removedListeners = false;\n function stopWaiting() {\n if (!removedListeners) {\n window.removeEventListener('storage', stopWaiting);\n SuperTokensLock.removeFromWaiting(stopWaiting);\n clearTimeout(timeOutId);\n removedListeners = true;\n }\n if (!resolvedCalled) {\n resolvedCalled = true;\n var timeToWait = MIN_TIME_TO_WAIT - (Date.now() - startedAt);\n if (timeToWait > 0) {\n setTimeout(resolve, timeToWait);\n }\n else {\n resolve(null);\n }\n }\n }\n window.addEventListener('storage', stopWaiting);\n SuperTokensLock.addToWaiting(stopWaiting);\n var timeOutId = setTimeout(stopWaiting, Math.max(0, MAX_TIME - Date.now()));\n })];\n case 1:\n _a.sent();\n return [2 /*return*/];\n }\n });\n });\n };\n SuperTokensLock.addToWaiting = function (func) {\n this.removeFromWaiting(func);\n if (SuperTokensLock.waiters === undefined) {\n return;\n }\n SuperTokensLock.waiters.push(func);\n };\n SuperTokensLock.removeFromWaiting = function (func) {\n if (SuperTokensLock.waiters === undefined) {\n return;\n }\n SuperTokensLock.waiters = SuperTokensLock.waiters.filter(function (i) { return i !== func; });\n };\n SuperTokensLock.notifyWaiters = function () {\n if (SuperTokensLock.waiters === undefined) {\n return;\n }\n var waiters = SuperTokensLock.waiters.slice(); // so that if Lock.waiters is changed it's ok.\n waiters.forEach(function (i) { return i(); });\n };\n /**\n * @function releaseLock\n * @memberOf Lock\n * @param {string} lockKey - Key for which lock is being released\n * @returns {void}\n * @description Release a lock.\n */\n SuperTokensLock.prototype.releaseLock = function (lockKey) {\n return __awaiter(this, void 0, void 0, function () {\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, this.releaseLock__private__(lockKey)];\n case 1: return [2 /*return*/, _a.sent()];\n }\n });\n });\n };\n /**\n * @function releaseLock\n * @memberOf Lock\n * @param {string} lockKey - Key for which lock is being released\n * @returns {void}\n * @description Release a lock.\n */\n SuperTokensLock.prototype.releaseLock__private__ = function (lockKey) {\n return __awaiter(this, void 0, void 0, function () {\n var STORAGE, STORAGE_KEY, lockObj, parsedlockObj;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n STORAGE = this.storageHandler === undefined ? DEFAULT_STORAGE_HANDLER : this.storageHandler;\n STORAGE_KEY = LOCK_STORAGE_KEY + \"-\" + lockKey;\n lockObj = STORAGE.getItemSync(STORAGE_KEY);\n if (lockObj === null) {\n return [2 /*return*/];\n }\n parsedlockObj = JSON.parse(lockObj);\n if (!(parsedlockObj.id === this.id)) return [3 /*break*/, 2];\n return [4 /*yield*/, processLock_1.default().lock(parsedlockObj.iat)];\n case 1:\n _a.sent();\n this.acquiredIatSet.delete(parsedlockObj.iat);\n STORAGE.removeItemSync(STORAGE_KEY);\n processLock_1.default().unlock(parsedlockObj.iat);\n SuperTokensLock.notifyWaiters();\n _a.label = 2;\n case 2: return [2 /*return*/];\n }\n });\n });\n };\n /**\n * @function lockCorrector\n * @returns {void}\n * @description If a lock is acquired by a tab and the tab is closed before the lock is\n * released, this function will release those locks\n */\n SuperTokensLock.lockCorrector = function (storageHandler) {\n var MIN_ALLOWED_TIME = Date.now() - 5000;\n var STORAGE = storageHandler;\n var KEYS = [];\n var currIndex = 0;\n while (true) {\n var key = STORAGE.keySync(currIndex);\n if (key === null) {\n break;\n }\n KEYS.push(key);\n currIndex++;\n }\n var notifyWaiters = false;\n for (var i = 0; i < KEYS.length; i++) {\n var LOCK_KEY = KEYS[i];\n if (LOCK_KEY.includes(LOCK_STORAGE_KEY)) {\n var lockObj = STORAGE.getItemSync(LOCK_KEY);\n if (lockObj !== null) {\n var parsedlockObj = JSON.parse(lockObj);\n if ((parsedlockObj.timeRefreshed === undefined && parsedlockObj.timeAcquired < MIN_ALLOWED_TIME) ||\n (parsedlockObj.timeRefreshed !== undefined && parsedlockObj.timeRefreshed < MIN_ALLOWED_TIME)) {\n STORAGE.removeItemSync(LOCK_KEY);\n notifyWaiters = true;\n }\n }\n }\n }\n if (notifyWaiters) {\n SuperTokensLock.notifyWaiters();\n }\n };\n SuperTokensLock.waiters = undefined;\n return SuperTokensLock;\n}());\nexports.default = SuperTokensLock;\n","import BrowserTabsLock from 'browser-tabs-lock';\nimport { TimeoutError } from './errors';\n\n/**\n * Lock manager abstraction for cross-tab synchronization.\n * Supports both modern Web Locks API and legacy localStorage-based locking.\n */\n\n/** Lock manager interface - callback pattern ensures automatic lock release */\nexport interface ILockManager {\n /**\n * Run callback while holding a lock.\n * Lock is automatically released when callback completes or throws.\n *\n * @param key - Lock identifier\n * @param timeout - Maximum time to wait for lock acquisition (ms)\n * @param callback - Function to execute while holding the lock\n * @returns Promise resolving to callback's return value\n * @throws Error if lock cannot be acquired within timeout\n */\n runWithLock<T>(\n key: string,\n timeout: number,\n callback: () => Promise<T>\n ): Promise<T>;\n}\n\n/** Web Locks API implementation - true mutex with OS-level queuing */\nexport class WebLocksApiManager implements ILockManager {\n async runWithLock<T>(\n key: string,\n timeout: number,\n callback: () => Promise<T>\n ): Promise<T> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n try {\n return await navigator.locks.request(\n key,\n { mode: 'exclusive', signal: controller.signal },\n async lock => {\n clearTimeout(timeoutId);\n if (!lock) throw new Error('Lock not available');\n return await callback();\n }\n );\n } catch (error: any) {\n clearTimeout(timeoutId);\n if (error?.name === 'AbortError') throw new TimeoutError();\n throw error;\n }\n }\n}\n\n/** Legacy localStorage-based locking with retry logic for older browsers */\nexport class LegacyLockManager implements ILockManager {\n private lock: BrowserTabsLock;\n private activeLocks: Set<string> = new Set();\n private pagehideHandler: () => void;\n\n constructor() {\n this.lock = new BrowserTabsLock();\n\n this.pagehideHandler = () => {\n this.activeLocks.forEach(key => this.lock.releaseLock(key));\n this.activeLocks.clear();\n };\n }\n\n async runWithLock<T>(\n key: string,\n timeout: number,\n callback: () => Promise<T>\n ): Promise<T> {\n // Retry logic to handle race conditions in localStorage-based locking\n const retryAttempts = 10;\n let acquired = false;\n\n for (let i = 0; i < retryAttempts && !acquired; i++) {\n acquired = await this.lock.acquireLock(key, timeout);\n }\n\n if (!acquired) {\n throw new TimeoutError();\n }\n\n this.activeLocks.add(key);\n\n // Add pagehide listener when acquiring first lock\n if (this.activeLocks.size === 1 && typeof window !== 'undefined') {\n window.addEventListener('pagehide', this.pagehideHandler);\n }\n\n try {\n return await callback();\n } finally {\n this.activeLocks.delete(key);\n await this.lock.releaseLock(key);\n\n // Remove pagehide listener when all locks are released\n if (this.activeLocks.size === 0 && typeof window !== 'undefined') {\n window.removeEventListener('pagehide', this.pagehideHandler);\n }\n }\n }\n}\n\n/**\n * Feature detection for Web Locks API support\n */\nfunction isWebLocksSupported(): boolean {\n return (\n typeof navigator !== 'undefined' &&\n typeof navigator.locks?.request === 'function'\n );\n}\n\nfunction createLockManager(): ILockManager {\n return isWebLocksSupported()\n ? new WebLocksApiManager()\n : new LegacyLockManager();\n}\n\n/**\n * Get the singleton lock manager instance.\n * Uses Web Locks API in modern browsers, falls back to localStorage in older browsers.\n */\nlet lockManager: ILockManager | null = null;\n\nexport function getLockManager(): ILockManager {\n if (!lockManager) {\n lockManager = createLockManager();\n }\n return lockManager;\n}\n\n// For testing: allow resetting the singleton\nexport function resetLockManager(): void {\n lockManager = null;\n}\n",null,"import * as dpopLib from 'dpop';\n\nexport const DPOP_NONCE_HEADER = 'dpop-nonce';\n\nconst KEY_PAIR_ALGORITHM: dpopLib.JWSAlgorithm = 'ES256';\n\nconst SUPPORTED_GRANT_TYPES = [\n 'authorization_code',\n 'refresh_token',\n 'urn:ietf:params:oauth:grant-type:token-exchange',\n 'http://auth0.com/oauth/grant-type/mfa-oob',\n 'http://auth0.com/oauth/grant-type/mfa-otp',\n 'http://auth0.com/oauth/grant-type/mfa-recovery-code'\n];\n\nexport type KeyPair = Readonly<dpopLib.KeyPair>;\n\ntype GenerateProofParams = {\n keyPair: KeyPair;\n url: string;\n method: string;\n nonce?: string;\n accessToken?: string;\n};\n\nexport function generateKeyPair(): Promise<KeyPair> {\n return dpopLib.generateKeyPair(KEY_PAIR_ALGORITHM, { extractable: false });\n}\n\nexport function calculateThumbprint(\n keyPair: Pick<KeyPair, 'publicKey'>\n): Promise<string> {\n return dpopLib.calculateThumbprint(keyPair.publicKey);\n}\n\nfunction normalizeUrl(url: string): string {\n const parsedUrl = new URL(url);\n\n /**\n * \"The HTTP target URI (...) without query and fragment parts\"\n * @see {@link https://www.rfc-editor.org/rfc/rfc9449.html#section-4.2-4.6}\n */\n parsedUrl.search = '';\n parsedUrl.hash = '';\n\n return parsedUrl.href;\n}\n\nexport function generateProof({\n keyPair,\n url,\n method,\n nonce,\n accessToken\n}: GenerateProofParams): Promise<string> {\n const normalizedUrl = normalizeUrl(url);\n\n return dpopLib.generateProof(\n keyPair,\n normalizedUrl,\n method,\n nonce,\n accessToken\n );\n}\n\nexport function isGrantTypeSupported(grantType: string): boolean {\n return SUPPORTED_GRANT_TYPES.includes(grantType);\n}\n","import { WorkerRefreshTokenMessage } from './worker.types';\n\n/**\n * Sends the specified message to the web worker\n * @param message The message to send\n * @param to The worker to send the message to\n */\nexport const sendMessage = (message: WorkerRefreshTokenMessage, to: Worker) =>\n new Promise(function (resolve, reject) {\n const messageChannel = new MessageChannel();\n\n messageChannel.port1.onmessage = function (event) {\n // Only for fetch errors, as these get retried\n if (event.data.error) {\n reject(new Error(event.data.error));\n } else {\n resolve(event.data);\n }\n messageChannel.port1.close();\n };\n\n to.postMessage(message, [messageChannel.port2]);\n });\n","import {\n DEFAULT_FETCH_TIMEOUT_MS,\n DEFAULT_SILENT_TOKEN_RETRY_COUNT\n} from './constants';\n\nimport { fromEntries } from './utils';\nimport { sendMessage } from './worker/worker.utils';\nimport { FetchOptions, FetchResponse } from './global';\nimport {\n GenericError,\n MfaRequiredError,\n MissingRefreshTokenError,\n UseDpopNonceError\n} from './errors';\nimport { Dpop } from './dpop/dpop';\nimport { DPOP_NONCE_HEADER } from './dpop/utils';\n\nexport const createAbortController = () => new AbortController();\n\nconst dofetch = async (fetchUrl: string, fetchOptions: FetchOptions) => {\n const response = await fetch(fetchUrl, fetchOptions);\n\n return {\n ok: response.ok,\n json: await response.json(),\n\n /**\n * This is not needed, but do it anyway so the object shape is the\n * same as when using a Web Worker (which *does* need this, see\n * src/worker/token.worker.ts).\n */\n headers: fromEntries(response.headers)\n };\n};\n\nconst fetchWithoutWorker = async (\n fetchUrl: string,\n fetchOptions: FetchOptions,\n timeout: number\n) => {\n const controller = createAbortController();\n fetchOptions.signal = controller.signal;\n\n let timeoutId: NodeJS.Timeout;\n\n // The promise will resolve with one of these two promises (the fetch or the timeout), whichever completes first.\n return Promise.race([\n dofetch(fetchUrl, fetchOptions),\n\n new Promise((_, reject) => {\n timeoutId = setTimeout(() => {\n controller.abort();\n reject(new Error(\"Timeout when executing 'fetch'\"));\n }, timeout);\n })\n ]).finally(() => {\n clearTimeout(timeoutId);\n });\n};\n\nconst fetchWithWorker = async (\n fetchUrl: string,\n audience: string,\n scope: string,\n fetchOptions: FetchOptions,\n timeout: number,\n worker: Worker,\n useFormData?: boolean,\n useMrrt?: boolean\n) => {\n return sendMessage(\n {\n auth: {\n audience,\n scope\n },\n timeout,\n fetchUrl,\n fetchOptions,\n useFormData,\n useMrrt\n },\n worker\n );\n};\n\nexport const switchFetch = async (\n fetchUrl: string,\n audience: string,\n scope: string,\n fetchOptions: FetchOptions,\n worker?: Worker,\n useFormData?: boolean,\n timeout = DEFAULT_FETCH_TIMEOUT_MS,\n useMrrt?: boolean,\n): Promise<any> => {\n if (worker) {\n return fetchWithWorker(\n fetchUrl,\n audience,\n scope,\n fetchOptions,\n timeout,\n worker,\n useFormData,\n useMrrt\n );\n } else {\n return fetchWithoutWorker(fetchUrl, fetchOptions, timeout);\n }\n};\n\nexport async function getJSON<T>(\n url: string,\n timeout: number | undefined,\n audience: string,\n scope: string,\n options: FetchOptions,\n worker?: Worker,\n useFormData?: boolean,\n useMrrt?: boolean,\n dpop?: Pick<Dpop, 'generateProof' | 'getNonce' | 'setNonce'>,\n isDpopRetry?: boolean\n): Promise<T> {\n if (dpop) {\n const dpopProof = await dpop.generateProof({\n url,\n method: options.method || 'GET',\n nonce: await dpop.getNonce()\n });\n\n options.headers = { ...options.headers, dpop: dpopProof };\n }\n\n let fetchError: null | Error = null;\n let response!: FetchResponse;\n\n for (let i = 0; i < DEFAULT_SILENT_TOKEN_RETRY_COUNT; i++) {\n try {\n response = await switchFetch(\n url,\n audience,\n scope,\n options,\n worker,\n useFormData,\n timeout,\n useMrrt,\n );\n fetchError = null;\n break;\n } catch (e) {\n // Fetch only fails in the case of a network issue, so should be\n // retried here. Failure status (4xx, 5xx, etc) return a resolved Promise\n // with the failure in the body.\n // https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API\n fetchError = e;\n }\n }\n\n if (fetchError) {\n throw fetchError;\n }\n\n const {\n json: { error, error_description, ...data },\n headers,\n ok\n } = response;\n\n let newDpopNonce: string | undefined;\n\n if (dpop) {\n /**\n * Note that a new DPoP nonce can appear in both error and success responses!\n *\n * @see {@link https://www.rfc-editor.org/rfc/rfc9449.html#section-8.2-3}\n */\n newDpopNonce = headers[DPOP_NONCE_HEADER];\n\n if (newDpopNonce) {\n await dpop.setNonce(newDpopNonce);\n }\n }\n\n if (!ok) {\n const errorMessage =\n error_description || `HTTP error. Unable to fetch ${url}`;\n\n if (error === 'mfa_required') {\n throw new MfaRequiredError(error, errorMessage, data.mfa_token, data.mfa_requirements);\n }\n\n if (error === 'missing_refresh_token') {\n throw new MissingRefreshTokenError(audience, scope);\n }\n\n /**\n * When DPoP is used and we get a `use_dpop_nonce` error from the server,\n * we must retry ONCE with any new nonce received in the rejected request.\n *\n * If a new nonce was not received or the retry fails again, we give up and\n * throw the error as is.\n */\n if (error === 'use_dpop_nonce') {\n if (!dpop || !newDpopNonce || isDpopRetry) {\n throw new UseDpopNonceError(newDpopNonce);\n }\n\n // repeat the call but with isDpopRetry=true to avoid any more retries\n return getJSON(\n url,\n timeout,\n audience,\n scope,\n options,\n worker,\n useFormData,\n useMrrt,\n dpop,\n true // !\n );\n }\n\n throw new GenericError(error || 'request_error', errorMessage);\n }\n\n return data;\n}\n","import { TokenEndpointOptions, TokenEndpointResponse } from './global';\nimport { DEFAULT_AUTH0_CLIENT, DEFAULT_AUDIENCE } from './constants';\nimport * as dpopUtils from './dpop/utils';\nimport { getJSON } from './http';\nimport { createQueryParams, stripAuth0Client } from './utils';\n\nexport async function oauthToken(\n {\n baseUrl,\n timeout,\n audience,\n scope,\n auth0Client,\n useFormData,\n useMrrt,\n dpop,\n ...options\n }: TokenEndpointOptions,\n worker?: Worker\n) {\n const isTokenExchange =\n options.grant_type === 'urn:ietf:params:oauth:grant-type:token-exchange';\n\n const refreshWithMrrt = options.grant_type === 'refresh_token' && useMrrt;\n\n const allParams = {\n ...options,\n ...(isTokenExchange && audience && { audience }),\n ...(isTokenExchange && scope && { scope }),\n ...(refreshWithMrrt && { audience, scope })\n };\n\n const body = useFormData\n ? createQueryParams(allParams)\n : JSON.stringify(allParams);\n\n const isDpopSupported = dpopUtils.isGrantTypeSupported(options.grant_type);\n\n return await getJSON<TokenEndpointResponse>(\n `${baseUrl}/oauth/token`,\n timeout,\n audience || DEFAULT_AUDIENCE,\n scope,\n {\n method: 'POST',\n body,\n headers: {\n 'Content-Type': useFormData\n ? 'application/x-www-form-urlencoded'\n : 'application/json',\n 'Auth0-Client': btoa(\n JSON.stringify(stripAuth0Client(auth0Client || DEFAULT_AUTH0_CLIENT))\n )\n }\n },\n worker,\n useFormData,\n useMrrt,\n isDpopSupported ? dpop : undefined\n );\n}\n","import { DEFAULT_AUDIENCE } from \"./constants\";\n\n/**\n * @ignore\n */\nconst dedupe = (arr: string[]) => Array.from(new Set(arr));\n\n/**\n * @ignore\n */\n/**\n * Returns a string of unique scopes by removing duplicates and unnecessary whitespace.\n *\n * @param {...(string | undefined)[]} scopes - A list of scope strings or undefined values.\n * @returns {string} A string containing unique scopes separated by a single space.\n */\nexport const getUniqueScopes = (...scopes: (string | undefined)[]) => {\n return dedupe(scopes.filter(Boolean).join(' ').trim().split(/\\s+/)).join(' ');\n};\n\n/**\n * @ignore\n */\n/**\n * We will check if the developer has created the client with a string or object of audience:scopes. We will inject\n * the base scopes to each audience, and store the base ones inside default key. As well, if the developer created the Auth0Client\n * with a string of scopes, we will store the requested ones with the base scopes inside the default key as well.\n * @param authScopes The scopes requested by the user when creating the Auth0Client\n * @param openIdScope openId scope\n * @param extraScopes Other scopes to accumulate such as offline_access\n * @returns {Record<string, string>} An object with all scopes that are going to be accumulated.\n */\nexport const injectDefaultScopes = (authScopes: string | Record<string, string> | undefined, openIdScope: string, ...extraScopes: string[]): Record<string, string> => {\n if (typeof authScopes !== 'object') {\n return { [DEFAULT_AUDIENCE]: getUniqueScopes(openIdScope, authScopes, ...extraScopes) };\n }\n\n let requestedScopes: Record<string, string> = {\n [DEFAULT_AUDIENCE]: getUniqueScopes(openIdScope, ...extraScopes),\n };\n\n Object.keys(authScopes).forEach((key) => {\n const audienceScopes = authScopes[key];\n\n requestedScopes[key] = getUniqueScopes(openIdScope, audienceScopes, ...extraScopes);\n });\n\n return requestedScopes;\n}\n\n/**\n * @ignore\n */\n/**\n * Will return a string of scopes. If a specific audience was requested and it exist inside the scopes object, we will return those\n * related to that audience that we want to accumulate. If not, we will return the ones stored inside the default key.\n * @param authScopes Object of audience:scopes that are going to be accumulated\n * @param methodScopes The scopes requested for the developer in a specific request\n * @param audience The audience the developer requested for an specific request or the one they configured in the Auth0Client\n * @returns {string} A combination of Auth0Client scopes and the ones requested by the developer for a specific request\n */\nexport const scopesToRequest = (authScopes: Record<string, string>, methodScopes: string | undefined, audience: string | undefined): string => {\n let scope: string | undefined;\n\n if (audience) {\n scope = authScopes[audience];\n }\n\n if (!scope) {\n scope = authScopes[DEFAULT_AUDIENCE];\n }\n\n return getUniqueScopes(scope, methodScopes);\n}","import { IdToken, User } from '../global';\n\nexport const CACHE_KEY_PREFIX = '@@auth0spajs@@';\nexport const CACHE_KEY_ID_TOKEN_SUFFIX = '@@user@@';\n\nexport type CacheKeyData = {\n audience?: string;\n scope?: string;\n clientId: string;\n};\n\nexport class CacheKey {\n public clientId: string;\n public scope?: string;\n public audience?: string;\n\n constructor(\n data: CacheKeyData,\n public prefix: string = CACHE_KEY_PREFIX,\n public suffix?: string\n ) {\n this.clientId = data.clientId;\n this.scope = data.scope;\n this.audience = data.audience;\n }\n\n /**\n * Converts this `CacheKey` instance into a string for use in a cache\n * @returns A string representation of the key\n */\n toKey(): string {\n return [this.prefix, this.clientId, this.audience, this.scope, this.suffix]\n .filter(Boolean)\n .join('::');\n }\n\n /**\n * Converts a cache key string into a `CacheKey` instance.\n * @param key The key to convert\n * @returns An instance of `CacheKey`\n */\n static fromKey(key: string): CacheKey {\n const [prefix, clientId, audience, scope] = key.split('::');\n\n return new CacheKey({ clientId, scope, audience }, prefix);\n }\n\n /**\n * Utility function to build a `CacheKey` instance from a cache entry\n * @param entry The entry\n * @returns An instance of `CacheKey`\n */\n static fromCacheEntry(entry: CacheEntry): CacheKey {\n const { scope, audience, client_id: clientId } = entry;\n\n return new CacheKey({\n scope,\n audience,\n clientId\n });\n }\n}\n\nexport interface DecodedToken {\n claims: IdToken;\n user: User;\n}\n\nexport interface IdTokenEntry {\n id_token: string;\n decodedToken: DecodedToken;\n}\n\nexport type CacheEntry = {\n id_token?: string;\n token_type?: string;\n access_token: string;\n expires_in: number;\n decodedToken?: DecodedToken;\n audience: string;\n scope: string;\n client_id: string;\n refresh_token?: string;\n oauthTokenScope?: string;\n};\n\nexport type WrappedCacheEntry = {\n body: Partial<CacheEntry>;\n expiresAt: number;\n};\n\nexport type KeyManifestEntry = {\n keys: string[];\n};\n\nexport type Cacheable = WrappedCacheEntry | KeyManifestEntry;\n\nexport type MaybePromise<T> = Promise<T> | T;\n\nexport interface ICache {\n set<T = Cacheable>(key: string, entry: T): MaybePromise<void>;\n get<T = Cacheable>(key: string): MaybePromise<T | undefined>;\n remove(key: string): MaybePromise<void>;\n allKeys?(): MaybePromise<string[]>;\n}\n","import { ICache, Cacheable, CACHE_KEY_PREFIX, MaybePromise } from './shared';\n\nexport class LocalStorageCache implements ICache {\n public set<T = Cacheable>(key: string, entry: T) {\n localStorage.setItem(key, JSON.stringify(entry));\n }\n\n public get<T = Cacheable>(key: string): MaybePromise<T | undefined> {\n const json = window.localStorage.getItem(key);\n\n if (!json) return;\n\n try {\n const payload = JSON.parse(json) as T;\n return payload;\n /* c8 ignore next 3 */\n } catch (e) {\n return;\n }\n }\n\n public remove(key: string) {\n localStorage.removeItem(key);\n }\n\n public allKeys() {\n return Object.keys(window.localStorage).filter(key =>\n key.startsWith(CACHE_KEY_PREFIX)\n );\n }\n}\n","import { Cacheable, ICache, MaybePromise } from './shared';\n\nexport class InMemoryCache {\n public enclosedCache: ICache = (function () {\n let cache: Record<string, unknown> = {};\n\n return {\n set<T = Cacheable>(key: string, entry: T) {\n cache[key] = entry;\n },\n\n get<T = Cacheable>(key: string): MaybePromise<T | undefined> {\n const cacheEntry = cache[key] as T;\n\n if (!cacheEntry) {\n return;\n }\n\n return cacheEntry;\n },\n\n remove(key: string) {\n delete cache[key];\n },\n\n allKeys(): string[] {\n return Object.keys(cache);\n }\n };\n })();\n}\n","import { DEFAULT_NOW_PROVIDER } from '../constants';\nimport { CacheKeyManifest } from './key-manifest';\n\nimport {\n CacheEntry,\n ICache,\n CacheKey,\n CACHE_KEY_PREFIX,\n WrappedCacheEntry,\n DecodedToken,\n CACHE_KEY_ID_TOKEN_SUFFIX,\n IdTokenEntry\n} from './shared';\n\nconst DEFAULT_EXPIRY_ADJUSTMENT_SECONDS = 0;\n\nexport class CacheManager {\n private nowProvider: () => number | Promise<number>;\n\n constructor(\n private cache: ICache,\n private keyManifest?: CacheKeyManifest,\n nowProvider?: () => number | Promise<number>\n ) {\n this.nowProvider = nowProvider || DEFAULT_NOW_PROVIDER;\n }\n\n async setIdToken(\n clientId: string,\n idToken: string,\n decodedToken: DecodedToken\n ): Promise<void> {\n const cacheKey = this.getIdTokenCacheKey(clientId);\n await this.cache.set(cacheKey, {\n id_token: idToken,\n decodedToken\n });\n await this.keyManifest?.add(cacheKey);\n }\n\n async getIdToken(cacheKey: CacheKey): Promise<IdTokenEntry | undefined> {\n const entry = await this.cache.get<IdTokenEntry>(\n this.getIdTokenCacheKey(cacheKey.clientId)\n );\n\n if (!entry && cacheKey.scope && cacheKey.audience) {\n const entryByScope = await this.get(cacheKey);\n\n if (!entryByScope) {\n return;\n }\n\n if (!entryByScope.id_token || !entryByScope.decodedToken) {\n return;\n }\n\n return {\n id_token: entryByScope.id_token,\n decodedToken: entryByScope.decodedToken\n };\n }\n\n if (!entry) {\n return;\n }\n\n return { id_token: entry.id_token, decodedToken: entry.decodedToken };\n }\n\n async get(\n cacheKey: CacheKey,\n expiryAdjustmentSeconds = DEFAULT_EXPIRY_ADJUSTMENT_SECONDS,\n useMrrt = false,\n cacheMode?: string\n ): Promise<Partial<CacheEntry> | undefined> {\n let wrappedEntry = await this.cache.get<WrappedCacheEntry>(\n cacheKey.toKey()\n );\n\n if (!wrappedEntry) {\n const keys = await this.getCacheKeys();\n\n if (!keys) return;\n\n const matchedKey = this.matchExistingCacheKey(cacheKey, keys);\n\n if (matchedKey) {\n wrappedEntry = await this.cache.get<WrappedCacheEntry>(matchedKey);\n }\n\n // To refresh using MRRT we need to send a request to the server\n // If cacheMode is 'cache-only', this will make us unable to call the server\n // so it won't be needed to find a valid refresh token\n if (!wrappedEntry && useMrrt && cacheMode !== 'cache-only') {\n return this.getEntryWithRefreshToken(cacheKey, keys);\n }\n }\n\n // If we still don't have an entry, exit.\n if (!wrappedEntry) {\n return;\n }\n\n const now = await this.nowProvider();\n const nowSeconds = Math.floor(now / 1000);\n\n if (wrappedEntry.expiresAt - expiryAdjustmentSeconds < nowSeconds) {\n if (wrappedEntry.body.refresh_token) {\n return this.modifiedCachedEntry(wrappedEntry, cacheKey);\n }\n\n await this.cache.remove(cacheKey.toKey());\n await this.keyManifest?.remove(cacheKey.toKey());\n\n return;\n }\n\n return wrappedEntry.body;\n }\n\n private async modifiedCachedEntry(wrappedEntry: WrappedCacheEntry, cacheKey: CacheKey): Promise<Partial<CacheEntry>> {\n // We need to keep audience and scope in order to check them later when doing refresh\n // using MRRT. See getScopeToRequest method.\n wrappedEntry.body = {\n refresh_token: wrappedEntry.body.refresh_token,\n audience: wrappedEntry.body.audience,\n scope: wrappedEntry.body.scope,\n };\n\n await this.cache.set(cacheKey.toKey(), wrappedEntry);\n\n return {\n refresh_token: wrappedEntry.body.refresh_token,\n audience: wrappedEntry.body.audience,\n scope: wrappedEntry.body.scope,\n };\n }\n\n async set(entry: CacheEntry): Promise<void> {\n const cacheKey = new CacheKey({\n clientId: entry.client_id,\n scope: entry.scope,\n audience: entry.audience\n });\n\n const wrappedEntry = await this.wrapCacheEntry(entry);\n\n await this.cache.set(cacheKey.toKey(), wrappedEntry);\n await this.keyManifest?.add(cacheKey.toKey());\n }\n\n async remove(\n client_id: string,\n audience?: string,\n scope?: string,\n ): Promise<void> {\n const cacheKey = new CacheKey({\n clientId: client_id,\n scope: scope,\n audience: audience\n });\n\n await this.cache.remove(cacheKey.toKey());\n }\n\n async clear(clientId?: string): Promise<void> {\n const keys = await this.getCacheKeys();\n\n /* c8 ignore next */\n if (!keys) return;\n\n await keys\n .filter(key => (clientId ? key.includes(clientId) : true))\n .reduce(async (memo, key) => {\n await memo;\n await this.cache.remove(key);\n }, Promise.resolve());\n\n await this.keyManifest?.clear();\n }\n\n private async wrapCacheEntry(entry: CacheEntry): Promise<WrappedCacheEntry> {\n const now = await this.nowProvider();\n const expiresInTime = Math.floor(now / 1000) + entry.expires_in;\n\n return {\n body: entry,\n expiresAt: expiresInTime\n };\n }\n\n private async getCacheKeys(): Promise<string[] | undefined> {\n if (this.keyManifest) {\n return (await this.keyManifest.get())?.keys;\n } else if (this.cache.allKeys) {\n return this.cache.allKeys();\n }\n }\n\n /**\n * Returns the cache key to be used to store the id token\n * @param clientId The client id used to link to the id token\n * @returns The constructed cache key, as a string, to store the id token\n */\n private getIdTokenCacheKey(clientId: string) {\n return new CacheKey(\n { clientId },\n CACHE_KEY_PREFIX,\n CACHE_KEY_ID_TOKEN_SUFFIX\n ).toKey();\n }\n\n /**\n * Finds the corresponding key in the cache based on the provided cache key.\n * The keys inside the cache are in the format {prefix}::{clientId}::{audience}::{scope}.\n * The first key in the cache that satisfies the following conditions is returned\n * - `prefix` is strict equal to Auth0's internally configured `keyPrefix`\n * - `clientId` is strict equal to the `cacheKey.clientId`\n * - `audience` is strict equal to the `cacheKey.audience`\n * - `scope` contains at least all the `cacheKey.scope` values\n * *\n * @param keyToMatch The provided cache key\n * @param allKeys A list of existing cache keys\n */\n private matchExistingCacheKey(keyToMatch: CacheKey, allKeys: Array<string>) {\n return allKeys.filter(key => {\n const cacheKey = CacheKey.fromKey(key);\n const scopeSet = new Set(cacheKey.scope && cacheKey.scope.split(' '));\n const scopesToMatch = keyToMatch.scope?.split(' ') || [];\n\n const hasAllScopes =\n cacheKey.scope &&\n scopesToMatch.reduce(\n (acc, current) => acc && scopeSet.has(current),\n true\n );\n\n return (\n cacheKey.prefix === CACHE_KEY_PREFIX &&\n cacheKey.clientId === keyToMatch.clientId &&\n cacheKey.audience === keyToMatch.audience &&\n hasAllScopes\n );\n })[0];\n }\n\n /**\n * Returns the first entry that contains a refresh_token that satisfies the following conditions\n * The keys inside the cache are in the format {prefix}::{clientId}::{audience}::{scope}.\n * - `prefix` is strict equal to Auth0's internally configured `keyPrefix`\n * - `clientId` is strict equal to the `cacheKey.clientId`\n * @param keyToMatch The provided cache key\n * @param allKeys A list of existing cache keys\n */\n private async getEntryWithRefreshToken(keyToMatch: CacheKey, allKeys: Array<string>): Promise<Partial<CacheEntry> | undefined> {\n for (const key of allKeys) {\n const cacheKey = CacheKey.fromKey(key);\n\n if (cacheKey.prefix === CACHE_KEY_PREFIX &&\n cacheKey.clientId === keyToMatch.clientId) {\n const cachedEntry = await this.cache.get<WrappedCacheEntry>(key);\n\n if (cachedEntry?.body?.refresh_token) {\n return this.modifiedCachedEntry(cachedEntry, keyToMatch);\n }\n }\n }\n\n return undefined;\n }\n\n /**\n * Updates the refresh token in all cache entries that contain the old refresh token.\n *\n * When a refresh token is rotated, multiple cache entries (for different audiences/scopes)\n * may share the same refresh token. This method propagates the new refresh token to all\n * matching entries.\n *\n * @param oldRefreshToken The refresh token that was used and is now invalid\n * @param newRefreshToken The new refresh token received from the server\n */\n async updateEntry(\n oldRefreshToken: string,\n newRefreshToken: string,\n ): Promise<void> {\n const allKeys = await this.getCacheKeys();\n\n if (!allKeys) return;\n\n for (const key of allKeys) {\n const entry = await this.cache.get<WrappedCacheEntry>(key);\n\n if (entry?.body?.refresh_token === oldRefreshToken) {\n entry.body.refresh_token = newRefreshToken;\n await this.cache.set(key, entry);\n }\n }\n }\n}\n","import { ClientStorage } from './storage';\n\nconst TRANSACTION_STORAGE_KEY_PREFIX = 'a0.spajs.txs';\n\nexport interface LoginTransaction {\n nonce: string;\n scope: string;\n audience: string;\n appState?: any;\n code_verifier: string;\n redirect_uri?: string;\n organization?: string;\n state?: string;\n response_type: 'code';\n}\n\nexport interface ConnectAccountTransaction {\n appState?: any;\n audience?: string;\n auth_session: string;\n code_verifier: string;\n redirect_uri: string;\n scope?: string;\n state: string;\n connection: string;\n response_type: 'connect_code';\n}\n\nexport class TransactionManager {\n private storageKey: string;\n\n constructor(\n private storage: ClientStorage,\n private clientId: string,\n private cookieDomain?: string\n ) {\n this.storageKey = `${TRANSACTION_STORAGE_KEY_PREFIX}.${this.clientId}`;\n }\n\n public create<T extends Object = LoginTransaction>(transaction: T) {\n this.storage.save(this.storageKey, transaction, {\n daysUntilExpire: 1,\n cookieDomain: this.cookieDomain\n });\n }\n\n public get<T extends Object = LoginTransaction>(): T | undefined {\n return this.storage.get(this.storageKey);\n }\n\n public remove() {\n this.storage.remove(this.storageKey, {\n cookieDomain: this.cookieDomain\n });\n }\n}","import { urlDecodeB64 } from './utils';\nimport { IdToken, JWTVerifyOptions } from './global';\n\nconst isNumber = (n: any) => typeof n === 'number';\n\nconst idTokendecoded = [\n 'iss',\n 'aud',\n 'exp',\n 'nbf',\n 'iat',\n 'jti',\n 'azp',\n 'nonce',\n 'auth_time',\n 'at_hash',\n 'c_hash',\n 'acr',\n 'amr',\n 'sub_jwk',\n 'cnf',\n 'sip_from_tag',\n 'sip_date',\n 'sip_callid',\n 'sip_cseq_num',\n 'sip_via_branch',\n 'orig',\n 'dest',\n 'mky',\n 'events',\n 'toe',\n 'txn',\n 'rph',\n 'sid',\n 'vot',\n 'vtm'\n];\n\nexport const decode = (token: string) => {\n const parts = token.split('.');\n const [header, payload, signature] = parts;\n\n if (parts.length !== 3 || !header || !payload || !signature) {\n throw new Error('ID token could not be decoded');\n }\n const payloadJSON = JSON.parse(urlDecodeB64(payload));\n const claims: IdToken = { __raw: token };\n const user: any = {};\n Object.keys(payloadJSON).forEach(k => {\n claims[k] = payloadJSON[k];\n if (!idTokendecoded.includes(k)) {\n user[k] = payloadJSON[k];\n }\n });\n return {\n encoded: { header, payload, signature },\n header: JSON.parse(urlDecodeB64(header)),\n claims,\n user\n };\n};\n\nexport const verify = (options: JWTVerifyOptions) => {\n if (!options.id_token) {\n throw new Error('ID token is required but missing');\n }\n\n const decoded = decode(options.id_token);\n\n if (!decoded.claims.iss) {\n throw new Error(\n 'Issuer (iss) claim must be a string present in the ID token'\n );\n }\n\n if (decoded.claims.iss !== options.iss) {\n throw new Error(\n `Issuer (iss) claim mismatch in the ID token; expected \"${options.iss}\", found \"${decoded.claims.iss}\"`\n );\n }\n\n if (!decoded.user.sub) {\n throw new Error(\n 'Subject (sub) claim must be a string present in the ID token'\n );\n }\n\n if (decoded.header.alg !== 'RS256') {\n throw new Error(\n `Signature algorithm of \"${decoded.header.alg}\" is not supported. Expected the ID token to be signed with \"RS256\".`\n );\n }\n\n if (\n !decoded.claims.aud ||\n !(\n typeof decoded.claims.aud === 'string' ||\n Array.isArray(decoded.claims.aud)\n )\n ) {\n throw new Error(\n 'Audience (aud) claim must be a string or array of strings present in the ID token'\n );\n }\n if (Array.isArray(decoded.claims.aud)) {\n if (!decoded.claims.aud.includes(options.aud)) {\n throw new Error(\n `Audience (aud) claim mismatch in the ID token; expected \"${\n options.aud\n }\" but was not one of \"${decoded.claims.aud.join(', ')}\"`\n );\n }\n if (decoded.claims.aud.length > 1) {\n if (!decoded.claims.azp) {\n throw new Error(\n 'Authorized Party (azp) claim must be a string present in the ID token when Audience (aud) claim has multiple values'\n );\n }\n if (decoded.claims.azp !== options.aud) {\n throw new Error(\n `Authorized Party (azp) claim mismatch in the ID token; expected \"${options.aud}\", found \"${decoded.claims.azp}\"`\n );\n }\n }\n } else if (decoded.claims.aud !== options.aud) {\n throw new Error(\n `Audience (aud) claim mismatch in the ID token; expected \"${options.aud}\" but found \"${decoded.claims.aud}\"`\n );\n }\n if (options.nonce) {\n if (!decoded.claims.nonce) {\n throw new Error(\n 'Nonce (nonce) claim must be a string present in the ID token'\n );\n }\n if (decoded.claims.nonce !== options.nonce) {\n throw new Error(\n `Nonce (nonce) claim mismatch in the ID token; expected \"${options.nonce}\", found \"${decoded.claims.nonce}\"`\n );\n }\n }\n\n if (options.max_age && !isNumber(decoded.claims.auth_time)) {\n throw new Error(\n 'Authentication Time (auth_time) claim must be a number present in the ID token when Max Age (max_age) is specified'\n );\n }\n\n /* c8 ignore next 5 */\n if (decoded.claims.exp == null || !isNumber(decoded.claims.exp)) {\n throw new Error(\n 'Expiration Time (exp) claim must be a number present in the ID token'\n );\n }\n if (!isNumber(decoded.claims.iat)) {\n throw new Error(\n 'Issued At (iat) claim must be a number present in the ID token'\n );\n }\n\n const leeway = options.leeway || 60;\n const now = new Date(options.now || Date.now());\n const expDate = new Date(0);\n\n expDate.setUTCSeconds(decoded.claims.exp + leeway);\n\n if (now > expDate) {\n throw new Error(\n `Expiration Time (exp) claim error in the ID token; current time (${now}) is after expiration time (${expDate})`\n );\n }\n\n if (decoded.claims.nbf != null && isNumber(decoded.claims.nbf)) {\n const nbfDate = new Date(0);\n nbfDate.setUTCSeconds(decoded.claims.nbf - leeway);\n if (now < nbfDate) {\n throw new Error(\n `Not Before time (nbf) claim in the ID token indicates that this token can't be used just yet. Current time (${now}) is before ${nbfDate}`\n );\n }\n }\n\n if (decoded.claims.auth_time != null && isNumber(decoded.claims.auth_time)) {\n const authTimeDate = new Date(0);\n authTimeDate.setUTCSeconds(\n parseInt(decoded.claims.auth_time) + (options.max_age as number) + leeway\n );\n\n if (now > authTimeDate) {\n throw new Error(\n `Authentication Time (auth_time) claim in the ID token indicates that too much time has passed since the last end-user authentication. Current time (${now}) is after last auth at ${authTimeDate}`\n );\n }\n }\n\n if (options.organization) {\n const org = options.organization.trim();\n if (org.startsWith('org_')) {\n const orgId = org;\n if (!decoded.claims.org_id) {\n throw new Error(\n 'Organization ID (org_id) claim must be a string present in the ID token'\n );\n } else if (orgId !== decoded.claims.org_id) {\n throw new Error(\n `Organization ID (org_id) claim mismatch in the ID token; expected \"${orgId}\", found \"${decoded.claims.org_id}\"`\n );\n }\n } else {\n const orgName = org.toLowerCase();\n // TODO should we verify if there is an `org_id` claim?\n if (!decoded.claims.org_name) {\n throw new Error(\n 'Organization Name (org_name) claim must be a string present in the ID token'\n );\n } else if (orgName !== decoded.claims.org_name) {\n throw new Error(\n `Organization Name (org_name) claim mismatch in the ID token; expected \"${orgName}\", found \"${decoded.claims.org_name}\"`\n );\n }\n }\n }\n\n return decoded;\n};\n","\"use strict\";\r\nvar __assign = (this && this.__assign) || function () {\r\n __assign = Object.assign || function(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\r\n t[p] = s[p];\r\n }\r\n return t;\r\n };\r\n return __assign.apply(this, arguments);\r\n};\r\nexports.__esModule = true;\r\nfunction stringifyAttribute(name, value) {\r\n if (!value) {\r\n return '';\r\n }\r\n var stringified = '; ' + name;\r\n if (value === true) {\r\n return stringified; // boolean attributes shouldn't have a value\r\n }\r\n return stringified + '=' + value;\r\n}\r\nfunction stringifyAttributes(attributes) {\r\n if (typeof attributes.expires === 'number') {\r\n var expires = new Date();\r\n expires.setMilliseconds(expires.getMilliseconds() + attributes.expires * 864e+5);\r\n attributes.expires = expires;\r\n }\r\n return stringifyAttribute('Expires', attributes.expires ? attributes.expires.toUTCString() : '')\r\n + stringifyAttribute('Domain', attributes.domain)\r\n + stringifyAttribute('Path', attributes.path)\r\n + stringifyAttribute('Secure', attributes.secure)\r\n + stringifyAttribute('SameSite', attributes.sameSite);\r\n}\r\nfunction encode(name, value, attributes) {\r\n return encodeURIComponent(name)\r\n .replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent) // allowed special characters\r\n .replace(/\\(/g, '%28').replace(/\\)/g, '%29') // replace opening and closing parens\r\n + '=' + encodeURIComponent(value)\r\n // allowed special characters\r\n .replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent)\r\n + stringifyAttributes(attributes);\r\n}\r\nexports.encode = encode;\r\nfunction parse(cookieString) {\r\n var result = {};\r\n var cookies = cookieString ? cookieString.split('; ') : [];\r\n var rdecode = /(%[\\dA-F]{2})+/gi;\r\n for (var i = 0; i < cookies.length; i++) {\r\n var parts = cookies[i].split('=');\r\n var cookie = parts.slice(1).join('=');\r\n if (cookie.charAt(0) === '\"') {\r\n cookie = cookie.slice(1, -1);\r\n }\r\n try {\r\n var name_1 = parts[0].replace(rdecode, decodeURIComponent);\r\n result[name_1] = cookie.replace(rdecode, decodeURIComponent);\r\n }\r\n catch (e) {\r\n // ignore cookies with invalid name/value encoding\r\n }\r\n }\r\n return result;\r\n}\r\nexports.parse = parse;\r\nfunction getAll() {\r\n return parse(document.cookie);\r\n}\r\nexports.getAll = getAll;\r\nfunction get(name) {\r\n return getAll()[name];\r\n}\r\nexports.get = get;\r\nfunction set(name, value, attributes) {\r\n document.cookie = encode(name, value, __assign({ path: '/' }, attributes));\r\n}\r\nexports.set = set;\r\nfunction remove(name, attributes) {\r\n set(name, '', __assign(__assign({}, attributes), { expires: -1 }));\r\n}\r\nexports.remove = remove;\r\n","import * as Cookies from 'es-cookie';\n\ninterface ClientStorageOptions {\n daysUntilExpire?: number;\n cookieDomain?: string;\n}\n\n/**\n * Defines a type that handles storage to/from a storage location\n */\nexport type ClientStorage = {\n get<T extends Object>(key: string): T | undefined;\n save(key: string, value: any, options?: ClientStorageOptions): void;\n remove(key: string, options?: ClientStorageOptions): void;\n};\n\n/**\n * A storage protocol for marshalling data to/from cookies\n */\nexport const CookieStorage = {\n get<T extends Object>(key: string) {\n const value = Cookies.get(key);\n\n if (typeof value === 'undefined') {\n return;\n }\n\n return <T>JSON.parse(value);\n },\n\n save(key: string, value: any, options?: ClientStorageOptions): void {\n let cookieAttributes: Cookies.CookieAttributes = {};\n\n if ('https:' === window.location.protocol) {\n cookieAttributes = {\n secure: true,\n sameSite: 'none'\n };\n }\n\n if (options?.daysUntilExpire) {\n cookieAttributes.expires = options.daysUntilExpire;\n }\n\n if (options?.cookieDomain) {\n cookieAttributes.domain = options.cookieDomain;\n }\n\n Cookies.set(key, JSON.stringify(value), cookieAttributes);\n },\n\n remove(key: string, options?: ClientStorageOptions) {\n let cookieAttributes: Cookies.CookieAttributes = {};\n\n if (options?.cookieDomain) {\n cookieAttributes.domain = options.cookieDomain;\n }\n\n Cookies.remove(key, cookieAttributes);\n }\n} as ClientStorage;\n\n/**\n * @ignore\n */\nconst LEGACY_PREFIX = '_legacy_';\n\n/**\n * Cookie storage that creates a cookie for modern and legacy browsers.\n * See: https://web.dev/samesite-cookie-recipes/#handling-incompatible-clients\n */\nexport const CookieStorageWithLegacySameSite = {\n get<T extends Object>(key: string) {\n const value = CookieStorage.get<T>(key);\n\n if (value) {\n return value;\n }\n\n return CookieStorage.get<T>(`${LEGACY_PREFIX}${key}`);\n },\n\n save(key: string, value: any, options?: ClientStorageOptions): void {\n let cookieAttributes: Cookies.CookieAttributes = {};\n\n if ('https:' === window.location.protocol) {\n cookieAttributes = { secure: true };\n }\n\n if (options?.daysUntilExpire) {\n cookieAttributes.expires = options.daysUntilExpire;\n }\n\n if (options?.cookieDomain) {\n cookieAttributes.domain = options.cookieDomain;\n }\n\n Cookies.set(\n `${LEGACY_PREFIX}${key}`,\n JSON.stringify(value),\n cookieAttributes\n );\n CookieStorage.save(key, value, options);\n },\n\n remove(key: string, options?: ClientStorageOptions) {\n let cookieAttributes: Cookies.CookieAttributes = {};\n\n if (options?.cookieDomain) {\n cookieAttributes.domain = options.cookieDomain;\n }\n\n Cookies.remove(key, cookieAttributes);\n CookieStorage.remove(key, options);\n CookieStorage.remove(`${LEGACY_PREFIX}${key}`, options);\n }\n} as ClientStorage;\n\n/**\n * A storage protocol for marshalling data to/from session storage\n */\nexport const SessionStorage = {\n get<T extends Object>(key: string) {\n /* c8 ignore next 3 */\n if (typeof sessionStorage === 'undefined') {\n return;\n }\n\n const value = sessionStorage.getItem(key);\n\n if (value == null) {\n return;\n }\n\n return <T>JSON.parse(value);\n },\n\n save(key: string, value: any): void {\n sessionStorage.setItem(key, JSON.stringify(value));\n },\n\n remove(key: string) {\n sessionStorage.removeItem(key);\n }\n} as ClientStorage;\n","import { ICache } from './cache';\nimport type { Dpop } from './dpop/dpop';\nimport { CompleteResponse } from './MyAccountApiClient';\n\nexport interface AuthorizationParams {\n /**\n * - `'page'`: displays the UI with a full page view\n * - `'popup'`: displays the UI with a popup window\n * - `'touch'`: displays the UI in a way that leverages a touch interface\n * - `'wap'`: displays the UI with a \"feature phone\" type interface\n */\n display?: 'page' | 'popup' | 'touch' | 'wap';\n\n /**\n * - `'none'`: do not prompt user for login or consent on reauthentication\n * - `'login'`: prompt user for reauthentication\n * - `'consent'`: prompt user for consent before processing request\n * - `'select_account'`: prompt user to select an account\n */\n prompt?: 'none' | 'login' | 'consent' | 'select_account';\n\n /**\n * Maximum allowable elapsed time (in seconds) since authentication.\n * If the last time the user authenticated is greater than this value,\n * the user must be reauthenticated.\n */\n max_age?: string | number;\n\n /**\n * The space-separated list of language tags, ordered by preference.\n * For example: `'fr-CA fr en'`.\n */\n ui_locales?: string;\n\n /**\n * Previously issued ID Token.\n */\n id_token_hint?: string;\n\n /**\n * Provides a hint to Auth0 as to what flow should be displayed.\n * The default behavior is to show a login page but you can override\n * this by passing 'signup' to show the signup page instead.\n *\n * This only affects the New Universal Login Experience.\n */\n screen_hint?: 'signup' | 'login' | string;\n\n /**\n * The user's email address or other identifier. When your app knows\n * which user is trying to authenticate, you can provide this parameter\n * to pre-fill the email box or select the right session for sign-in.\n *\n * This currently only affects the classic Lock experience.\n */\n login_hint?: string;\n\n acr_values?: string;\n\n /**\n * The default scope to be used on authentication requests.\n *\n * This defaults to `profile email` if not set. If you are setting extra scopes and require\n * `profile` and `email` to be included then you must include them in the provided scope.\n *\n * Note: The `openid` scope is **always applied** regardless of this setting.\n */\n scope?: string;\n\n /**\n * The default audience to be used for requesting API access.\n */\n audience?: string;\n\n /**\n * The name of the connection configured for your application.\n * If null, it will redirect to the Auth0 Login Page and show\n * the Login Widget.\n */\n connection?: string;\n\n /**\n * The organization to log in to.\n *\n * This will specify an `organization` parameter in your user's login request.\n *\n * - If you provide an Organization ID (a string with the prefix `org_`), it will be validated against the `org_id` claim of your user's ID Token. The validation is case-sensitive.\n * - If you provide an Organization Name (a string *without* the prefix `org_`), it will be validated against the `org_name` claim of your user's ID Token. The validation is case-insensitive.\n * To use an Organization Name you must have \"Allow Organization Names in Authentication API\" switched on in your Auth0 settings dashboard.\n * More information is available on the [Auth0 documentation portal](https://auth0.com/docs/manage-users/organizations/configure-organizations/use-org-name-authentication-api)\n *\n */\n organization?: string;\n\n /**\n * The Id of an invitation to accept. This is available from the user invitation URL that is given when participating in a user invitation flow.\n */\n invitation?: string;\n\n /**\n * The default URL where Auth0 will redirect your browser to with\n * the authentication result. It must be whitelisted in\n * the \"Allowed Callback URLs\" field in your Auth0 Application's\n * settings. If not provided here, it should be provided in the other\n * methods that provide authentication.\n */\n redirect_uri?: string;\n\n /**\n * If you need to send custom parameters to the Authorization Server,\n * make sure to use the original parameter name.\n */\n [key: string]: any;\n}\n\nexport interface ClientAuthorizationParams extends Omit<AuthorizationParams, 'scope'> {\n scope?: string | Record<string, string>\n};\n\ninterface BaseLoginOptions {\n /**\n * URL parameters that will be sent back to the Authorization Server. This can be known parameters\n * defined by Auth0 or custom parameters that you define.\n */\n authorizationParams?: AuthorizationParams;\n}\n\nexport interface Auth0ClientOptions {\n /**\n * Your Auth0 account domain such as `'example.auth0.com'`,\n * `'example.eu.auth0.com'` or , `'example.mycompany.com'`\n * (when using [custom domains](https://auth0.com/docs/custom-domains))\n */\n domain: string;\n /**\n * The issuer to be used for validation of JWTs, optionally defaults to the domain above\n */\n issuer?: string;\n /**\n * The Client ID found on your Application settings page\n */\n clientId: string;\n /**\n * The value in seconds used to account for clock skew in JWT expirations.\n * Typically, this value is no more than a minute or two at maximum.\n * Defaults to 60s.\n */\n leeway?: number;\n\n /**\n * The location to use when storing cache data. Valid values are `memory` or `localstorage`.\n * The default setting is `memory`.\n *\n * Read more about [changing storage options in the Auth0 docs](https://auth0.com/docs/libraries/auth0-single-page-app-sdk#change-storage-options)\n */\n cacheLocation?: CacheLocation;\n\n /**\n * Specify a custom cache implementation to use for token storage and retrieval. This setting takes precedence over `cacheLocation` if they are both specified.\n */\n cache?: ICache;\n\n /**\n * If true, refresh tokens are used to fetch new access tokens from the Auth0 server. If false, the standard technique of using a hidden iframe and the `authorization_code` grant with `prompt=none` is used.\n * The default setting is `false`.\n *\n * Standard technique relies on cookies. Because browsers increasingly block third-party cookies, it requires a Custom Domain to function reliably. Refresh tokens serve as a fallback for environments where third-party cookies are blocked.\n * Using a Custom Domain with this set to `false` is the most secure and recommended approach.\n *\n * **Note**: Use of refresh tokens must be enabled by an administrator on your Auth0 client application.\n */\n useRefreshTokens?: boolean;\n\n /**\n * If true, fallback to the technique of using a hidden iframe and the `authorization_code` grant with `prompt=none` when unable to use refresh tokens. If false, the iframe fallback is not used and\n * errors relating to a failed `refresh_token` grant should be handled appropriately. The default setting is `false`.\n *\n * **Note**: There might be situations where doing silent auth with a Web Message response from an iframe is not possible,\n * like when you're serving your application from the file system or a custom protocol (like in a Desktop or Native app).\n * In situations like this you can disable the iframe fallback and handle the failed `refresh_token` grant and prompt the user to login interactively with `loginWithRedirect` or `loginWithPopup`.\"\n *\n * E.g. Using the `file:` protocol in an Electron application does not support that legacy technique.\n *\n * @example\n * let token: string;\n * try {\n * token = await auth0.getTokenSilently();\n * } catch (e) {\n * if (e.error === 'missing_refresh_token' || e.error === 'invalid_grant') {\n * auth0.loginWithRedirect();\n * }\n * }\n */\n useRefreshTokensFallback?: boolean;\n\n /**\n * A maximum number of seconds to wait before declaring background calls to /authorize as failed for timeout\n * Defaults to 60s.\n */\n authorizeTimeoutInSeconds?: number;\n\n /**\n * Specify the timeout for HTTP calls using `fetch`. The default is 10 seconds.\n */\n httpTimeoutInSeconds?: number;\n\n /**\n * Internal property to send information about the client to the authorization server.\n * @internal\n */\n auth0Client?: {\n name: string;\n version: string;\n env?: { [key: string]: string };\n };\n\n /**\n * Sets an additional cookie with no SameSite attribute to support legacy browsers\n * that are not compatible with the latest SameSite changes.\n * This will log a warning on modern browsers, you can disable the warning by setting\n * this to false but be aware that some older useragents will not work,\n * See https://www.chromium.org/updates/same-site/incompatible-clients\n * Defaults to true\n */\n legacySameSiteCookie?: boolean;\n\n /**\n * If `true`, the SDK will use a cookie when storing information about the auth transaction while\n * the user is going through the authentication flow on the authorization server.\n *\n * The default is `false`, in which case the SDK will use session storage.\n *\n * @notes\n *\n * You might want to enable this if you rely on your users being able to authenticate using flows that\n * may end up spanning across multiple tabs (e.g. magic links) or you cannot otherwise rely on session storage being available.\n */\n useCookiesForTransactions?: boolean;\n\n /**\n * Number of days until the cookie `auth0.is.authenticated` will expire\n * Defaults to 1.\n */\n sessionCheckExpiryDays?: number;\n\n /**\n * The domain the cookie is accessible from. If not set, the cookie is scoped to\n * the current domain, including the subdomain.\n *\n * Note: setting this incorrectly may cause silent authentication to stop working\n * on page load.\n *\n *\n * To keep a user logged in across multiple subdomains set this to your\n * top-level domain and prefixed with a `.` (eg: `.example.com`).\n */\n cookieDomain?: string;\n\n /**\n * If true, data to the token endpoint is transmitted as x-www-form-urlencoded data, if false it will be transmitted as JSON. The default setting is `true`.\n *\n * **Note:** Setting this to `false` may affect you if you use Auth0 Rules and are sending custom, non-primitive data. If you disable this,\n * please verify that your Auth0 Rules continue to work as intended.\n */\n useFormData?: boolean;\n\n /**\n * Modify the value used as the current time during the token validation.\n *\n * **Note**: Using this improperly can potentially compromise the token validation.\n */\n nowProvider?: () => Promise<number> | number;\n\n /**\n * If provided, the SDK will load the token worker from this URL instead of the integrated `blob`. An example of when this is useful is if you have strict\n * Content-Security-Policy (CSP) and wish to avoid needing to set `worker-src: blob:`. We recommend either serving the worker, which you can find in the module\n * at `<module_path>/dist/auth0-spa-js.worker.production.js`, from the same host as your application or using the Auth0 CDN\n * `https://cdn.auth0.com/js/auth0-spa-js/<version>/auth0-spa-js.worker.production.js`.\n *\n * **Note**: The worker is only used when `useRefreshTokens: true`, `cacheLocation: 'memory'`, and the `cache` is not custom.\n */\n workerUrl?: string;\n\n\n /**\n * If `true`, the SDK will allow the refreshing of tokens using MRRT\n */\n useMrrt?: boolean;\n\n /**\n * If `true`, DPoP (OAuth 2.0 Demonstrating Proof of Possession, RFC9449)\n * will be used to cryptographically bind tokens to this specific browser\n * so they can't be used from a different device in case of a leak.\n *\n * The default setting is `false`.\n */\n useDpop?: boolean;\n\n\n /**\n * URL parameters that will be sent back to the Authorization Server. This can be known parameters\n * defined by Auth0 or custom parameters that you define.\n */\n authorizationParams?: ClientAuthorizationParams;\n}\n\n/**\n * Configuration details exposed by the Auth0Client after initialization.\n *\n * @category Main\n */\nexport interface ClientConfiguration {\n /**\n * The Auth0 domain that was configured\n */\n domain: string;\n\n /**\n * The Auth0 client ID that was configured\n */\n clientId: string;\n}\n\n/**\n * The possible locations where tokens can be stored\n */\nexport type CacheLocation = 'memory' | 'localstorage';\n\n/**\n * @ignore\n */\nexport interface AuthorizeOptions extends AuthorizationParams {\n response_type: string;\n response_mode: string;\n redirect_uri?: string;\n nonce: string;\n state: string;\n scope: string;\n code_challenge: string;\n code_challenge_method: string;\n}\n\nexport interface RedirectLoginOptions<TAppState = any>\n extends BaseLoginOptions {\n /**\n * Used to store state before doing the redirect\n */\n appState?: TAppState;\n /**\n * Used to add to the URL fragment before redirecting\n */\n fragment?: string;\n /**\n * Used to control the redirect and not rely on the SDK to do the actual redirect.\n *\n * @example\n * const client = new Auth0Client({\n * async onRedirect(url) {\n * window.location.replace(url);\n * }\n * });\n * @deprecated since v2.0.1, use `openUrl` instead.\n */\n onRedirect?: (url: string) => Promise<void>;\n\n /**\n * Used to control the redirect and not rely on the SDK to do the actual redirect.\n *\n * @example\n * const client = new Auth0Client({\n * openUrl(url) {\n * window.location.replace(url);\n * }\n * });\n *\n * @example\n * import { Browser } from '@capacitor/browser';\n *\n * const client = new Auth0Client({\n * async openUrl(url) {\n * await Browser.open({ url });\n * }\n * });\n */\n openUrl?: (url: string) => Promise<void> | void;\n}\n\n/**\n * The types of responses expected from the authorization server.\n * - `code`: used for the standard login flow.\n * - `connect_code`: used for the connect account flow.\n */\nexport enum ResponseType {\n Code = 'code',\n ConnectCode = 'connect_code'\n}\n\nexport interface RedirectLoginResult<TAppState = any> {\n /**\n * State stored when the redirect request was made\n */\n appState?: TAppState;\n\n /**\n * The type of response, for login it will be `code`\n */\n response_type: ResponseType.Code;\n}\n\nexport interface PopupLoginOptions extends BaseLoginOptions { }\n\nexport interface PopupConfigOptions {\n /**\n * The number of seconds to wait for a popup response before\n * throwing a timeout error. Defaults to 60s\n */\n timeoutInSeconds?: number;\n\n /**\n * Accepts an already-created popup window to use. If not specified, the SDK\n * will create its own. This may be useful for platforms like iOS that have\n * security restrictions around when popups can be invoked (e.g. from a user click event)\n */\n popup?: any;\n\n /**\n * Controls whether the SDK automatically closes the popup window.\n *\n * - `true` (default): SDK closes the popup automatically after receiving the authorization response\n * - `false`: SDK does not close the popup. The caller is responsible for closing it, including on errors.\n *\n * Setting this to `false` is useful when you need full control over the popup lifecycle,\n * such as in Chrome extensions where closing the popup too early can terminate the\n * extension's service worker before authentication completes.\n *\n * When `closePopup: false`, you should close the popup in a try/finally block:\n * ```\n * const popup = window.open('', '_blank');\n * try {\n * await auth0.loginWithPopup({}, { popup, closePopup: false });\n * } finally {\n * popup.close();\n * }\n * ```\n *\n * @default true\n */\n closePopup?: boolean;\n}\n\nexport interface GetTokenSilentlyOptions {\n /**\n * When `off`, ignores the cache and always sends a\n * request to Auth0.\n * When `cache-only`, only reads from the cache and never sends a request to Auth0.\n * Defaults to `on`, where it both reads from the cache and sends a request to Auth0 as needed.\n */\n cacheMode?: 'on' | 'off' | 'cache-only';\n\n /**\n * Parameters that will be sent back to Auth0 as part of a request.\n */\n authorizationParams?: {\n /**\n * There's no actual redirect when getting a token silently,\n * but, according to the spec, a `redirect_uri` param is required.\n * Auth0 uses this parameter to validate that the current `origin`\n * matches the `redirect_uri` `origin` when sending the response.\n * It must be whitelisted in the \"Allowed Web Origins\" in your\n * Auth0 Application's settings.\n */\n redirect_uri?: string;\n\n /**\n * The scope that was used in the authentication request\n */\n scope?: string;\n\n /**\n * The audience that was used in the authentication request\n */\n audience?: string;\n\n /**\n * If you need to send custom parameters to the Authorization Server,\n * make sure to use the original parameter name.\n */\n [key: string]: any;\n };\n\n /** A maximum number of seconds to wait before declaring the background /authorize call as failed for timeout\n * Defaults to 60s.\n */\n timeoutInSeconds?: number;\n\n /**\n * If true, the full response from the /oauth/token endpoint (or the cache, if the cache was used) is returned\n * (minus `refresh_token` if one was issued). Otherwise, just the access token is returned.\n *\n * The default is `false`.\n */\n detailedResponse?: boolean;\n}\n\nexport interface GetTokenWithPopupOptions extends PopupLoginOptions {\n /**\n * When `off`, ignores the cache and always sends a request to Auth0.\n * When `cache-only`, only reads from the cache and never sends a request to Auth0.\n * Defaults to `on`, where it both reads from the cache and sends a request to Auth0 as needed.\n */\n cacheMode?: 'on' | 'off' | 'cache-only';\n}\n\nexport interface LogoutUrlOptions {\n /**\n * The `clientId` of your application.\n *\n * If this property is not set, then the `clientId` that was used during initialization of the SDK is sent to the logout endpoint.\n *\n * If this property is set to `null`, then no client ID value is sent to the logout endpoint.\n *\n * [Read more about how redirecting after logout works](https://auth0.com/docs/logout/guides/redirect-users-after-logout)\n */\n clientId?: string | null;\n\n /**\n * Parameters to pass to the logout endpoint. This can be known parameters defined by Auth0 or custom parameters\n * you wish to provide.\n */\n logoutParams?: {\n /**\n * When supported by the upstream identity provider,\n * forces the user to logout of their identity provider\n * and from Auth0.\n * [Read more about how federated logout works at Auth0](https://auth0.com/docs/logout/guides/logout-idps)\n */\n federated?: boolean;\n /**\n * The URL where Auth0 will redirect your browser to after the logout.\n *\n * **Note**: If the `client_id` parameter is included, the\n * `returnTo` URL that is provided must be listed in the\n * Application's \"Allowed Logout URLs\" in the Auth0 dashboard.\n * However, if the `client_id` parameter is not included, the\n * `returnTo` URL must be listed in the \"Allowed Logout URLs\" at\n * the account level in the Auth0 dashboard.\n *\n * [Read more about how redirecting after logout works](https://auth0.com/docs/logout/guides/redirect-users-after-logout)\n */\n returnTo?: string;\n\n /**\n * If you need to send custom parameters to the logout endpoint, make sure to use the original parameter name.\n */\n [key: string]: any;\n };\n}\n\nexport interface LogoutOptions extends LogoutUrlOptions {\n /**\n * Used to control the redirect and not rely on the SDK to do the actual redirect.\n *\n * @example\n * await auth0.logout({\n * async onRedirect(url) {\n * window.location.replace(url);\n * }\n * });\n * @deprecated since v2.0.1, use `openUrl` instead.\n */\n onRedirect?: (url: string) => Promise<void>;\n\n /**\n * Used to control the redirect and not rely on the SDK to do the actual redirect.\n *\n * Set to `false` to disable the redirect, or provide a function to handle the actual redirect yourself.\n *\n * @example\n * await auth0.logout({\n * openUrl(url) {\n * window.location.replace(url);\n * }\n * });\n *\n * @example\n * import { Browser } from '@capacitor/browser';\n *\n * await auth0.logout({\n * async openUrl(url) {\n * await Browser.open({ url });\n * }\n * });\n */\n openUrl?: false | ((url: string) => Promise<void> | void);\n}\n\nexport interface RedirectConnectAccountOptions<TAppState = any> {\n /**\n * The name of the connection to link (e.g. 'google-oauth2').\n */\n connection: string;\n\n /**\n * Array of scopes to request from the Identity Provider during the connect account flow.\n * \n * @example\n * await auth0.connectAccountWithRedirect({\n * connection: 'google-oauth2',\n * scopes: ['https://www.googleapis.com/auth/calendar']\n * });\n */\n scopes?: string[];\n\n /**\n * Additional authorization parameters for the request.\n *\n * @example\n * await auth0.connectAccountWithRedirect({\n * connection: 'github',\n * authorization_params: {\n * audience: 'https://api.github.com'\n * }\n * });\n */\n authorization_params?: AuthorizationParams;\n\n /**\n * The URI to redirect back to after connecting the account.\n */\n redirectUri?: string;\n\n /**\n * Optional application state to persist through the transaction.\n *\n * @example\n * await auth0.connectAccountWithRedirect({\n * connection: 'google-oauth2',\n * appState: { returnTo: '/settings' }\n * });\n */\n appState?: TAppState;\n\n /**\n * Optional function to handle the redirect URL.\n *\n * @example\n * await auth0.connectAccountWithRedirect({\n * connection: 'google-oauth2',\n * openUrl: async (url) => { myBrowserApi.open(url); }\n * });\n */\n openUrl?: (url: string) => Promise<void>;\n}\n\n/**\n * The result returned after a successful account connection redirect.\n *\n * Combines the redirect login result (including any persisted app state)\n * with the complete response from the My Account API.\n *\n * @template TAppState - The type of application state persisted through the transaction.\n * @example\n * const result = await auth0.connectAccountWithRedirect(options);\n * console.log(result.appState); // Access persisted app state\n * console.log(result.connection); // The connection of the account you connected to.\n * console.log(result.response_type === 'connect_code'); // The response type will be 'connect_code'\n */\nexport type ConnectAccountRedirectResult<TAppState = any> = CompleteResponse & {\n /**\n * State stored when the redirect request was made\n */\n appState?: TAppState;\n\n /**\n * The type of response, for connect account it will be `connect_code`\n */\n response_type: ResponseType.ConnectCode;\n};\n\n/**\n * @ignore\n */\nexport interface AuthenticationResult {\n state: string;\n code?: string;\n /**\n * This is for the redirect from the connect account flow.\n */\n connect_code?: string;\n error?: string;\n error_description?: string;\n}\n\n/**\n * @ignore\n */\nexport interface TokenEndpointOptions {\n baseUrl: string;\n client_id: string;\n grant_type: string;\n timeout?: number;\n auth0Client: any;\n useFormData?: boolean;\n dpop?: Pick<Dpop, 'generateProof' | 'getNonce' | 'setNonce'>;\n [key: string]: any;\n}\n\nexport type TokenEndpointResponse = {\n id_token: string;\n token_type: string;\n access_token: string;\n refresh_token?: string;\n expires_in: number;\n scope?: string;\n};\n\n/**\n * @ignore\n */\nexport interface OAuthTokenOptions extends TokenEndpointOptions {\n code_verifier: string;\n code: string;\n redirect_uri: string;\n audience: string;\n scope: string;\n}\n\n/**\n * @ignore\n */\nexport interface RefreshTokenOptions extends TokenEndpointOptions {\n refresh_token: string;\n}\n\n/**\n * @ignore\n */\nexport interface JWTVerifyOptions {\n iss: string;\n aud: string;\n id_token: string;\n nonce?: string;\n leeway?: number;\n max_age?: number;\n organization?: string;\n now?: number;\n}\n\nexport interface IdToken {\n __raw: string;\n name?: string;\n given_name?: string;\n family_name?: string;\n middle_name?: string;\n nickname?: string;\n preferred_username?: string;\n profile?: string;\n picture?: string;\n website?: string;\n email?: string;\n email_verified?: boolean;\n gender?: string;\n birthdate?: string;\n zoneinfo?: string;\n locale?: string;\n phone_number?: string;\n phone_number_verified?: boolean;\n address?: string;\n updated_at?: string;\n iss?: string;\n aud?: string;\n exp?: number;\n nbf?: number;\n iat?: number;\n jti?: string;\n azp?: string;\n nonce?: string;\n auth_time?: string;\n at_hash?: string;\n c_hash?: string;\n acr?: string;\n amr?: string[];\n sub_jwk?: string;\n cnf?: string;\n sid?: string;\n org_id?: string;\n org_name?: string;\n [key: string]: any;\n}\n\nexport class User {\n name?: string;\n given_name?: string;\n family_name?: string;\n middle_name?: string;\n nickname?: string;\n preferred_username?: string;\n profile?: string;\n picture?: string;\n website?: string;\n email?: string;\n email_verified?: boolean;\n gender?: string;\n birthdate?: string;\n zoneinfo?: string;\n locale?: string;\n phone_number?: string;\n phone_number_verified?: boolean;\n address?: string;\n updated_at?: string;\n sub?: string;\n [key: string]: any;\n}\n\n/**\n * @ignore\n */\nexport type FetchOptions = {\n method?: string;\n headers?: Record<string, string>;\n credentials?: 'include' | 'omit';\n body?: string;\n signal?: AbortSignal;\n};\n\n/**\n * @ignore\n */\nexport type FetchResponse = {\n ok: boolean;\n headers: Record<string, string | undefined>;\n json: any;\n};\n\nexport type GetTokenSilentlyVerboseResponse = Omit<\n TokenEndpointResponse,\n 'refresh_token'\n>;\n\n// MFA API types\nexport type {\n Authenticator,\n AuthenticatorType,\n OobChannel,\n MfaFactorType,\n EnrollParams,\n EnrollOtpParams,\n EnrollSmsParams,\n EnrollVoiceParams,\n EnrollEmailParams,\n EnrollPushParams,\n EnrollmentResponse,\n OtpEnrollmentResponse,\n OobEnrollmentResponse,\n ChallengeAuthenticatorParams,\n ChallengeResponse,\n VerifyParams,\n MfaGrantType,\n EnrollmentFactor\n} from './mfa/types';\n","const singlePromiseMap: Record<string, Promise<any>> = {};\n\nexport const singlePromise = <T>(\n cb: () => Promise<T>,\n key: string\n): Promise<T> => {\n let promise: null | Promise<T> = singlePromiseMap[key];\n if (!promise) {\n promise = cb().finally(() => {\n delete singlePromiseMap[key];\n promise = null;\n });\n singlePromiseMap[key] = promise;\n }\n return promise;\n};\n\nexport const retryPromise = async (\n cb: () => Promise<boolean>,\n maxNumberOfRetries = 3\n) => {\n for (let i = 0; i < maxNumberOfRetries; i++) {\n if (await cb()) {\n return true;\n }\n }\n\n return false;\n};\n","import {\n CACHE_KEY_PREFIX,\n ICache,\n KeyManifestEntry,\n MaybePromise\n} from './shared';\n\nexport class CacheKeyManifest {\n private readonly manifestKey: string;\n\n constructor(private cache: ICache, private clientId: string) {\n this.manifestKey = this.createManifestKeyFrom(this.clientId);\n }\n\n async add(key: string): Promise<void> {\n const keys = new Set(\n (await this.cache.get<KeyManifestEntry>(this.manifestKey))?.keys || []\n );\n\n keys.add(key);\n\n await this.cache.set<KeyManifestEntry>(this.manifestKey, {\n keys: [...keys]\n });\n }\n\n async remove(key: string): Promise<void> {\n const entry = await this.cache.get<KeyManifestEntry>(this.manifestKey);\n\n if (entry) {\n const keys = new Set(entry.keys);\n keys.delete(key);\n\n if (keys.size > 0) {\n return await this.cache.set(this.manifestKey, { keys: [...keys] });\n }\n\n return await this.cache.remove(this.manifestKey);\n }\n }\n\n get(): MaybePromise<KeyManifestEntry | undefined> {\n return this.cache.get<KeyManifestEntry>(this.manifestKey);\n }\n\n clear(): MaybePromise<void> {\n return this.cache.remove(this.manifestKey);\n }\n\n private createManifestKeyFrom(clientId: string): string {\n return `${CACHE_KEY_PREFIX}::${clientId}`;\n }\n}\n","import { ICache, InMemoryCache, LocalStorageCache } from './cache';\nimport {\n Auth0ClientOptions,\n AuthorizationParams,\n AuthorizeOptions,\n ClientAuthorizationParams,\n LogoutOptions\n} from './global';\nimport { scopesToRequest } from './scope';\n\n/**\n * @ignore\n */\nexport const GET_TOKEN_SILENTLY_LOCK_KEY = 'auth0.lock.getTokenSilently';\n\n/**\n * @ignore\n */\nexport const GET_TOKEN_FROM_IFRAME_LOCK_KEY = 'auth0.lock.getTokenFromIFrame';\n\n/**\n * @ignore\n */\nexport const buildGetTokenSilentlyLockKey = (\n clientId: string,\n audience: string\n) => `${GET_TOKEN_SILENTLY_LOCK_KEY}.${clientId}.${audience}`;\n\n/**\n * @ignore\n * Builds a global lock key for iframe-based authentication flows.\n * This ensures only one iframe authorization request runs at a time per client,\n * preventing \"Invalid state\" errors from concurrent iframe requests overwriting\n * each other's state in the Auth0 session.\n */\nexport const buildIframeLockKey = (clientId: string) =>\n `${GET_TOKEN_FROM_IFRAME_LOCK_KEY}.${clientId}`;\n\n/**\n * @ignore\n */\nexport const buildOrganizationHintCookieName = (clientId: string) =>\n `auth0.${clientId}.organization_hint`;\n\n/**\n * @ignore\n */\nexport const OLD_IS_AUTHENTICATED_COOKIE_NAME = 'auth0.is.authenticated';\n\n/**\n * @ignore\n */\nexport const buildIsAuthenticatedCookieName = (clientId: string) =>\n `auth0.${clientId}.is.authenticated`;\n\n/**\n * @ignore\n */\nconst cacheLocationBuilders: Record<string, () => ICache> = {\n memory: () => new InMemoryCache().enclosedCache,\n localstorage: () => new LocalStorageCache()\n};\n\n/**\n * @ignore\n */\nexport const cacheFactory = (location: string) => {\n return cacheLocationBuilders[location];\n};\n\n/**\n * @ignore\n */\nexport const getAuthorizeParams = (\n clientOptions: Auth0ClientOptions & {\n authorizationParams: ClientAuthorizationParams;\n },\n scope: Record<string, string>,\n authorizationParams: AuthorizationParams & { scope?: string },\n state: string,\n nonce: string,\n code_challenge: string,\n redirect_uri: string | undefined,\n response_mode: string | undefined,\n thumbprint: string | undefined\n): AuthorizeOptions => {\n return {\n client_id: clientOptions.clientId,\n ...clientOptions.authorizationParams,\n ...authorizationParams,\n scope: scopesToRequest(scope, authorizationParams.scope, authorizationParams.audience),\n response_type: 'code',\n response_mode: response_mode || 'query',\n state,\n nonce,\n redirect_uri:\n redirect_uri || clientOptions.authorizationParams.redirect_uri,\n code_challenge,\n code_challenge_method: 'S256',\n dpop_jkt: thumbprint\n };\n};\n\n/**\n * @ignore\n *\n * Function used to provide support for the deprecated onRedirect through openUrl.\n */\nexport const patchOpenUrlWithOnRedirect = <\n T extends Pick<LogoutOptions, 'openUrl' | 'onRedirect'>\n>(\n options: T\n) => {\n const { openUrl, onRedirect, ...originalOptions } = options;\n\n const result = {\n ...originalOptions,\n openUrl: openUrl === false || openUrl ? openUrl : onRedirect\n };\n\n return result as T;\n};\n\n/**\n * @ignore\n * \n * Checks if all scopes are included inside other array of scopes\n */\nexport const allScopesAreIncluded = (scopeToInclude?: string, scopes?: string): boolean => {\n const scopeGroup = scopes?.split(\" \") || [];\n const scopesToInclude = scopeToInclude?.split(\" \") || [];\n return scopesToInclude.every((key) => scopeGroup.includes(key));\n}\n\n/**\n * @ignore\n * \n * Returns the scopes that are missing after a refresh\n */\nexport const getMissingScopes = (requestedScope?: string, respondedScope?: string): string => {\n const requestedScopes = requestedScope?.split(\" \") || [];\n const respondedScopes = respondedScope?.split(\" \") || [];\n\n const missingScopes = requestedScopes.filter((scope) => respondedScopes.indexOf(scope) == -1);\n\n return missingScopes.join(\",\");\n}\n\n/**\n * @ignore\n *\n * For backward compatibility we are going to check if we are going to downscope while doing a refresh request\n * while MRRT is allowed. If the audience is the same for the refresh_token we are going to use and it has\n * lower scopes than the ones originally in the token, we are going to return the scopes that were stored\n * with the refresh_token in the tokenset.\n * @param useMrrt Setting that the user can activate to use MRRT in their requests\n * @param authorizationParams Contains the audience and scope that the user requested to obtain a token\n * @param cachedAudience Audience stored with the refresh_token wich we are going to use in the request\n * @param cachedScope Scope stored with the refresh_token wich we are going to use in the request\n */\nexport const getScopeToRequest = (\n useMrrt: boolean | undefined,\n authorizationParams: { audience?: string, scope: string },\n cachedAudience?: string,\n cachedScope?: string\n): string => {\n if (useMrrt && cachedAudience && cachedScope) {\n if (authorizationParams.audience !== cachedAudience) {\n return authorizationParams.scope;\n }\n\n const cachedScopes = cachedScope.split(\" \");\n const newScopes = authorizationParams.scope?.split(\" \") || [];\n const newScopesAreIncluded = newScopes.every((scope) => cachedScopes.includes(scope));\n\n return cachedScopes.length >= newScopes.length && newScopesAreIncluded ? cachedScope : authorizationParams.scope;\n }\n\n return authorizationParams.scope;\n}\n\n/**\n * @ignore\n * \n * Checks if the refresh request has been done using MRRT\n * @param cachedAudience Audience from the refresh token used to refresh\n * @param cachedScope Scopes from the refresh token used to refresh\n * @param requestAudience Audience sent to the server\n * @param requestScope Scopes sent to the server\n */\nexport const isRefreshWithMrrt = (\n cachedAudience: string | undefined,\n cachedScope: string | undefined,\n requestAudience: string | undefined,\n requestScope: string,\n): boolean => {\n if (cachedAudience !== requestAudience) {\n return true;\n }\n\n return !allScopesAreIncluded(requestScope, cachedScope);\n}","import { type KeyPair } from './utils';\n\nconst VERSION = 1;\nconst NAME = 'auth0-spa-js';\nconst TABLES = {\n NONCE: 'nonce',\n KEYPAIR: 'keypair'\n} as const;\n\nconst AUTH0_NONCE_ID = 'auth0';\n\ntype Table = (typeof TABLES)[keyof typeof TABLES];\n\nexport class DpopStorage {\n protected readonly clientId: string;\n protected dbHandle: IDBDatabase | undefined;\n\n constructor(clientId: string) {\n this.clientId = clientId;\n }\n\n protected getVersion(): number {\n return VERSION;\n }\n\n protected createDbHandle(): Promise<IDBDatabase> {\n const req = window.indexedDB.open(NAME, this.getVersion());\n\n return new Promise((resolve, reject) => {\n req.onupgradeneeded = () =>\n Object.values(TABLES).forEach(t => req.result.createObjectStore(t));\n\n req.onerror = () => reject(req.error);\n req.onsuccess = () => resolve(req.result);\n });\n }\n\n protected async getDbHandle(): Promise<IDBDatabase> {\n if (!this.dbHandle) {\n this.dbHandle = await this.createDbHandle();\n }\n\n return this.dbHandle;\n }\n\n protected async executeDbRequest<T = unknown>(\n table: string,\n mode: IDBTransactionMode,\n requestFactory: (table: IDBObjectStore) => IDBRequest<T>\n ): Promise<T> {\n const db = await this.getDbHandle();\n\n const txn = db.transaction(table, mode);\n const store = txn.objectStore(table);\n\n const request = requestFactory(store);\n\n return new Promise((resolve, reject) => {\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n });\n }\n\n protected buildKey(id?: string): string {\n const finalId = id\n ? `_${id}` // prefix to avoid collisions\n : AUTH0_NONCE_ID;\n\n return `${this.clientId}::${finalId}`;\n }\n\n public setNonce(nonce: string, id?: string): Promise<void> {\n return this.save(TABLES.NONCE, this.buildKey(id), nonce);\n }\n\n public setKeyPair(keyPair: KeyPair): Promise<void> {\n return this.save(TABLES.KEYPAIR, this.buildKey(), keyPair);\n }\n\n protected async save(\n table: Table,\n key: IDBValidKey,\n obj: unknown\n ): Promise<void> {\n return void await this.executeDbRequest(table, 'readwrite', table =>\n table.put(obj, key)\n );\n }\n\n public findNonce(id?: string): Promise<string | undefined> {\n return this.find(TABLES.NONCE, this.buildKey(id));\n }\n\n public findKeyPair(): Promise<KeyPair | undefined> {\n return this.find(TABLES.KEYPAIR, this.buildKey());\n }\n\n protected find<T = unknown>(\n table: Table,\n key: IDBValidKey\n ): Promise<T | undefined> {\n return this.executeDbRequest(table, 'readonly', table => table.get(key));\n }\n\n protected async deleteBy(\n table: Table,\n predicate: (key: IDBValidKey) => boolean\n ): Promise<void> {\n const allKeys = await this.executeDbRequest(table, 'readonly', table =>\n table.getAllKeys()\n );\n\n allKeys\n ?.filter(predicate)\n .map(k =>\n this.executeDbRequest(table, 'readwrite', table => table.delete(k))\n );\n }\n\n protected deleteByClientId(table: Table, clientId: string): Promise<void> {\n return this.deleteBy(\n table,\n k => typeof k === 'string' && k.startsWith(`${clientId}::`)\n );\n }\n\n public clearNonces(): Promise<void> {\n return this.deleteByClientId(TABLES.NONCE, this.clientId);\n }\n\n public clearKeyPairs(): Promise<void> {\n return this.deleteByClientId(TABLES.KEYPAIR, this.clientId);\n }\n}\n","import { DpopStorage } from './storage';\nimport * as dpopUtils from './utils';\n\nexport class Dpop {\n protected readonly storage: DpopStorage;\n\n public constructor(clientId: string) {\n this.storage = new DpopStorage(clientId);\n }\n\n public getNonce(id?: string): Promise<string | undefined> {\n return this.storage.findNonce(id);\n }\n\n public setNonce(nonce: string, id?: string): Promise<void> {\n return this.storage.setNonce(nonce, id);\n }\n\n protected async getOrGenerateKeyPair(): Promise<dpopUtils.KeyPair> {\n let keyPair = await this.storage.findKeyPair();\n\n if (!keyPair) {\n keyPair = await dpopUtils.generateKeyPair();\n await this.storage.setKeyPair(keyPair);\n }\n\n return keyPair;\n }\n\n public async generateProof(params: {\n url: string;\n method: string;\n nonce?: string;\n accessToken?: string;\n }): Promise<string> {\n const keyPair = await this.getOrGenerateKeyPair();\n\n return dpopUtils.generateProof({\n keyPair,\n ...params\n });\n }\n\n public async calculateThumbprint(): Promise<string> {\n const keyPair = await this.getOrGenerateKeyPair();\n\n return dpopUtils.calculateThumbprint(keyPair);\n }\n\n public async clear(): Promise<void> {\n await Promise.all([\n this.storage.clearNonces(),\n this.storage.clearKeyPairs()\n ]);\n }\n}\n","import { DPOP_NONCE_HEADER } from './dpop/utils';\nimport { UseDpopNonceError } from './errors';\nimport { GetTokenSilentlyVerboseResponse } from './global';\n\nexport type ResponseHeaders =\n | Record<string, string | null | undefined>\n | [string, string][]\n | { get(name: string): string | null | undefined };\n\nexport type CustomFetchMinimalOutput = {\n status: number;\n headers: ResponseHeaders;\n};\n\nexport type CustomFetchImpl<TOutput extends CustomFetchMinimalOutput> = (\n req: Request\n) => Promise<TOutput>;\n\nexport type AuthParams = {\n scope?: string[];\n audience?: string;\n};\n\ntype AccessTokenFactory = (authParams?: AuthParams) => Promise<string | GetTokenSilentlyVerboseResponse>;\n\nenum TokenType {\n Bearer = 'Bearer',\n DPoP = 'DPoP'\n}\n\nexport type FetcherConfig<TOutput extends CustomFetchMinimalOutput> = {\n getAccessToken?: AccessTokenFactory;\n baseUrl?: string;\n fetch?: CustomFetchImpl<TOutput>;\n dpopNonceId?: string;\n};\n\nexport type FetcherHooks = {\n isDpopEnabled: () => boolean;\n getAccessToken: AccessTokenFactory;\n getDpopNonce: () => Promise<string | undefined>;\n setDpopNonce: (nonce: string) => Promise<void>;\n generateDpopProof: (params: {\n url: string;\n method: string;\n nonce?: string;\n accessToken: string;\n }) => Promise<string>;\n};\n\nexport type FetchWithAuthCallbacks<TOutput> = {\n onUseDpopNonceError?(): Promise<TOutput>;\n};\n\nexport class Fetcher<TOutput extends CustomFetchMinimalOutput> {\n protected readonly config: Omit<FetcherConfig<TOutput>, 'fetch'> &\n Required<Pick<FetcherConfig<TOutput>, 'fetch'>>;\n\n protected readonly hooks: FetcherHooks;\n\n constructor(config: FetcherConfig<TOutput>, hooks: FetcherHooks) {\n this.hooks = hooks;\n\n this.config = {\n ...config,\n fetch:\n config.fetch ||\n // For easier testing and constructor compatibility with SSR.\n ((typeof window === 'undefined'\n ? fetch\n : window.fetch.bind(window)) as () => Promise<any>)\n };\n }\n\n protected isAbsoluteUrl(url: string): boolean {\n // `http://example.com`, `https://example.com` or `//example.com`\n return /^(https?:)?\\/\\//i.test(url);\n }\n\n protected buildUrl(\n baseUrl: string | undefined,\n url: string | undefined\n ): string {\n if (url) {\n if (this.isAbsoluteUrl(url)) {\n return url;\n }\n\n if (baseUrl) {\n return `${baseUrl.replace(/\\/?\\/$/, '')}/${url.replace(/^\\/+/, '')}`;\n }\n }\n\n throw new TypeError('`url` must be absolute or `baseUrl` non-empty.');\n }\n\n protected getAccessToken(authParams?: AuthParams): Promise<string | GetTokenSilentlyVerboseResponse> {\n return this.config.getAccessToken\n ? this.config.getAccessToken(authParams)\n : this.hooks.getAccessToken(authParams);\n }\n\n protected extractUrl(info: RequestInfo | URL): string {\n if (typeof info === 'string') {\n return info;\n }\n\n if (info instanceof URL) {\n return info.href;\n }\n\n return info.url;\n }\n\n protected buildBaseRequest(\n info: RequestInfo | URL,\n init: RequestInit | undefined\n ): Request {\n // In the native `fetch()` behavior, `init` can override `info` and the result\n // is the merge of both. So let's replicate that behavior by passing those into\n // a fresh `Request` object.\n\n // No `baseUrl`? We can use `info` and `init` as is.\n if (!this.config.baseUrl) {\n return new Request(info, init);\n }\n\n // But if `baseUrl` is present, first we have to build the final URL...\n const finalUrl = this.buildUrl(this.config.baseUrl, this.extractUrl(info));\n\n // ... and then overwrite `info`'s URL with it, making sure we keep any other\n // properties that might be there already (headers, etc).\n const finalInfo = info instanceof Request\n ? new Request(finalUrl, info)\n : finalUrl;\n\n return new Request(finalInfo, init);\n }\n\n protected setAuthorizationHeader(\n request: Request,\n accessToken: string,\n tokenType: string = TokenType.Bearer\n ): void {\n request.headers.set(\n 'authorization',\n `${tokenType} ${accessToken}`\n );\n }\n\n protected async setDpopProofHeader(\n request: Request,\n accessToken: string\n ): Promise<void> {\n if (!this.config.dpopNonceId) {\n return;\n }\n\n const dpopNonce = await this.hooks.getDpopNonce();\n\n const dpopProof = await this.hooks.generateDpopProof({\n accessToken,\n method: request.method,\n nonce: dpopNonce,\n url: request.url\n });\n\n request.headers.set('dpop', dpopProof);\n }\n\n protected async prepareRequest(request: Request, authParams?: AuthParams) {\n const accessTokenResponse = await this.getAccessToken(authParams);\n\n let tokenType: string;\n let accessToken: string;\n if (typeof accessTokenResponse === 'string') {\n tokenType = this.config.dpopNonceId ? TokenType.DPoP : TokenType.Bearer;\n accessToken = accessTokenResponse;\n } else {\n tokenType = accessTokenResponse.token_type;\n accessToken = accessTokenResponse.access_token;\n }\n\n this.setAuthorizationHeader(request, accessToken, tokenType);\n if (tokenType === TokenType.DPoP) {\n await this.setDpopProofHeader(request, accessToken);\n }\n }\n\n protected getHeader(headers: ResponseHeaders, name: string): string {\n if (Array.isArray(headers)) {\n return new Headers(headers).get(name) || '';\n }\n\n if (typeof headers.get === 'function') {\n return headers.get(name) || '';\n }\n\n return (headers as Record<string, string | null | undefined>)[name] || '';\n }\n\n protected hasUseDpopNonceError(response: TOutput): boolean {\n if (response.status !== 401) {\n return false;\n }\n\n const wwwAuthHeader = this.getHeader(response.headers, 'www-authenticate');\n\n return wwwAuthHeader.includes('invalid_dpop_nonce') || wwwAuthHeader.includes('use_dpop_nonce');\n }\n\n protected async handleResponse(\n response: TOutput,\n callbacks: FetchWithAuthCallbacks<TOutput>\n ): Promise<TOutput> {\n const newDpopNonce = this.getHeader(response.headers, DPOP_NONCE_HEADER);\n\n if (newDpopNonce) {\n await this.hooks.setDpopNonce(newDpopNonce);\n }\n\n if (!this.hasUseDpopNonceError(response)) {\n return response;\n }\n\n // After a `use_dpop_nonce` error, if we didn't get a new DPoP nonce or we\n // did but it still got rejected for the same reason, we have to give up.\n if (!newDpopNonce || !callbacks.onUseDpopNonceError) {\n throw new UseDpopNonceError(newDpopNonce);\n }\n\n return callbacks.onUseDpopNonceError();\n }\n\n protected async internalFetchWithAuth(\n info: RequestInfo | URL,\n init: RequestInit | undefined,\n callbacks: FetchWithAuthCallbacks<TOutput>,\n authParams?: AuthParams\n ): Promise<TOutput> {\n const request = this.buildBaseRequest(info, init);\n\n await this.prepareRequest(request, authParams);\n\n const response = await this.config.fetch(request);\n\n return this.handleResponse(response, callbacks);\n }\n\n public fetchWithAuth(\n info: RequestInfo | URL,\n init?: RequestInit,\n authParams?: AuthParams\n ): Promise<TOutput> {\n const callbacks: FetchWithAuthCallbacks<TOutput> = {\n onUseDpopNonceError: () =>\n this.internalFetchWithAuth(\n info,\n init,\n {\n ...callbacks,\n // Retry on a `use_dpop_nonce` error, but just once.\n onUseDpopNonceError: undefined\n },\n authParams\n )\n };\n\n return this.internalFetchWithAuth(info, init, callbacks, authParams);\n }\n}\n","import { AuthorizationParams } from './global';\nimport { Fetcher } from './fetcher';\n\ninterface ConnectRequest {\n /** The name of the connection to link the account with (e.g., 'google-oauth2', 'facebook'). */\n connection: string;\n /** Array of scopes to request from the Identity Provider during the connect account flow. */\n scopes?: string[];\n /** The URI to redirect to after the connection process completes. */\n redirect_uri: string;\n /** An opaque value used to maintain state between the request and callback. */\n state?: string;\n /** The PKCE code challenge derived from the code verifier. */\n code_challenge?: string;\n /** The method used to derive the code challenge. Required when code_challenge is provided. */\n code_challenge_method?: 'S256';\n authorization_params?: AuthorizationParams;\n}\n\ninterface ConnectResponse {\n /** The base URI to initiate the account connection flow. */\n connect_uri: string;\n /** The authentication session identifier. */\n auth_session: string;\n /** Parameters to be used with the connect URI. */\n connect_params: {\n /** The ticket identifier to be used with the connection URI. */\n ticket: string;\n };\n /** The number of seconds until the ticket expires. */\n expires_in: number;\n}\n\ninterface CompleteRequest {\n /** The authentication session identifier */\n auth_session: string;\n /** The authorization code returned from the connect flow */\n connect_code: string;\n /** The redirect URI used in the original request */\n redirect_uri: string;\n /** The PKCE code verifier */\n code_verifier?: string;\n}\n\nexport interface CompleteResponse {\n /** The unique identifier of the connected account */\n id: string;\n /** The connection name */\n connection: string;\n /** The access type, always 'offline' */\n access_type: 'offline';\n /** Array of scopes granted */\n scopes?: string[];\n /** ISO date string of when the connected account was created */\n created_at: string;\n /** ISO date string of when the refresh token expires (optional) */\n expires_at?: string;\n}\n\n// Validation error returned from MyAccount API\nexport interface ErrorResponse {\n type: string;\n status: number;\n title: string;\n detail: string;\n validation_errors?: {\n detail: string;\n field?: string;\n pointer?: string;\n source?: string;\n }[];\n}\n\n/**\n * Subset of the MyAccount API that handles the connect accounts flow.\n */\nexport class MyAccountApiClient {\n constructor(\n private myAccountFetcher: Fetcher<Response>,\n private apiBase: string\n ) {}\n\n /**\n * Get a ticket for the connect account flow.\n */\n async connectAccount(params: ConnectRequest): Promise<ConnectResponse> {\n const res = await this.myAccountFetcher.fetchWithAuth(\n `${this.apiBase}v1/connected-accounts/connect`,\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(params)\n }\n );\n return this._handleResponse(res);\n }\n\n /**\n * Verify the redirect from the connect account flow and complete the connecting of the account.\n */\n async completeAccount(params: CompleteRequest): Promise<CompleteResponse> {\n const res = await this.myAccountFetcher.fetchWithAuth(\n `${this.apiBase}v1/connected-accounts/complete`,\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(params)\n }\n );\n return this._handleResponse(res);\n }\n\n private async _handleResponse(res: Response) {\n let body: any;\n try {\n body = await res.text();\n body = JSON.parse(body);\n } catch (err) {\n throw new MyAccountApiError({\n type: 'invalid_json',\n status: res.status,\n title: 'Invalid JSON response',\n detail: body || String(err)\n });\n }\n\n if (res.ok) {\n return body;\n } else {\n throw new MyAccountApiError(body);\n }\n }\n}\n\nexport class MyAccountApiError extends Error {\n public readonly type: string;\n public readonly status: number;\n public readonly title: string;\n public readonly detail: string;\n public readonly validation_errors?: ErrorResponse['validation_errors'];\n\n constructor({\n type,\n status,\n title,\n detail,\n validation_errors\n }: ErrorResponse) {\n super(detail);\n this.name = 'MyAccountApiError';\n this.type = type;\n this.status = status;\n this.title = title;\n this.detail = detail;\n this.validation_errors = validation_errors;\n Object.setPrototypeOf(this, MyAccountApiError.prototype);\n }\n}\n","import type { MfaFactorType, OobChannel } from './types';\n\n/**\n * Mapping configuration for a factor type\n */\nexport interface FactorMapping {\n authenticatorTypes: ['otp'] | ['oob'];\n oobChannels?: OobChannel[];\n}\n\n/**\n * Maps MFA factor types to auth-js enrollment parameters\n */\nexport const FACTOR_MAPPING: Record<MfaFactorType, FactorMapping> = {\n otp: {\n authenticatorTypes: ['otp']\n },\n sms: {\n authenticatorTypes: ['oob'],\n oobChannels: ['sms']\n },\n email: {\n authenticatorTypes: ['oob'],\n oobChannels: ['email']\n },\n push: {\n authenticatorTypes: ['oob'],\n oobChannels: ['auth0']\n },\n voice: {\n authenticatorTypes: ['oob'],\n oobChannels: ['voice']\n }\n};\n\n/**\n * MFA grant type constants for verification\n */\nexport const MfaGrantTypes = {\n /** Grant type for OTP (TOTP) verification */\n OTP: 'http://auth0.com/oauth/grant-type/mfa-otp',\n\n /** Grant type for OOB (SMS, Email, Push) verification */\n OOB: 'http://auth0.com/oauth/grant-type/mfa-oob',\n\n /** Grant type for recovery code verification */\n RECOVERY_CODE: 'http://auth0.com/oauth/grant-type/mfa-recovery-code'\n} as const;\n","import { FACTOR_MAPPING, MfaGrantTypes } from './constants';\nimport type { EnrollParams, VerifyParams, MfaGrantType } from './types';\n\n/**\n * Converts factor-based enrollment params to auth-js format\n *\n * @param params - The enrollment parameters with factorType\n * @returns Parameters in auth-js format with authenticatorTypes/oobChannels\n */\nexport function getAuthJsEnrollParams(params: EnrollParams) {\n const mapping = FACTOR_MAPPING[params.factorType];\n\n return {\n mfaToken: params.mfaToken,\n authenticatorTypes: mapping.authenticatorTypes,\n ...(mapping.oobChannels && { oobChannels: mapping.oobChannels }),\n ...('phoneNumber' in params && { phoneNumber: params.phoneNumber }),\n ...('email' in params && { email: params.email })\n };\n}\n\n/**\n * Gets the grant type from verification parameters based on which field is provided.\n *\n * Priority order: otp > oobCode > recoveryCode\n *\n * @param params - The verification parameters\n * @returns The grant type or undefined if no verification field is present\n */\nexport function getGrantType(params: VerifyParams): MfaGrantType | undefined {\n if ('otp' in params && params.otp) {\n return MfaGrantTypes.OTP;\n }\n if ('oobCode' in params && params.oobCode) {\n return MfaGrantTypes.OOB;\n }\n if ('recoveryCode' in params && params.recoveryCode) {\n return MfaGrantTypes.RECOVERY_CODE;\n }\n return undefined;\n}\n",null,"export const encoder = new TextEncoder();\nexport const decoder = new TextDecoder();\nconst MAX_INT32 = 2 ** 32;\nexport function concat(...buffers) {\n const size = buffers.reduce((acc, { length }) => acc + length, 0);\n const buf = new Uint8Array(size);\n let i = 0;\n for (const buffer of buffers) {\n buf.set(buffer, i);\n i += buffer.length;\n }\n return buf;\n}\nfunction writeUInt32BE(buf, value, offset) {\n if (value < 0 || value >= MAX_INT32) {\n throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`);\n }\n buf.set([value >>> 24, value >>> 16, value >>> 8, value & 0xff], offset);\n}\nexport function uint64be(value) {\n const high = Math.floor(value / MAX_INT32);\n const low = value % MAX_INT32;\n const buf = new Uint8Array(8);\n writeUInt32BE(buf, high, 0);\n writeUInt32BE(buf, low, 4);\n return buf;\n}\nexport function uint32be(value) {\n const buf = new Uint8Array(4);\n writeUInt32BE(buf, value);\n return buf;\n}\nexport function encode(string) {\n const bytes = new Uint8Array(string.length);\n for (let i = 0; i < string.length; i++) {\n const code = string.charCodeAt(i);\n if (code > 127) {\n throw new TypeError('non-ASCII string encountered in encode()');\n }\n bytes[i] = code;\n }\n return bytes;\n}\n","export function encodeBase64(input) {\n if (Uint8Array.prototype.toBase64) {\n return input.toBase64();\n }\n const CHUNK_SIZE = 0x8000;\n const arr = [];\n for (let i = 0; i < input.length; i += CHUNK_SIZE) {\n arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));\n }\n return btoa(arr.join(''));\n}\nexport function decodeBase64(encoded) {\n if (Uint8Array.fromBase64) {\n return Uint8Array.fromBase64(encoded);\n }\n const binary = atob(encoded);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n","import { encoder, decoder } from '../lib/buffer_utils.js';\nimport { encodeBase64, decodeBase64 } from '../lib/base64.js';\nexport function decode(input) {\n if (Uint8Array.fromBase64) {\n return Uint8Array.fromBase64(typeof input === 'string' ? input : decoder.decode(input), {\n alphabet: 'base64url',\n });\n }\n let encoded = input;\n if (encoded instanceof Uint8Array) {\n encoded = decoder.decode(encoded);\n }\n encoded = encoded.replace(/-/g, '+').replace(/_/g, '/');\n try {\n return decodeBase64(encoded);\n }\n catch {\n throw new TypeError('The input to be decoded is not correctly encoded.');\n }\n}\nexport function encode(input) {\n let unencoded = input;\n if (typeof unencoded === 'string') {\n unencoded = encoder.encode(unencoded);\n }\n if (Uint8Array.prototype.toBase64) {\n return unencoded.toBase64({ alphabet: 'base64url', omitPadding: true });\n }\n return encodeBase64(unencoded).replace(/=/g, '').replace(/\\+/g, '-').replace(/\\//g, '_');\n}\n","export class JOSEError extends Error {\n static code = 'ERR_JOSE_GENERIC';\n code = 'ERR_JOSE_GENERIC';\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nexport class JWTClaimValidationFailed extends JOSEError {\n static code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';\n code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';\n claim;\n reason;\n payload;\n constructor(message, payload, claim = 'unspecified', reason = 'unspecified') {\n super(message, { cause: { claim, reason, payload } });\n this.claim = claim;\n this.reason = reason;\n this.payload = payload;\n }\n}\nexport class JWTExpired extends JOSEError {\n static code = 'ERR_JWT_EXPIRED';\n code = 'ERR_JWT_EXPIRED';\n claim;\n reason;\n payload;\n constructor(message, payload, claim = 'unspecified', reason = 'unspecified') {\n super(message, { cause: { claim, reason, payload } });\n this.claim = claim;\n this.reason = reason;\n this.payload = payload;\n }\n}\nexport class JOSEAlgNotAllowed extends JOSEError {\n static code = 'ERR_JOSE_ALG_NOT_ALLOWED';\n code = 'ERR_JOSE_ALG_NOT_ALLOWED';\n}\nexport class JOSENotSupported extends JOSEError {\n static code = 'ERR_JOSE_NOT_SUPPORTED';\n code = 'ERR_JOSE_NOT_SUPPORTED';\n}\nexport class JWEDecryptionFailed extends JOSEError {\n static code = 'ERR_JWE_DECRYPTION_FAILED';\n code = 'ERR_JWE_DECRYPTION_FAILED';\n constructor(message = 'decryption operation failed', options) {\n super(message, options);\n }\n}\nexport class JWEInvalid extends JOSEError {\n static code = 'ERR_JWE_INVALID';\n code = 'ERR_JWE_INVALID';\n}\nexport class JWSInvalid extends JOSEError {\n static code = 'ERR_JWS_INVALID';\n code = 'ERR_JWS_INVALID';\n}\nexport class JWTInvalid extends JOSEError {\n static code = 'ERR_JWT_INVALID';\n code = 'ERR_JWT_INVALID';\n}\nexport class JWKInvalid extends JOSEError {\n static code = 'ERR_JWK_INVALID';\n code = 'ERR_JWK_INVALID';\n}\nexport class JWKSInvalid extends JOSEError {\n static code = 'ERR_JWKS_INVALID';\n code = 'ERR_JWKS_INVALID';\n}\nexport class JWKSNoMatchingKey extends JOSEError {\n static code = 'ERR_JWKS_NO_MATCHING_KEY';\n code = 'ERR_JWKS_NO_MATCHING_KEY';\n constructor(message = 'no applicable key found in the JSON Web Key Set', options) {\n super(message, options);\n }\n}\nexport class JWKSMultipleMatchingKeys extends JOSEError {\n [Symbol.asyncIterator];\n static code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';\n code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';\n constructor(message = 'multiple matching keys found in the JSON Web Key Set', options) {\n super(message, options);\n }\n}\nexport class JWKSTimeout extends JOSEError {\n static code = 'ERR_JWKS_TIMEOUT';\n code = 'ERR_JWKS_TIMEOUT';\n constructor(message = 'request timed out', options) {\n super(message, options);\n }\n}\nexport class JWSSignatureVerificationFailed extends JOSEError {\n static code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';\n code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';\n constructor(message = 'signature verification failed', options) {\n super(message, options);\n }\n}\n","const unusable = (name, prop = 'algorithm.name') => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);\nconst isAlgorithm = (algorithm, name) => algorithm.name === name;\nfunction getHashLength(hash) {\n return parseInt(hash.name.slice(4), 10);\n}\nfunction getNamedCurve(alg) {\n switch (alg) {\n case 'ES256':\n return 'P-256';\n case 'ES384':\n return 'P-384';\n case 'ES512':\n return 'P-521';\n default:\n throw new Error('unreachable');\n }\n}\nfunction checkUsage(key, usage) {\n if (usage && !key.usages.includes(usage)) {\n throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);\n }\n}\nexport function checkSigCryptoKey(key, alg, usage) {\n switch (alg) {\n case 'HS256':\n case 'HS384':\n case 'HS512': {\n if (!isAlgorithm(key.algorithm, 'HMAC'))\n throw unusable('HMAC');\n const expected = parseInt(alg.slice(2), 10);\n const actual = getHashLength(key.algorithm.hash);\n if (actual !== expected)\n throw unusable(`SHA-${expected}`, 'algorithm.hash');\n break;\n }\n case 'RS256':\n case 'RS384':\n case 'RS512': {\n if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5'))\n throw unusable('RSASSA-PKCS1-v1_5');\n const expected = parseInt(alg.slice(2), 10);\n const actual = getHashLength(key.algorithm.hash);\n if (actual !== expected)\n throw unusable(`SHA-${expected}`, 'algorithm.hash');\n break;\n }\n case 'PS256':\n case 'PS384':\n case 'PS512': {\n if (!isAlgorithm(key.algorithm, 'RSA-PSS'))\n throw unusable('RSA-PSS');\n const expected = parseInt(alg.slice(2), 10);\n const actual = getHashLength(key.algorithm.hash);\n if (actual !== expected)\n throw unusable(`SHA-${expected}`, 'algorithm.hash');\n break;\n }\n case 'Ed25519':\n case 'EdDSA': {\n if (!isAlgorithm(key.algorithm, 'Ed25519'))\n throw unusable('Ed25519');\n break;\n }\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87': {\n if (!isAlgorithm(key.algorithm, alg))\n throw unusable(alg);\n break;\n }\n case 'ES256':\n case 'ES384':\n case 'ES512': {\n if (!isAlgorithm(key.algorithm, 'ECDSA'))\n throw unusable('ECDSA');\n const expected = getNamedCurve(alg);\n const actual = key.algorithm.namedCurve;\n if (actual !== expected)\n throw unusable(expected, 'algorithm.namedCurve');\n break;\n }\n default:\n throw new TypeError('CryptoKey does not support this operation');\n }\n checkUsage(key, usage);\n}\nexport function checkEncCryptoKey(key, alg, usage) {\n switch (alg) {\n case 'A128GCM':\n case 'A192GCM':\n case 'A256GCM': {\n if (!isAlgorithm(key.algorithm, 'AES-GCM'))\n throw unusable('AES-GCM');\n const expected = parseInt(alg.slice(1, 4), 10);\n const actual = key.algorithm.length;\n if (actual !== expected)\n throw unusable(expected, 'algorithm.length');\n break;\n }\n case 'A128KW':\n case 'A192KW':\n case 'A256KW': {\n if (!isAlgorithm(key.algorithm, 'AES-KW'))\n throw unusable('AES-KW');\n const expected = parseInt(alg.slice(1, 4), 10);\n const actual = key.algorithm.length;\n if (actual !== expected)\n throw unusable(expected, 'algorithm.length');\n break;\n }\n case 'ECDH': {\n switch (key.algorithm.name) {\n case 'ECDH':\n case 'X25519':\n break;\n default:\n throw unusable('ECDH or X25519');\n }\n break;\n }\n case 'PBES2-HS256+A128KW':\n case 'PBES2-HS384+A192KW':\n case 'PBES2-HS512+A256KW':\n if (!isAlgorithm(key.algorithm, 'PBKDF2'))\n throw unusable('PBKDF2');\n break;\n case 'RSA-OAEP':\n case 'RSA-OAEP-256':\n case 'RSA-OAEP-384':\n case 'RSA-OAEP-512': {\n if (!isAlgorithm(key.algorithm, 'RSA-OAEP'))\n throw unusable('RSA-OAEP');\n const expected = parseInt(alg.slice(9), 10) || 1;\n const actual = getHashLength(key.algorithm.hash);\n if (actual !== expected)\n throw unusable(`SHA-${expected}`, 'algorithm.hash');\n break;\n }\n default:\n throw new TypeError('CryptoKey does not support this operation');\n }\n checkUsage(key, usage);\n}\n","function message(msg, actual, ...types) {\n types = types.filter(Boolean);\n if (types.length > 2) {\n const last = types.pop();\n msg += `one of type ${types.join(', ')}, or ${last}.`;\n }\n else if (types.length === 2) {\n msg += `one of type ${types[0]} or ${types[1]}.`;\n }\n else {\n msg += `of type ${types[0]}.`;\n }\n if (actual == null) {\n msg += ` Received ${actual}`;\n }\n else if (typeof actual === 'function' && actual.name) {\n msg += ` Received function ${actual.name}`;\n }\n else if (typeof actual === 'object' && actual != null) {\n if (actual.constructor?.name) {\n msg += ` Received an instance of ${actual.constructor.name}`;\n }\n }\n return msg;\n}\nexport const invalidKeyInput = (actual, ...types) => message('Key must be ', actual, ...types);\nexport const withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);\n","export function assertCryptoKey(key) {\n if (!isCryptoKey(key)) {\n throw new Error('CryptoKey instance expected');\n }\n}\nexport const isCryptoKey = (key) => {\n if (key?.[Symbol.toStringTag] === 'CryptoKey')\n return true;\n try {\n return key instanceof CryptoKey;\n }\n catch {\n return false;\n }\n};\nexport const isKeyObject = (key) => key?.[Symbol.toStringTag] === 'KeyObject';\nexport const isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);\n","export function isDisjoint(...headers) {\n const sources = headers.filter(Boolean);\n if (sources.length === 0 || sources.length === 1) {\n return true;\n }\n let acc;\n for (const header of sources) {\n const parameters = Object.keys(header);\n if (!acc || acc.size === 0) {\n acc = new Set(parameters);\n continue;\n }\n for (const parameter of parameters) {\n if (acc.has(parameter)) {\n return false;\n }\n acc.add(parameter);\n }\n }\n return true;\n}\n","const isObjectLike = (value) => typeof value === 'object' && value !== null;\nexport function isObject(input) {\n if (!isObjectLike(input) || Object.prototype.toString.call(input) !== '[object Object]') {\n return false;\n }\n if (Object.getPrototypeOf(input) === null) {\n return true;\n }\n let proto = input;\n while (Object.getPrototypeOf(proto) !== null) {\n proto = Object.getPrototypeOf(proto);\n }\n return Object.getPrototypeOf(input) === proto;\n}\n","export function checkKeyLength(alg, key) {\n if (alg.startsWith('RS') || alg.startsWith('PS')) {\n const { modulusLength } = key.algorithm;\n if (typeof modulusLength !== 'number' || modulusLength < 2048) {\n throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);\n }\n }\n}\n","import { invalidKeyInput } from './invalid_key_input.js';\nimport { encodeBase64, decodeBase64 } from '../lib/base64.js';\nimport { JOSENotSupported } from '../util/errors.js';\nimport { isCryptoKey, isKeyObject } from './is_key_like.js';\nconst formatPEM = (b64, descriptor) => {\n const newlined = (b64.match(/.{1,64}/g) || []).join('\\n');\n return `-----BEGIN ${descriptor}-----\\n${newlined}\\n-----END ${descriptor}-----`;\n};\nconst genericExport = async (keyType, keyFormat, key) => {\n if (isKeyObject(key)) {\n if (key.type !== keyType) {\n throw new TypeError(`key is not a ${keyType} key`);\n }\n return key.export({ format: 'pem', type: keyFormat });\n }\n if (!isCryptoKey(key)) {\n throw new TypeError(invalidKeyInput(key, 'CryptoKey', 'KeyObject'));\n }\n if (!key.extractable) {\n throw new TypeError('CryptoKey is not extractable');\n }\n if (key.type !== keyType) {\n throw new TypeError(`key is not a ${keyType} key`);\n }\n return formatPEM(encodeBase64(new Uint8Array(await crypto.subtle.exportKey(keyFormat, key))), `${keyType.toUpperCase()} KEY`);\n};\nexport const toSPKI = (key) => genericExport('public', 'spki', key);\nexport const toPKCS8 = (key) => genericExport('private', 'pkcs8', key);\nconst bytesEqual = (a, b) => {\n if (a.byteLength !== b.length)\n return false;\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i])\n return false;\n }\n return true;\n};\nconst createASN1State = (data) => ({ data, pos: 0 });\nconst parseLength = (state) => {\n const first = state.data[state.pos++];\n if (first & 0x80) {\n const lengthOfLen = first & 0x7f;\n let length = 0;\n for (let i = 0; i < lengthOfLen; i++) {\n length = (length << 8) | state.data[state.pos++];\n }\n return length;\n }\n return first;\n};\nconst skipElement = (state, count = 1) => {\n if (count <= 0)\n return;\n state.pos++;\n const length = parseLength(state);\n state.pos += length;\n if (count > 1) {\n skipElement(state, count - 1);\n }\n};\nconst expectTag = (state, expectedTag, errorMessage) => {\n if (state.data[state.pos++] !== expectedTag) {\n throw new Error(errorMessage);\n }\n};\nconst getSubarray = (state, length) => {\n const result = state.data.subarray(state.pos, state.pos + length);\n state.pos += length;\n return result;\n};\nconst parseAlgorithmOID = (state) => {\n expectTag(state, 0x06, 'Expected algorithm OID');\n const oidLen = parseLength(state);\n return getSubarray(state, oidLen);\n};\nfunction parsePKCS8Header(state) {\n expectTag(state, 0x30, 'Invalid PKCS#8 structure');\n parseLength(state);\n expectTag(state, 0x02, 'Expected version field');\n const verLen = parseLength(state);\n state.pos += verLen;\n expectTag(state, 0x30, 'Expected algorithm identifier');\n const algIdLen = parseLength(state);\n const algIdStart = state.pos;\n return { algIdStart, algIdLength: algIdLen };\n}\nfunction parseSPKIHeader(state) {\n expectTag(state, 0x30, 'Invalid SPKI structure');\n parseLength(state);\n expectTag(state, 0x30, 'Expected algorithm identifier');\n const algIdLen = parseLength(state);\n const algIdStart = state.pos;\n return { algIdStart, algIdLength: algIdLen };\n}\nconst parseECAlgorithmIdentifier = (state) => {\n const algOid = parseAlgorithmOID(state);\n if (bytesEqual(algOid, [0x2b, 0x65, 0x6e])) {\n return 'X25519';\n }\n if (!bytesEqual(algOid, [0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01])) {\n throw new Error('Unsupported key algorithm');\n }\n expectTag(state, 0x06, 'Expected curve OID');\n const curveOidLen = parseLength(state);\n const curveOid = getSubarray(state, curveOidLen);\n for (const { name, oid } of [\n { name: 'P-256', oid: [0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07] },\n { name: 'P-384', oid: [0x2b, 0x81, 0x04, 0x00, 0x22] },\n { name: 'P-521', oid: [0x2b, 0x81, 0x04, 0x00, 0x23] },\n ]) {\n if (bytesEqual(curveOid, oid)) {\n return name;\n }\n }\n throw new Error('Unsupported named curve');\n};\nconst genericImport = async (keyFormat, keyData, alg, options) => {\n let algorithm;\n let keyUsages;\n const isPublic = keyFormat === 'spki';\n const getSigUsages = () => (isPublic ? ['verify'] : ['sign']);\n const getEncUsages = () => isPublic ? ['encrypt', 'wrapKey'] : ['decrypt', 'unwrapKey'];\n switch (alg) {\n case 'PS256':\n case 'PS384':\n case 'PS512':\n algorithm = { name: 'RSA-PSS', hash: `SHA-${alg.slice(-3)}` };\n keyUsages = getSigUsages();\n break;\n case 'RS256':\n case 'RS384':\n case 'RS512':\n algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${alg.slice(-3)}` };\n keyUsages = getSigUsages();\n break;\n case 'RSA-OAEP':\n case 'RSA-OAEP-256':\n case 'RSA-OAEP-384':\n case 'RSA-OAEP-512':\n algorithm = {\n name: 'RSA-OAEP',\n hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`,\n };\n keyUsages = getEncUsages();\n break;\n case 'ES256':\n case 'ES384':\n case 'ES512': {\n const curveMap = { ES256: 'P-256', ES384: 'P-384', ES512: 'P-521' };\n algorithm = { name: 'ECDSA', namedCurve: curveMap[alg] };\n keyUsages = getSigUsages();\n break;\n }\n case 'ECDH-ES':\n case 'ECDH-ES+A128KW':\n case 'ECDH-ES+A192KW':\n case 'ECDH-ES+A256KW': {\n try {\n const namedCurve = options.getNamedCurve(keyData);\n algorithm = namedCurve === 'X25519' ? { name: 'X25519' } : { name: 'ECDH', namedCurve };\n }\n catch (cause) {\n throw new JOSENotSupported('Invalid or unsupported key format');\n }\n keyUsages = isPublic ? [] : ['deriveBits'];\n break;\n }\n case 'Ed25519':\n case 'EdDSA':\n algorithm = { name: 'Ed25519' };\n keyUsages = getSigUsages();\n break;\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n algorithm = { name: alg };\n keyUsages = getSigUsages();\n break;\n default:\n throw new JOSENotSupported('Invalid or unsupported \"alg\" (Algorithm) value');\n }\n return crypto.subtle.importKey(keyFormat, keyData, algorithm, options?.extractable ?? (isPublic ? true : false), keyUsages);\n};\nconst processPEMData = (pem, pattern) => {\n return decodeBase64(pem.replace(pattern, ''));\n};\nexport const fromPKCS8 = (pem, alg, options) => {\n const keyData = processPEMData(pem, /(?:-----(?:BEGIN|END) PRIVATE KEY-----|\\s)/g);\n let opts = options;\n if (alg?.startsWith?.('ECDH-ES')) {\n opts ||= {};\n opts.getNamedCurve = (keyData) => {\n const state = createASN1State(keyData);\n parsePKCS8Header(state);\n return parseECAlgorithmIdentifier(state);\n };\n }\n return genericImport('pkcs8', keyData, alg, opts);\n};\nexport const fromSPKI = (pem, alg, options) => {\n const keyData = processPEMData(pem, /(?:-----(?:BEGIN|END) PUBLIC KEY-----|\\s)/g);\n let opts = options;\n if (alg?.startsWith?.('ECDH-ES')) {\n opts ||= {};\n opts.getNamedCurve = (keyData) => {\n const state = createASN1State(keyData);\n parseSPKIHeader(state);\n return parseECAlgorithmIdentifier(state);\n };\n }\n return genericImport('spki', keyData, alg, opts);\n};\nfunction spkiFromX509(buf) {\n const state = createASN1State(buf);\n expectTag(state, 0x30, 'Invalid certificate structure');\n parseLength(state);\n expectTag(state, 0x30, 'Invalid tbsCertificate structure');\n parseLength(state);\n if (buf[state.pos] === 0xa0) {\n skipElement(state, 6);\n }\n else {\n skipElement(state, 5);\n }\n const spkiStart = state.pos;\n expectTag(state, 0x30, 'Invalid SPKI structure');\n const spkiContentLen = parseLength(state);\n return buf.subarray(spkiStart, spkiStart + spkiContentLen + (state.pos - spkiStart));\n}\nfunction extractX509SPKI(x509) {\n const derBytes = processPEMData(x509, /(?:-----(?:BEGIN|END) CERTIFICATE-----|\\s)/g);\n return spkiFromX509(derBytes);\n}\nexport const fromX509 = (pem, alg, options) => {\n let spki;\n try {\n spki = extractX509SPKI(pem);\n }\n catch (cause) {\n throw new TypeError('Failed to parse the X.509 certificate', { cause });\n }\n return fromSPKI(formatPEM(encodeBase64(spki), 'PUBLIC KEY'), alg, options);\n};\n","import { JOSENotSupported } from '../util/errors.js';\nfunction subtleMapping(jwk) {\n let algorithm;\n let keyUsages;\n switch (jwk.kty) {\n case 'AKP': {\n switch (jwk.alg) {\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n algorithm = { name: jwk.alg };\n keyUsages = jwk.priv ? ['sign'] : ['verify'];\n break;\n default:\n throw new JOSENotSupported('Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value');\n }\n break;\n }\n case 'RSA': {\n switch (jwk.alg) {\n case 'PS256':\n case 'PS384':\n case 'PS512':\n algorithm = { name: 'RSA-PSS', hash: `SHA-${jwk.alg.slice(-3)}` };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'RS256':\n case 'RS384':\n case 'RS512':\n algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${jwk.alg.slice(-3)}` };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'RSA-OAEP':\n case 'RSA-OAEP-256':\n case 'RSA-OAEP-384':\n case 'RSA-OAEP-512':\n algorithm = {\n name: 'RSA-OAEP',\n hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`,\n };\n keyUsages = jwk.d ? ['decrypt', 'unwrapKey'] : ['encrypt', 'wrapKey'];\n break;\n default:\n throw new JOSENotSupported('Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value');\n }\n break;\n }\n case 'EC': {\n switch (jwk.alg) {\n case 'ES256':\n algorithm = { name: 'ECDSA', namedCurve: 'P-256' };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'ES384':\n algorithm = { name: 'ECDSA', namedCurve: 'P-384' };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'ES512':\n algorithm = { name: 'ECDSA', namedCurve: 'P-521' };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'ECDH-ES':\n case 'ECDH-ES+A128KW':\n case 'ECDH-ES+A192KW':\n case 'ECDH-ES+A256KW':\n algorithm = { name: 'ECDH', namedCurve: jwk.crv };\n keyUsages = jwk.d ? ['deriveBits'] : [];\n break;\n default:\n throw new JOSENotSupported('Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value');\n }\n break;\n }\n case 'OKP': {\n switch (jwk.alg) {\n case 'Ed25519':\n case 'EdDSA':\n algorithm = { name: 'Ed25519' };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'ECDH-ES':\n case 'ECDH-ES+A128KW':\n case 'ECDH-ES+A192KW':\n case 'ECDH-ES+A256KW':\n algorithm = { name: jwk.crv };\n keyUsages = jwk.d ? ['deriveBits'] : [];\n break;\n default:\n throw new JOSENotSupported('Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value');\n }\n break;\n }\n default:\n throw new JOSENotSupported('Invalid or unsupported JWK \"kty\" (Key Type) Parameter value');\n }\n return { algorithm, keyUsages };\n}\nexport async function jwkToKey(jwk) {\n if (!jwk.alg) {\n throw new TypeError('\"alg\" argument is required when \"jwk.alg\" is not present');\n }\n const { algorithm, keyUsages } = subtleMapping(jwk);\n const keyData = { ...jwk };\n if (keyData.kty !== 'AKP') {\n delete keyData.alg;\n }\n delete keyData.use;\n return crypto.subtle.importKey('jwk', keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages);\n}\n","import { decode as decodeBase64URL } from '../util/base64url.js';\nimport { fromSPKI, fromPKCS8, fromX509 } from '../lib/asn1.js';\nimport { jwkToKey } from '../lib/jwk_to_key.js';\nimport { JOSENotSupported } from '../util/errors.js';\nimport { isObject } from '../lib/is_object.js';\nexport async function importSPKI(spki, alg, options) {\n if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) {\n throw new TypeError('\"spki\" must be SPKI formatted string');\n }\n return fromSPKI(spki, alg, options);\n}\nexport async function importX509(x509, alg, options) {\n if (typeof x509 !== 'string' || x509.indexOf('-----BEGIN CERTIFICATE-----') !== 0) {\n throw new TypeError('\"x509\" must be X.509 formatted string');\n }\n return fromX509(x509, alg, options);\n}\nexport async function importPKCS8(pkcs8, alg, options) {\n if (typeof pkcs8 !== 'string' || pkcs8.indexOf('-----BEGIN PRIVATE KEY-----') !== 0) {\n throw new TypeError('\"pkcs8\" must be PKCS#8 formatted string');\n }\n return fromPKCS8(pkcs8, alg, options);\n}\nexport async function importJWK(jwk, alg, options) {\n if (!isObject(jwk)) {\n throw new TypeError('JWK must be an object');\n }\n let ext;\n alg ??= jwk.alg;\n ext ??= options?.extractable ?? jwk.ext;\n switch (jwk.kty) {\n case 'oct':\n if (typeof jwk.k !== 'string' || !jwk.k) {\n throw new TypeError('missing \"k\" (Key Value) Parameter value');\n }\n return decodeBase64URL(jwk.k);\n case 'RSA':\n if ('oth' in jwk && jwk.oth !== undefined) {\n throw new JOSENotSupported('RSA JWK \"oth\" (Other Primes Info) Parameter value is not supported');\n }\n return jwkToKey({ ...jwk, alg, ext });\n case 'AKP': {\n if (typeof jwk.alg !== 'string' || !jwk.alg) {\n throw new TypeError('missing \"alg\" (Algorithm) Parameter value');\n }\n if (alg !== undefined && alg !== jwk.alg) {\n throw new TypeError('JWK alg and alg option value mismatch');\n }\n return jwkToKey({ ...jwk, ext });\n }\n case 'EC':\n case 'OKP':\n return jwkToKey({ ...jwk, alg, ext });\n default:\n throw new JOSENotSupported('Unsupported \"kty\" (Key Type) Parameter value');\n }\n}\n","import { JOSENotSupported, JWEInvalid, JWSInvalid } from '../util/errors.js';\nexport function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {\n if (joseHeader.crit !== undefined && protectedHeader?.crit === undefined) {\n throw new Err('\"crit\" (Critical) Header Parameter MUST be integrity protected');\n }\n if (!protectedHeader || protectedHeader.crit === undefined) {\n return new Set();\n }\n if (!Array.isArray(protectedHeader.crit) ||\n protectedHeader.crit.length === 0 ||\n protectedHeader.crit.some((input) => typeof input !== 'string' || input.length === 0)) {\n throw new Err('\"crit\" (Critical) Header Parameter MUST be an array of non-empty strings when present');\n }\n let recognized;\n if (recognizedOption !== undefined) {\n recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);\n }\n else {\n recognized = recognizedDefault;\n }\n for (const parameter of protectedHeader.crit) {\n if (!recognized.has(parameter)) {\n throw new JOSENotSupported(`Extension Header Parameter \"${parameter}\" is not recognized`);\n }\n if (joseHeader[parameter] === undefined) {\n throw new Err(`Extension Header Parameter \"${parameter}\" is missing`);\n }\n if (recognized.get(parameter) && protectedHeader[parameter] === undefined) {\n throw new Err(`Extension Header Parameter \"${parameter}\" MUST be integrity protected`);\n }\n }\n return new Set(protectedHeader.crit);\n}\n","export function validateAlgorithms(option, algorithms) {\n if (algorithms !== undefined &&\n (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== 'string'))) {\n throw new TypeError(`\"${option}\" option must be an array of strings`);\n }\n if (!algorithms) {\n return undefined;\n }\n return new Set(algorithms);\n}\n","import { isObject } from './is_object.js';\nexport const isJWK = (key) => isObject(key) && typeof key.kty === 'string';\nexport const isPrivateJWK = (key) => key.kty !== 'oct' &&\n ((key.kty === 'AKP' && typeof key.priv === 'string') || typeof key.d === 'string');\nexport const isPublicJWK = (key) => key.kty !== 'oct' && key.d === undefined && key.priv === undefined;\nexport const isSecretJWK = (key) => key.kty === 'oct' && typeof key.k === 'string';\n","import { isJWK } from './is_jwk.js';\nimport { decode } from '../util/base64url.js';\nimport { jwkToKey } from './jwk_to_key.js';\nimport { isCryptoKey, isKeyObject } from './is_key_like.js';\nlet cache;\nconst handleJWK = async (key, jwk, alg, freeze = false) => {\n cache ||= new WeakMap();\n let cached = cache.get(key);\n if (cached?.[alg]) {\n return cached[alg];\n }\n const cryptoKey = await jwkToKey({ ...jwk, alg });\n if (freeze)\n Object.freeze(key);\n if (!cached) {\n cache.set(key, { [alg]: cryptoKey });\n }\n else {\n cached[alg] = cryptoKey;\n }\n return cryptoKey;\n};\nconst handleKeyObject = (keyObject, alg) => {\n cache ||= new WeakMap();\n let cached = cache.get(keyObject);\n if (cached?.[alg]) {\n return cached[alg];\n }\n const isPublic = keyObject.type === 'public';\n const extractable = isPublic ? true : false;\n let cryptoKey;\n if (keyObject.asymmetricKeyType === 'x25519') {\n switch (alg) {\n case 'ECDH-ES':\n case 'ECDH-ES+A128KW':\n case 'ECDH-ES+A192KW':\n case 'ECDH-ES+A256KW':\n break;\n default:\n throw new TypeError('given KeyObject instance cannot be used for this algorithm');\n }\n cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ['deriveBits']);\n }\n if (keyObject.asymmetricKeyType === 'ed25519') {\n if (alg !== 'EdDSA' && alg !== 'Ed25519') {\n throw new TypeError('given KeyObject instance cannot be used for this algorithm');\n }\n cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [\n isPublic ? 'verify' : 'sign',\n ]);\n }\n switch (keyObject.asymmetricKeyType) {\n case 'ml-dsa-44':\n case 'ml-dsa-65':\n case 'ml-dsa-87': {\n if (alg !== keyObject.asymmetricKeyType.toUpperCase()) {\n throw new TypeError('given KeyObject instance cannot be used for this algorithm');\n }\n cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [\n isPublic ? 'verify' : 'sign',\n ]);\n }\n }\n if (keyObject.asymmetricKeyType === 'rsa') {\n let hash;\n switch (alg) {\n case 'RSA-OAEP':\n hash = 'SHA-1';\n break;\n case 'RS256':\n case 'PS256':\n case 'RSA-OAEP-256':\n hash = 'SHA-256';\n break;\n case 'RS384':\n case 'PS384':\n case 'RSA-OAEP-384':\n hash = 'SHA-384';\n break;\n case 'RS512':\n case 'PS512':\n case 'RSA-OAEP-512':\n hash = 'SHA-512';\n break;\n default:\n throw new TypeError('given KeyObject instance cannot be used for this algorithm');\n }\n if (alg.startsWith('RSA-OAEP')) {\n return keyObject.toCryptoKey({\n name: 'RSA-OAEP',\n hash,\n }, extractable, isPublic ? ['encrypt'] : ['decrypt']);\n }\n cryptoKey = keyObject.toCryptoKey({\n name: alg.startsWith('PS') ? 'RSA-PSS' : 'RSASSA-PKCS1-v1_5',\n hash,\n }, extractable, [isPublic ? 'verify' : 'sign']);\n }\n if (keyObject.asymmetricKeyType === 'ec') {\n const nist = new Map([\n ['prime256v1', 'P-256'],\n ['secp384r1', 'P-384'],\n ['secp521r1', 'P-521'],\n ]);\n const namedCurve = nist.get(keyObject.asymmetricKeyDetails?.namedCurve);\n if (!namedCurve) {\n throw new TypeError('given KeyObject instance cannot be used for this algorithm');\n }\n if (alg === 'ES256' && namedCurve === 'P-256') {\n cryptoKey = keyObject.toCryptoKey({\n name: 'ECDSA',\n namedCurve,\n }, extractable, [isPublic ? 'verify' : 'sign']);\n }\n if (alg === 'ES384' && namedCurve === 'P-384') {\n cryptoKey = keyObject.toCryptoKey({\n name: 'ECDSA',\n namedCurve,\n }, extractable, [isPublic ? 'verify' : 'sign']);\n }\n if (alg === 'ES512' && namedCurve === 'P-521') {\n cryptoKey = keyObject.toCryptoKey({\n name: 'ECDSA',\n namedCurve,\n }, extractable, [isPublic ? 'verify' : 'sign']);\n }\n if (alg.startsWith('ECDH-ES')) {\n cryptoKey = keyObject.toCryptoKey({\n name: 'ECDH',\n namedCurve,\n }, extractable, isPublic ? [] : ['deriveBits']);\n }\n }\n if (!cryptoKey) {\n throw new TypeError('given KeyObject instance cannot be used for this algorithm');\n }\n if (!cached) {\n cache.set(keyObject, { [alg]: cryptoKey });\n }\n else {\n cached[alg] = cryptoKey;\n }\n return cryptoKey;\n};\nexport async function normalizeKey(key, alg) {\n if (key instanceof Uint8Array) {\n return key;\n }\n if (isCryptoKey(key)) {\n return key;\n }\n if (isKeyObject(key)) {\n if (key.type === 'secret') {\n return key.export();\n }\n if ('toCryptoKey' in key && typeof key.toCryptoKey === 'function') {\n try {\n return handleKeyObject(key, alg);\n }\n catch (err) {\n if (err instanceof TypeError) {\n throw err;\n }\n }\n }\n let jwk = key.export({ format: 'jwk' });\n return handleJWK(key, jwk, alg);\n }\n if (isJWK(key)) {\n if (key.k) {\n return decode(key.k);\n }\n return handleJWK(key, key, alg, true);\n }\n throw new Error('unreachable');\n}\n","import { withAlg as invalidKeyInput } from './invalid_key_input.js';\nimport { isKeyLike } from './is_key_like.js';\nimport * as jwk from './is_jwk.js';\nconst tag = (key) => key?.[Symbol.toStringTag];\nconst jwkMatchesOp = (alg, key, usage) => {\n if (key.use !== undefined) {\n let expected;\n switch (usage) {\n case 'sign':\n case 'verify':\n expected = 'sig';\n break;\n case 'encrypt':\n case 'decrypt':\n expected = 'enc';\n break;\n }\n if (key.use !== expected) {\n throw new TypeError(`Invalid key for this operation, its \"use\" must be \"${expected}\" when present`);\n }\n }\n if (key.alg !== undefined && key.alg !== alg) {\n throw new TypeError(`Invalid key for this operation, its \"alg\" must be \"${alg}\" when present`);\n }\n if (Array.isArray(key.key_ops)) {\n let expectedKeyOp;\n switch (true) {\n case usage === 'sign' || usage === 'verify':\n case alg === 'dir':\n case alg.includes('CBC-HS'):\n expectedKeyOp = usage;\n break;\n case alg.startsWith('PBES2'):\n expectedKeyOp = 'deriveBits';\n break;\n case /^A\\d{3}(?:GCM)?(?:KW)?$/.test(alg):\n if (!alg.includes('GCM') && alg.endsWith('KW')) {\n expectedKeyOp = usage === 'encrypt' ? 'wrapKey' : 'unwrapKey';\n }\n else {\n expectedKeyOp = usage;\n }\n break;\n case usage === 'encrypt' && alg.startsWith('RSA'):\n expectedKeyOp = 'wrapKey';\n break;\n case usage === 'decrypt':\n expectedKeyOp = alg.startsWith('RSA') ? 'unwrapKey' : 'deriveBits';\n break;\n }\n if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) {\n throw new TypeError(`Invalid key for this operation, its \"key_ops\" must include \"${expectedKeyOp}\" when present`);\n }\n }\n return true;\n};\nconst symmetricTypeCheck = (alg, key, usage) => {\n if (key instanceof Uint8Array)\n return;\n if (jwk.isJWK(key)) {\n if (jwk.isSecretJWK(key) && jwkMatchesOp(alg, key, usage))\n return;\n throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK \"kty\" (Key Type) equal to \"oct\" and the JWK \"k\" (Key Value) present`);\n }\n if (!isKeyLike(key)) {\n throw new TypeError(invalidKeyInput(alg, key, 'CryptoKey', 'KeyObject', 'JSON Web Key', 'Uint8Array'));\n }\n if (key.type !== 'secret') {\n throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type \"secret\"`);\n }\n};\nconst asymmetricTypeCheck = (alg, key, usage) => {\n if (jwk.isJWK(key)) {\n switch (usage) {\n case 'decrypt':\n case 'sign':\n if (jwk.isPrivateJWK(key) && jwkMatchesOp(alg, key, usage))\n return;\n throw new TypeError(`JSON Web Key for this operation must be a private JWK`);\n case 'encrypt':\n case 'verify':\n if (jwk.isPublicJWK(key) && jwkMatchesOp(alg, key, usage))\n return;\n throw new TypeError(`JSON Web Key for this operation must be a public JWK`);\n }\n }\n if (!isKeyLike(key)) {\n throw new TypeError(invalidKeyInput(alg, key, 'CryptoKey', 'KeyObject', 'JSON Web Key'));\n }\n if (key.type === 'secret') {\n throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type \"secret\"`);\n }\n if (key.type === 'public') {\n switch (usage) {\n case 'sign':\n throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type \"private\"`);\n case 'decrypt':\n throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type \"private\"`);\n }\n }\n if (key.type === 'private') {\n switch (usage) {\n case 'verify':\n throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type \"public\"`);\n case 'encrypt':\n throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type \"public\"`);\n }\n }\n};\nexport function checkKeyType(alg, key, usage) {\n switch (alg.substring(0, 2)) {\n case 'A1':\n case 'A2':\n case 'di':\n case 'HS':\n case 'PB':\n symmetricTypeCheck(alg, key, usage);\n break;\n default:\n asymmetricTypeCheck(alg, key, usage);\n }\n}\n",null,"import { JOSENotSupported } from '../util/errors.js';\nexport function subtleAlgorithm(alg, algorithm) {\n const hash = `SHA-${alg.slice(-3)}`;\n switch (alg) {\n case 'HS256':\n case 'HS384':\n case 'HS512':\n return { hash, name: 'HMAC' };\n case 'PS256':\n case 'PS384':\n case 'PS512':\n return { hash, name: 'RSA-PSS', saltLength: parseInt(alg.slice(-3), 10) >> 3 };\n case 'RS256':\n case 'RS384':\n case 'RS512':\n return { hash, name: 'RSASSA-PKCS1-v1_5' };\n case 'ES256':\n case 'ES384':\n case 'ES512':\n return { hash, name: 'ECDSA', namedCurve: algorithm.namedCurve };\n case 'Ed25519':\n case 'EdDSA':\n return { name: 'Ed25519' };\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n return { name: alg };\n default:\n throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);\n }\n}\n","import { checkSigCryptoKey } from './crypto_key.js';\nimport { invalidKeyInput } from './invalid_key_input.js';\nexport async function getSigKey(alg, key, usage) {\n if (key instanceof Uint8Array) {\n if (!alg.startsWith('HS')) {\n throw new TypeError(invalidKeyInput(key, 'CryptoKey', 'KeyObject', 'JSON Web Key'));\n }\n return crypto.subtle.importKey('raw', key, { hash: `SHA-${alg.slice(-3)}`, name: 'HMAC' }, false, [usage]);\n }\n checkSigCryptoKey(key, alg, usage);\n return key;\n}\n","import { subtleAlgorithm } from './subtle_dsa.js';\nimport { checkKeyLength } from './check_key_length.js';\nimport { getSigKey } from './get_sign_verify_key.js';\nexport async function verify(alg, key, signature, data) {\n const cryptoKey = await getSigKey(alg, key, 'verify');\n checkKeyLength(alg, cryptoKey);\n const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm);\n try {\n return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);\n }\n catch {\n return false;\n }\n}\n","import { decode as b64u } from '../../util/base64url.js';\nimport { verify } from '../../lib/verify.js';\nimport { JOSEAlgNotAllowed, JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js';\nimport { concat, encoder, decoder, encode } from '../../lib/buffer_utils.js';\nimport { isDisjoint } from '../../lib/is_disjoint.js';\nimport { isObject } from '../../lib/is_object.js';\nimport { checkKeyType } from '../../lib/check_key_type.js';\nimport { validateCrit } from '../../lib/validate_crit.js';\nimport { validateAlgorithms } from '../../lib/validate_algorithms.js';\nimport { normalizeKey } from '../../lib/normalize_key.js';\nexport async function flattenedVerify(jws, key, options) {\n if (!isObject(jws)) {\n throw new JWSInvalid('Flattened JWS must be an object');\n }\n if (jws.protected === undefined && jws.header === undefined) {\n throw new JWSInvalid('Flattened JWS must have either of the \"protected\" or \"header\" members');\n }\n if (jws.protected !== undefined && typeof jws.protected !== 'string') {\n throw new JWSInvalid('JWS Protected Header incorrect type');\n }\n if (jws.payload === undefined) {\n throw new JWSInvalid('JWS Payload missing');\n }\n if (typeof jws.signature !== 'string') {\n throw new JWSInvalid('JWS Signature missing or incorrect type');\n }\n if (jws.header !== undefined && !isObject(jws.header)) {\n throw new JWSInvalid('JWS Unprotected Header incorrect type');\n }\n let parsedProt = {};\n if (jws.protected) {\n try {\n const protectedHeader = b64u(jws.protected);\n parsedProt = JSON.parse(decoder.decode(protectedHeader));\n }\n catch {\n throw new JWSInvalid('JWS Protected Header is invalid');\n }\n }\n if (!isDisjoint(parsedProt, jws.header)) {\n throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint');\n }\n const joseHeader = {\n ...parsedProt,\n ...jws.header,\n };\n const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options?.crit, parsedProt, joseHeader);\n let b64 = true;\n if (extensions.has('b64')) {\n b64 = parsedProt.b64;\n if (typeof b64 !== 'boolean') {\n throw new JWSInvalid('The \"b64\" (base64url-encode payload) Header Parameter must be a boolean');\n }\n }\n const { alg } = joseHeader;\n if (typeof alg !== 'string' || !alg) {\n throw new JWSInvalid('JWS \"alg\" (Algorithm) Header Parameter missing or invalid');\n }\n const algorithms = options && validateAlgorithms('algorithms', options.algorithms);\n if (algorithms && !algorithms.has(alg)) {\n throw new JOSEAlgNotAllowed('\"alg\" (Algorithm) Header Parameter value not allowed');\n }\n if (b64) {\n if (typeof jws.payload !== 'string') {\n throw new JWSInvalid('JWS Payload must be a string');\n }\n }\n else if (typeof jws.payload !== 'string' && !(jws.payload instanceof Uint8Array)) {\n throw new JWSInvalid('JWS Payload must be a string or an Uint8Array instance');\n }\n let resolvedKey = false;\n if (typeof key === 'function') {\n key = await key(parsedProt, jws);\n resolvedKey = true;\n }\n checkKeyType(alg, key, 'verify');\n const data = concat(jws.protected !== undefined ? encode(jws.protected) : new Uint8Array(), encode('.'), typeof jws.payload === 'string'\n ? b64\n ? encode(jws.payload)\n : encoder.encode(jws.payload)\n : jws.payload);\n let signature;\n try {\n signature = b64u(jws.signature);\n }\n catch {\n throw new JWSInvalid('Failed to base64url decode the signature');\n }\n const k = await normalizeKey(key, alg);\n const verified = await verify(alg, k, signature, data);\n if (!verified) {\n throw new JWSSignatureVerificationFailed();\n }\n let payload;\n if (b64) {\n try {\n payload = b64u(jws.payload);\n }\n catch {\n throw new JWSInvalid('Failed to base64url decode the payload');\n }\n }\n else if (typeof jws.payload === 'string') {\n payload = encoder.encode(jws.payload);\n }\n else {\n payload = jws.payload;\n }\n const result = { payload };\n if (jws.protected !== undefined) {\n result.protectedHeader = parsedProt;\n }\n if (jws.header !== undefined) {\n result.unprotectedHeader = jws.header;\n }\n if (resolvedKey) {\n return { ...result, key: k };\n }\n return result;\n}\n","import { flattenedVerify } from '../flattened/verify.js';\nimport { JWSInvalid } from '../../util/errors.js';\nimport { decoder } from '../../lib/buffer_utils.js';\nexport async function compactVerify(jws, key, options) {\n if (jws instanceof Uint8Array) {\n jws = decoder.decode(jws);\n }\n if (typeof jws !== 'string') {\n throw new JWSInvalid('Compact JWS must be a string or Uint8Array');\n }\n const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.');\n if (length !== 3) {\n throw new JWSInvalid('Invalid Compact JWS');\n }\n const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options);\n const result = { payload: verified.payload, protectedHeader: verified.protectedHeader };\n if (typeof key === 'function') {\n return { ...result, key: verified.key };\n }\n return result;\n}\n","import { JWTClaimValidationFailed, JWTExpired, JWTInvalid } from '../util/errors.js';\nimport { encoder, decoder } from './buffer_utils.js';\nimport { isObject } from './is_object.js';\nconst epoch = (date) => Math.floor(date.getTime() / 1000);\nconst minute = 60;\nconst hour = minute * 60;\nconst day = hour * 24;\nconst week = day * 7;\nconst year = day * 365.25;\nconst REGEX = /^(\\+|\\-)? ?(\\d+|\\d+\\.\\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;\nexport function secs(str) {\n const matched = REGEX.exec(str);\n if (!matched || (matched[4] && matched[1])) {\n throw new TypeError('Invalid time period format');\n }\n const value = parseFloat(matched[2]);\n const unit = matched[3].toLowerCase();\n let numericDate;\n switch (unit) {\n case 'sec':\n case 'secs':\n case 'second':\n case 'seconds':\n case 's':\n numericDate = Math.round(value);\n break;\n case 'minute':\n case 'minutes':\n case 'min':\n case 'mins':\n case 'm':\n numericDate = Math.round(value * minute);\n break;\n case 'hour':\n case 'hours':\n case 'hr':\n case 'hrs':\n case 'h':\n numericDate = Math.round(value * hour);\n break;\n case 'day':\n case 'days':\n case 'd':\n numericDate = Math.round(value * day);\n break;\n case 'week':\n case 'weeks':\n case 'w':\n numericDate = Math.round(value * week);\n break;\n default:\n numericDate = Math.round(value * year);\n break;\n }\n if (matched[1] === '-' || matched[4] === 'ago') {\n return -numericDate;\n }\n return numericDate;\n}\nfunction validateInput(label, input) {\n if (!Number.isFinite(input)) {\n throw new TypeError(`Invalid ${label} input`);\n }\n return input;\n}\nconst normalizeTyp = (value) => {\n if (value.includes('/')) {\n return value.toLowerCase();\n }\n return `application/${value.toLowerCase()}`;\n};\nconst checkAudiencePresence = (audPayload, audOption) => {\n if (typeof audPayload === 'string') {\n return audOption.includes(audPayload);\n }\n if (Array.isArray(audPayload)) {\n return audOption.some(Set.prototype.has.bind(new Set(audPayload)));\n }\n return false;\n};\nexport function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {\n let payload;\n try {\n payload = JSON.parse(decoder.decode(encodedPayload));\n }\n catch {\n }\n if (!isObject(payload)) {\n throw new JWTInvalid('JWT Claims Set must be a top-level JSON object');\n }\n const { typ } = options;\n if (typ &&\n (typeof protectedHeader.typ !== 'string' ||\n normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) {\n throw new JWTClaimValidationFailed('unexpected \"typ\" JWT header value', payload, 'typ', 'check_failed');\n }\n const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;\n const presenceCheck = [...requiredClaims];\n if (maxTokenAge !== undefined)\n presenceCheck.push('iat');\n if (audience !== undefined)\n presenceCheck.push('aud');\n if (subject !== undefined)\n presenceCheck.push('sub');\n if (issuer !== undefined)\n presenceCheck.push('iss');\n for (const claim of new Set(presenceCheck.reverse())) {\n if (!(claim in payload)) {\n throw new JWTClaimValidationFailed(`missing required \"${claim}\" claim`, payload, claim, 'missing');\n }\n }\n if (issuer &&\n !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) {\n throw new JWTClaimValidationFailed('unexpected \"iss\" claim value', payload, 'iss', 'check_failed');\n }\n if (subject && payload.sub !== subject) {\n throw new JWTClaimValidationFailed('unexpected \"sub\" claim value', payload, 'sub', 'check_failed');\n }\n if (audience &&\n !checkAudiencePresence(payload.aud, typeof audience === 'string' ? [audience] : audience)) {\n throw new JWTClaimValidationFailed('unexpected \"aud\" claim value', payload, 'aud', 'check_failed');\n }\n let tolerance;\n switch (typeof options.clockTolerance) {\n case 'string':\n tolerance = secs(options.clockTolerance);\n break;\n case 'number':\n tolerance = options.clockTolerance;\n break;\n case 'undefined':\n tolerance = 0;\n break;\n default:\n throw new TypeError('Invalid clockTolerance option type');\n }\n const { currentDate } = options;\n const now = epoch(currentDate || new Date());\n if ((payload.iat !== undefined || maxTokenAge) && typeof payload.iat !== 'number') {\n throw new JWTClaimValidationFailed('\"iat\" claim must be a number', payload, 'iat', 'invalid');\n }\n if (payload.nbf !== undefined) {\n if (typeof payload.nbf !== 'number') {\n throw new JWTClaimValidationFailed('\"nbf\" claim must be a number', payload, 'nbf', 'invalid');\n }\n if (payload.nbf > now + tolerance) {\n throw new JWTClaimValidationFailed('\"nbf\" claim timestamp check failed', payload, 'nbf', 'check_failed');\n }\n }\n if (payload.exp !== undefined) {\n if (typeof payload.exp !== 'number') {\n throw new JWTClaimValidationFailed('\"exp\" claim must be a number', payload, 'exp', 'invalid');\n }\n if (payload.exp <= now - tolerance) {\n throw new JWTExpired('\"exp\" claim timestamp check failed', payload, 'exp', 'check_failed');\n }\n }\n if (maxTokenAge) {\n const age = now - payload.iat;\n const max = typeof maxTokenAge === 'number' ? maxTokenAge : secs(maxTokenAge);\n if (age - tolerance > max) {\n throw new JWTExpired('\"iat\" claim timestamp check failed (too far in the past)', payload, 'iat', 'check_failed');\n }\n if (age < 0 - tolerance) {\n throw new JWTClaimValidationFailed('\"iat\" claim timestamp check failed (it should be in the past)', payload, 'iat', 'check_failed');\n }\n }\n return payload;\n}\nexport class JWTClaimsBuilder {\n #payload;\n constructor(payload) {\n if (!isObject(payload)) {\n throw new TypeError('JWT Claims Set MUST be an object');\n }\n this.#payload = structuredClone(payload);\n }\n data() {\n return encoder.encode(JSON.stringify(this.#payload));\n }\n get iss() {\n return this.#payload.iss;\n }\n set iss(value) {\n this.#payload.iss = value;\n }\n get sub() {\n return this.#payload.sub;\n }\n set sub(value) {\n this.#payload.sub = value;\n }\n get aud() {\n return this.#payload.aud;\n }\n set aud(value) {\n this.#payload.aud = value;\n }\n set jti(value) {\n this.#payload.jti = value;\n }\n set nbf(value) {\n if (typeof value === 'number') {\n this.#payload.nbf = validateInput('setNotBefore', value);\n }\n else if (value instanceof Date) {\n this.#payload.nbf = validateInput('setNotBefore', epoch(value));\n }\n else {\n this.#payload.nbf = epoch(new Date()) + secs(value);\n }\n }\n set exp(value) {\n if (typeof value === 'number') {\n this.#payload.exp = validateInput('setExpirationTime', value);\n }\n else if (value instanceof Date) {\n this.#payload.exp = validateInput('setExpirationTime', epoch(value));\n }\n else {\n this.#payload.exp = epoch(new Date()) + secs(value);\n }\n }\n set iat(value) {\n if (value === undefined) {\n this.#payload.iat = epoch(new Date());\n }\n else if (value instanceof Date) {\n this.#payload.iat = validateInput('setIssuedAt', epoch(value));\n }\n else if (typeof value === 'string') {\n this.#payload.iat = validateInput('setIssuedAt', epoch(new Date()) + secs(value));\n }\n else {\n this.#payload.iat = validateInput('setIssuedAt', value);\n }\n }\n}\n","import { compactVerify } from '../jws/compact/verify.js';\nimport { validateClaimsSet } from '../lib/jwt_claims_set.js';\nimport { JWTInvalid } from '../util/errors.js';\nexport async function jwtVerify(jwt, key, options) {\n const verified = await compactVerify(jwt, key, options);\n if (verified.protectedHeader.crit?.includes('b64') && verified.protectedHeader.b64 === false) {\n throw new JWTInvalid('JWTs MUST NOT use unencoded payload');\n }\n const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options);\n const result = { payload, protectedHeader: verified.protectedHeader };\n if (typeof key === 'function') {\n return { ...result, key: verified.key };\n }\n return result;\n}\n","import { importJWK } from '../key/import.js';\nimport { JWKSInvalid, JOSENotSupported, JWKSNoMatchingKey, JWKSMultipleMatchingKeys, } from '../util/errors.js';\nimport { isObject } from '../lib/is_object.js';\nfunction getKtyFromAlg(alg) {\n switch (typeof alg === 'string' && alg.slice(0, 2)) {\n case 'RS':\n case 'PS':\n return 'RSA';\n case 'ES':\n return 'EC';\n case 'Ed':\n return 'OKP';\n case 'ML':\n return 'AKP';\n default:\n throw new JOSENotSupported('Unsupported \"alg\" value for a JSON Web Key Set');\n }\n}\nfunction isJWKSLike(jwks) {\n return (jwks &&\n typeof jwks === 'object' &&\n Array.isArray(jwks.keys) &&\n jwks.keys.every(isJWKLike));\n}\nfunction isJWKLike(key) {\n return isObject(key);\n}\nclass LocalJWKSet {\n #jwks;\n #cached = new WeakMap();\n constructor(jwks) {\n if (!isJWKSLike(jwks)) {\n throw new JWKSInvalid('JSON Web Key Set malformed');\n }\n this.#jwks = structuredClone(jwks);\n }\n jwks() {\n return this.#jwks;\n }\n async getKey(protectedHeader, token) {\n const { alg, kid } = { ...protectedHeader, ...token?.header };\n const kty = getKtyFromAlg(alg);\n const candidates = this.#jwks.keys.filter((jwk) => {\n let candidate = kty === jwk.kty;\n if (candidate && typeof kid === 'string') {\n candidate = kid === jwk.kid;\n }\n if (candidate && (typeof jwk.alg === 'string' || kty === 'AKP')) {\n candidate = alg === jwk.alg;\n }\n if (candidate && typeof jwk.use === 'string') {\n candidate = jwk.use === 'sig';\n }\n if (candidate && Array.isArray(jwk.key_ops)) {\n candidate = jwk.key_ops.includes('verify');\n }\n if (candidate) {\n switch (alg) {\n case 'ES256':\n candidate = jwk.crv === 'P-256';\n break;\n case 'ES384':\n candidate = jwk.crv === 'P-384';\n break;\n case 'ES512':\n candidate = jwk.crv === 'P-521';\n break;\n case 'Ed25519':\n case 'EdDSA':\n candidate = jwk.crv === 'Ed25519';\n break;\n }\n }\n return candidate;\n });\n const { 0: jwk, length } = candidates;\n if (length === 0) {\n throw new JWKSNoMatchingKey();\n }\n if (length !== 1) {\n const error = new JWKSMultipleMatchingKeys();\n const _cached = this.#cached;\n error[Symbol.asyncIterator] = async function* () {\n for (const jwk of candidates) {\n try {\n yield await importWithAlgCache(_cached, jwk, alg);\n }\n catch { }\n }\n };\n throw error;\n }\n return importWithAlgCache(this.#cached, jwk, alg);\n }\n}\nasync function importWithAlgCache(cache, jwk, alg) {\n const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk);\n if (cached[alg] === undefined) {\n const key = await importJWK({ ...jwk, ext: true }, alg);\n if (key instanceof Uint8Array || key.type !== 'public') {\n throw new JWKSInvalid('JSON Web Key Set members must be public keys');\n }\n cached[alg] = key;\n }\n return cached[alg];\n}\nexport function createLocalJWKSet(jwks) {\n const set = new LocalJWKSet(jwks);\n const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);\n Object.defineProperties(localJWKSet, {\n jwks: {\n value: () => structuredClone(set.jwks()),\n enumerable: false,\n configurable: false,\n writable: false,\n },\n });\n return localJWKSet;\n}\n","import { JOSEError, JWKSNoMatchingKey, JWKSTimeout } from '../util/errors.js';\nimport { createLocalJWKSet } from './local.js';\nimport { isObject } from '../lib/is_object.js';\nfunction isCloudflareWorkers() {\n return (typeof WebSocketPair !== 'undefined' ||\n (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') ||\n (typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel'));\n}\nlet USER_AGENT;\nif (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) {\n const NAME = 'jose';\n const VERSION = 'v6.1.3';\n USER_AGENT = `${NAME}/${VERSION}`;\n}\nexport const customFetch = Symbol();\nasync function fetchJwks(url, headers, signal, fetchImpl = fetch) {\n const response = await fetchImpl(url, {\n method: 'GET',\n signal,\n redirect: 'manual',\n headers,\n }).catch((err) => {\n if (err.name === 'TimeoutError') {\n throw new JWKSTimeout();\n }\n throw err;\n });\n if (response.status !== 200) {\n throw new JOSEError('Expected 200 OK from the JSON Web Key Set HTTP response');\n }\n try {\n return await response.json();\n }\n catch {\n throw new JOSEError('Failed to parse the JSON Web Key Set HTTP response as JSON');\n }\n}\nexport const jwksCache = Symbol();\nfunction isFreshJwksCache(input, cacheMaxAge) {\n if (typeof input !== 'object' || input === null) {\n return false;\n }\n if (!('uat' in input) || typeof input.uat !== 'number' || Date.now() - input.uat >= cacheMaxAge) {\n return false;\n }\n if (!('jwks' in input) ||\n !isObject(input.jwks) ||\n !Array.isArray(input.jwks.keys) ||\n !Array.prototype.every.call(input.jwks.keys, isObject)) {\n return false;\n }\n return true;\n}\nclass RemoteJWKSet {\n #url;\n #timeoutDuration;\n #cooldownDuration;\n #cacheMaxAge;\n #jwksTimestamp;\n #pendingFetch;\n #headers;\n #customFetch;\n #local;\n #cache;\n constructor(url, options) {\n if (!(url instanceof URL)) {\n throw new TypeError('url must be an instance of URL');\n }\n this.#url = new URL(url.href);\n this.#timeoutDuration =\n typeof options?.timeoutDuration === 'number' ? options?.timeoutDuration : 5000;\n this.#cooldownDuration =\n typeof options?.cooldownDuration === 'number' ? options?.cooldownDuration : 30000;\n this.#cacheMaxAge = typeof options?.cacheMaxAge === 'number' ? options?.cacheMaxAge : 600000;\n this.#headers = new Headers(options?.headers);\n if (USER_AGENT && !this.#headers.has('User-Agent')) {\n this.#headers.set('User-Agent', USER_AGENT);\n }\n if (!this.#headers.has('accept')) {\n this.#headers.set('accept', 'application/json');\n this.#headers.append('accept', 'application/jwk-set+json');\n }\n this.#customFetch = options?.[customFetch];\n if (options?.[jwksCache] !== undefined) {\n this.#cache = options?.[jwksCache];\n if (isFreshJwksCache(options?.[jwksCache], this.#cacheMaxAge)) {\n this.#jwksTimestamp = this.#cache.uat;\n this.#local = createLocalJWKSet(this.#cache.jwks);\n }\n }\n }\n pendingFetch() {\n return !!this.#pendingFetch;\n }\n coolingDown() {\n return typeof this.#jwksTimestamp === 'number'\n ? Date.now() < this.#jwksTimestamp + this.#cooldownDuration\n : false;\n }\n fresh() {\n return typeof this.#jwksTimestamp === 'number'\n ? Date.now() < this.#jwksTimestamp + this.#cacheMaxAge\n : false;\n }\n jwks() {\n return this.#local?.jwks();\n }\n async getKey(protectedHeader, token) {\n if (!this.#local || !this.fresh()) {\n await this.reload();\n }\n try {\n return await this.#local(protectedHeader, token);\n }\n catch (err) {\n if (err instanceof JWKSNoMatchingKey) {\n if (this.coolingDown() === false) {\n await this.reload();\n return this.#local(protectedHeader, token);\n }\n }\n throw err;\n }\n }\n async reload() {\n if (this.#pendingFetch && isCloudflareWorkers()) {\n this.#pendingFetch = undefined;\n }\n this.#pendingFetch ||= fetchJwks(this.#url.href, this.#headers, AbortSignal.timeout(this.#timeoutDuration), this.#customFetch)\n .then((json) => {\n this.#local = createLocalJWKSet(json);\n if (this.#cache) {\n this.#cache.uat = Date.now();\n this.#cache.jwks = json;\n }\n this.#jwksTimestamp = Date.now();\n this.#pendingFetch = undefined;\n })\n .catch((err) => {\n this.#pendingFetch = undefined;\n throw err;\n });\n await this.#pendingFetch;\n }\n}\nexport function createRemoteJWKSet(url, options) {\n const set = new RemoteJWKSet(url, options);\n const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);\n Object.defineProperties(remoteJWKSet, {\n coolingDown: {\n get: () => set.coolingDown(),\n enumerable: true,\n configurable: false,\n },\n fresh: {\n get: () => set.fresh(),\n enumerable: true,\n configurable: false,\n },\n reload: {\n value: () => set.reload(),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n reloading: {\n get: () => set.pendingFetch(),\n enumerable: true,\n configurable: false,\n },\n jwks: {\n value: () => set.jwks(),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n });\n return remoteJWKSet;\n}\n","/**\n * Interface to represent an OAuth2 error.\n */\nexport interface OAuth2Error {\n error: string;\n error_description: string;\n message?: string;\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 };\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 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(\n 'build_authorization_url_error',\n 'There was an error when trying to build the authorization URL.',\n cause\n );\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(\n 'build_link_user_url_error',\n 'There was an error when trying to build the Link User URL.',\n cause\n );\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(\n 'build_unlink_user_url_error',\n 'There was an error when trying to build the Unlink User URL.',\n cause\n );\n this.name = 'BuildUnlinkUserUrlError';\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(\n 'The client secret or client assertion signing key must be provided.'\n );\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>(\n value: T\n): Partial<T> {\n return Object.entries(value)\n .filter(([, value]) => typeof value !== 'undefined')\n .reduce((acc, curr) => ({ ...acc, [curr[0]]: curr[1] }), {});\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","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 };\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 type {\n MfaClientOptions,\n AuthenticatorResponse,\n AuthenticatorApiResponse,\n ListAuthenticatorsOptions,\n DeleteAuthenticatorOptions,\n EnrollAuthenticatorOptions,\n EnrollmentResponse,\n EnrollmentApiResponse,\n ChallengeOptions,\n ChallengeResponse,\n ChallengeApiResponse,\n} from './types.js';\nimport {\n MfaListAuthenticatorsError,\n MfaEnrollmentError,\n MfaDeleteAuthenticatorError,\n MfaChallengeError,\n type MfaApiErrorResponse,\n} from './errors.js';\nimport {\n transformAuthenticatorResponse,\n transformEnrollmentResponse,\n transformChallengeResponse,\n} from './utils.js';\n\n\nexport class MfaClient {\n #baseUrl: string;\n #clientId: string;\n #customFetch: typeof fetch;\n\n /**\n * @internal\n */\n constructor(options: MfaClientOptions) {\n this.#baseUrl = `https://${options.domain}`;\n this.#clientId = options.clientId;\n this.#customFetch = options.customFetch ?? ((...args) => fetch(...args));\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 const error = (await response.json()) as MfaApiErrorResponse;\n throw new MfaListAuthenticatorsError(\n error.error_description || 'Failed to list authenticators',\n error\n );\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 const error = (await response.json()) as MfaApiErrorResponse;\n throw new MfaEnrollmentError(\n error.error_description || 'Failed to enroll authenticator',\n error\n );\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 const error = (await response.json()) as MfaApiErrorResponse;\n throw new MfaDeleteAuthenticatorError(\n error.error_description || 'Failed to delete authenticator',\n error\n );\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 (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 const error = (await response.json()) as MfaApiErrorResponse;\n throw new MfaChallengeError(\n error.error_description || 'Failed to challenge authenticator',\n error\n );\n }\n\n const apiResponse = (await response.json()) as ChallengeApiResponse;\n return transformChallengeResponse(apiResponse);\n }\n}\n","import {\n IDToken,\n TokenEndpointResponse,\n TokenEndpointResponseHelpers,\n} from 'openid-client';\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 * 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\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\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 * 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?:\n | 'urn:ietf:params:oauth:token-type:access_token'\n | '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 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 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(\n response: TokenEndpointResponse & TokenEndpointResponseHelpers\n ): 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 = (\n response as typeof response & { issued_token_type?: string }\n ).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 * as client from 'openid-client';\nimport { createRemoteJWKSet, importPKCS8, jwtVerify, customFetch } from 'jose';\nimport {\n BackchannelAuthenticationError,\n BuildAuthorizationUrlError,\n BuildLinkUserUrlError,\n BuildUnlinkUserUrlError,\n TokenExchangeError,\n MissingClientAuthError,\n NotSupportedError,\n NotSupportedErrorCode,\n OAuth2Error,\n TokenByClientCredentialsError,\n TokenByCodeError,\n TokenByRefreshTokenError,\n TokenForConnectionError,\n VerifyLogoutTokenError,\n} from './errors.js';\nimport { stripUndefinedProperties } from './utils.js';\nimport { MfaClient } from './mfa/mfa-client.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 TokenByRefreshTokenOptions,\n TokenForConnectionOptions,\n TokenResponse,\n VerifyLogoutTokenOptions,\n VerifyLogoutTokenResult,\n} from './types.js';\n\nconst DEFAULT_SCOPES = 'openid profile email offline_access';\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 * - requested_token_type: Determines the type of token returned, must be explicit\n * - actor_token, actor_token_type: Delegation parameters that affect authorization context\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(\n 'subject_token must not include leading or trailing whitespace'\n );\n }\n // Very common copy paste mistake (case-insensitive check)\n if (/^bearer\\s+/i.test(token)) {\n throw new TokenExchangeError(\n \"subject_token must not include the 'Bearer ' prefix\"\n );\n }\n}\n\n/**\n * Appends extra parameters to URLSearchParams while enforcing security constraints.\n */\nfunction appendExtraParams(\n params: URLSearchParams,\n extra?: Record<string, string | string[]>\n): 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 =\n '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 =\n '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 * 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 readonly #options: AuthClientOptions;\n #jwks?: ReturnType<typeof createRemoteJWKSet>;\n public mfa: MfaClient;\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 this.mfa = new MfaClient({\n domain: this.#options.domain,\n clientId: this.#options.clientId,\n customFetch: this.#options.customFetch,\n });\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 clientAuth = await this.#getClientAuth();\n\n this.#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.#options.customFetch, \n }\n );\n\n this.#serverMetadata = this.#configuration.serverMetadata();\n this.#configuration[client.customFetch] =\n this.#options.customFetch || fetch;\n\n return {\n configuration: this.#configuration,\n serverMetadata: this.#serverMetadata,\n };\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(\n options?: BuildAuthorizationUrlOptions\n ): Promise<BuildAuthorizationUrlResult> {\n const { serverMetadata } = await this.#discover();\n\n if (\n options?.pushedAuthorizationRequests &&\n !serverMetadata.pushed_authorization_request_endpoint\n ) {\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(\n options: BuildLinkUserUrlOptions\n ): 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(\n options: BuildUnlinkUserUrlOptions\n ): 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(\n options: BackchannelAuthenticationOptions\n ): 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(\n 'authorization_details',\n JSON.stringify(options.authorizationDetails)\n );\n }\n\n try {\n const backchannelAuthenticationResponse =\n await client.initiateBackchannelAuthentication(configuration, params);\n\n const tokenEndpointResponse =\n 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(\n 'authorization_details',\n JSON.stringify(options.authorizationDetails)\n );\n }\n\n try {\n const backchannelAuthenticationResponse =\n 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(\n options: TokenForConnectionOptions\n ): Promise<TokenResponse> {\n if (options.refreshToken && options.accessToken) {\n throw new TokenForConnectionError(\n 'Either a refresh or access token should be specified, but not both.'\n );\n }\n\n const subjectTokenValue = options.accessToken ?? options.refreshToken;\n if (!subjectTokenValue) {\n throw new TokenForConnectionError(\n 'Either a refresh or access token must be specified.'\n );\n }\n\n try {\n return await this.exchangeToken({\n connection: options.connection,\n subjectToken: subjectTokenValue,\n subjectTokenType: options.accessToken\n ? SUBJECT_TYPE_ACCESS_TOKEN\n : 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(\n options: TokenVaultExchangeOptions\n ): Promise<TokenResponse> {\n const { configuration } = await this.#discover();\n\n if ('audience' in options || 'resource' in options) {\n throw new TokenExchangeError(\n 'audience and resource parameters are not supported for Token Vault exchanges'\n );\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:\n options.subjectTokenType ?? SUBJECT_TYPE_ACCESS_TOKEN,\n requested_token_type:\n options.requestedTokenType ??\n 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 e as OAuth2Error\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(\n options: ExchangeProfileOptions\n ): Promise<TokenResponse> {\n const { configuration } = await this.#discover();\n\n validateSubjectToken(options.subjectToken);\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\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 return TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);\n } catch (e) {\n throw new TokenExchangeError(\n `Failed to exchange token of type '${options.subjectTokenType}'${options.audience ? ` for audience '${options.audience}'` : ''}.`,\n e as OAuth2Error\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(\n options: ExchangeProfileOptions | TokenVaultExchangeOptions\n ): Promise<TokenResponse> {\n return 'connection' in options\n ? this.#exchangeTokenVaultToken(options)\n : 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(\n url: URL,\n options: TokenByCodeOptions\n ): Promise<TokenResponse> {\n const { configuration } = await this.#discover();\n try {\n const tokenEndpointResponse = await client.authorizationCodeGrant(\n configuration,\n url,\n {\n pkceCodeVerifier: options.codeVerifier,\n }\n );\n\n return TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);\n } catch (e) {\n throw new TokenByCodeError(\n 'There was an error while trying to request a token.',\n e as OAuth2Error\n );\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 try {\n const tokenEndpointResponse = await client.refreshTokenGrant(\n configuration,\n options.refreshToken\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 e as OAuth2Error\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(\n options: TokenByClientCredentialsOptions\n ): 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(\n configuration,\n params\n );\n\n return TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);\n } catch (e) {\n throw new TokenByClientCredentialsError(\n 'There was an error while trying to request a token.',\n e as OAuth2Error\n );\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(\n options: VerifyLogoutTokenOptions\n ): Promise<VerifyLogoutTokenResult> {\n const { serverMetadata } = await this.#discover();\n this.#jwks ||= createRemoteJWKSet(new URL(serverMetadata!.jwks_uri!), {\n [customFetch]: this.#options.customFetch,\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(\n 'either \"sid\" or \"sub\" (or both) claims must be present'\n );\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 (\n !('http://schemas.openid.net/event/backchannel-logout' in payload.events)\n ) {\n throw new VerifyLogoutTokenError(\n '\"http://schemas.openid.net/event/backchannel-logout\" member is missing in the \"events\" claim'\n );\n }\n\n if (\n typeof payload.events[\n 'http://schemas.openid.net/event/backchannel-logout'\n ] !== 'object'\n ) {\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 (\n !this.#options.clientSecret &&\n !this.#options.clientAssertionSigningKey &&\n !this.#options.useMtls\n ) {\n throw new MissingClientAuthError();\n }\n\n if (this.#options.useMtls) {\n return client.TlsClientAuth();\n }\n\n let clientPrivateKey = this.#options.clientAssertionSigningKey as\n | CryptoKey\n | 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 }\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(\n options?: BuildAuthorizationUrlOptions\n ): 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","import { MfaApiErrorResponse } from '@auth0/auth0-auth-js';\nimport { GenericError } from '../errors';\n\n/**\n * Base class for MFA-related errors in auth0-spa-js.\n * Extends GenericError for unified error hierarchy across the SDK.\n */\nexport class MfaError extends GenericError {\n constructor(error: string, error_description: string) {\n super(error, error_description);\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, MfaError.prototype);\n }\n\n static fromPayload({\n error,\n error_description\n }: {\n error: string;\n error_description: string;\n }) {\n return new MfaError(error, error_description);\n }\n}\n\n/**\n * Error thrown when listing MFA authenticators fails.\n *\n * @example\n * ```typescript\n * try {\n * const authenticators = await mfa.getAuthenticators();\n * } catch (error) {\n * if (error instanceof MfaListAuthenticatorsError) {\n * console.log(error.error); // 'access_denied'\n * console.log(error.error_description); // 'Unauthorized'\n * }\n * }\n * ```\n */\nexport class MfaListAuthenticatorsError extends MfaError {\n constructor(error: string, error_description: string) {\n super(error, error_description);\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, MfaListAuthenticatorsError.prototype);\n }\n}\n\n/**\n * Error thrown when enrolling an MFA authenticator fails.\n *\n * @example\n * ```typescript\n * try {\n * const enrollment = await mfa.enroll({\n * authenticator_types: ['otp']\n * });\n * } catch (error) {\n * if (error instanceof MfaEnrollmentError) {\n * console.log(error.error); // 'invalid_phone_number'\n * console.log(error.error_description); // 'Invalid phone number format'\n * }\n * }\n * ```\n */\nexport class MfaEnrollmentError extends MfaError {\n constructor(error: string, error_description: string) {\n super(error, error_description);\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, MfaEnrollmentError.prototype);\n }\n}\n\n/**\n * Error thrown when initiating an MFA challenge fails.\n *\n * @example\n * ```typescript\n * try {\n * const challenge = await mfa.challenge({\n * mfaToken: mfaToken,\n * challengeType: 'otp',\n * authenticatorId: 'otp|dev_123'\n * });\n * } catch (error) {\n * if (error instanceof MfaChallengeError) {\n * console.log(error.error); // 'too_many_attempts'\n * console.log(error.error_description); // 'Rate limit exceeded'\n * }\n * }\n * ```\n */\nexport class MfaChallengeError extends MfaError {\n constructor(error: string, error_description: string) {\n super(error, error_description);\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, MfaChallengeError.prototype);\n }\n}\n\n/**\n * Error thrown when verifying an MFA challenge fails.\n *\n * @example\n * ```typescript\n * try {\n * const tokens = await mfa.verify({\n * mfaToken: mfaToken,\n * grant_type: 'http://auth0.com/oauth/grant-type/mfa-otp',\n * otp: '123456'\n * });\n * } catch (error) {\n * if (error instanceof MfaVerifyError) {\n * console.log(error.error); // 'invalid_otp' or 'context_not_found'\n * console.log(error.error_description); // Error details\n * }\n * }\n * ```\n */\nexport class MfaVerifyError extends MfaError {\n constructor(error: string, error_description: string) {\n super(error, error_description);\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, MfaVerifyError.prototype);\n }\n}\n\n/**\n * Error thrown when getting enrollment factors fails.\n *\n * @example\n * ```typescript\n * try {\n * const factors = await mfa.getEnrollmentFactors(mfaToken);\n * } catch (error) {\n * if (error instanceof MfaEnrollmentFactorsError) {\n * console.log(error.error); // 'mfa_context_not_found'\n * console.log(error.error_description); // 'MFA context not found...'\n * }\n * }\n * ```\n */\nexport class MfaEnrollmentFactorsError extends MfaError {\n constructor(error: string, error_description: string) {\n super(error, error_description);\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, MfaEnrollmentFactorsError.prototype);\n }\n}\n\n/**\n * Re-export MfaApiErrorResponse type for convenience\n */\nexport type { MfaApiErrorResponse };\n","import { MfaRequirements } from '../errors';\n\n/**\n * Represents the stored context for an MFA flow\n */\nexport interface MfaContext {\n /** The OAuth scope for the original token request */\n scope?: string;\n /** The API audience for the original token request */\n audience?: string;\n /** MFA requirements from the mfa_required error (camelCase for TypeScript conventions) */\n mfaRequirements?: MfaRequirements;\n /** Timestamp when the context was created */\n createdAt: number;\n}\n\n/**\n * Default TTL for MFA contexts in milliseconds (10 minutes)\n * This aligns with typical MFA token expiration times\n */\nconst DEFAULT_TTL_MS = 10 * 60 * 1000;\n\n/**\n * Manages MFA authentication contexts keyed by MFA token.\n *\n * When an mfa_required error occurs, the SDK stores the original request's\n * scope and audience. When the user later provides an MFA token for verification,\n * the SDK retrieves the matching context to complete the token exchange.\n *\n * This enables concurrent MFA flows without state conflicts.\n *\n * @example\n * ```typescript\n * const manager = new MfaContextManager();\n *\n * // Store context when mfa_required error occurs\n * manager.set('mfaTokenAbc', { scope: 'openid profile', audience: 'https://api.example.com' });\n *\n * // Retrieve context when user completes MFA\n * const context = manager.get('mfaTokenAbc');\n * // { scope: 'openid profile', audience: 'https://api.example.com', createdAt: ... }\n *\n * // Remove after successful verification\n * manager.remove('mfaTokenAbc');\n * ```\n */\nexport class MfaContextManager {\n private contexts: Map<string, MfaContext> = new Map();\n private readonly ttlMs: number;\n\n /**\n * Creates a new MfaContextManager\n * @param ttlMs - Time-to-live for contexts in milliseconds (default: 10 minutes)\n */\n constructor(ttlMs: number = DEFAULT_TTL_MS) {\n this.ttlMs = ttlMs;\n }\n\n /**\n * Stores an MFA context keyed by the MFA token.\n * Runs cleanup to remove expired entries before storing.\n *\n * @param mfaToken - The MFA token from the mfa_required error\n * @param context - The scope and audience from the original request\n */\n public set(\n mfaToken: string,\n context: Omit<MfaContext, 'createdAt'>\n ): void {\n this.cleanup();\n this.contexts.set(mfaToken, {\n ...context,\n createdAt: Date.now()\n });\n }\n\n /**\n * Retrieves the MFA context for a given token.\n * Returns undefined if the token is not found or has expired.\n *\n * @param mfaToken - The MFA token to look up\n * @returns The stored context, or undefined if not found/expired\n */\n public get(mfaToken: string): MfaContext | undefined {\n const context = this.contexts.get(mfaToken);\n if (!context) {\n return undefined;\n }\n\n // Check if expired\n if (Date.now() - context.createdAt > this.ttlMs) {\n this.contexts.delete(mfaToken);\n return undefined;\n }\n\n return context;\n }\n\n /**\n * Removes an MFA context.\n * Should be called after successful MFA verification.\n *\n * @param mfaToken - The MFA token to remove\n */\n public remove(mfaToken: string): void {\n this.contexts.delete(mfaToken);\n }\n\n /**\n * Removes all expired contexts from the Map.\n * Called automatically on every `set` operation.\n */\n private cleanup(): void {\n const now = Date.now();\n for (const [key, value] of this.contexts) {\n if (now - value.createdAt > this.ttlMs) {\n this.contexts.delete(key);\n }\n }\n }\n\n /**\n * Returns the number of stored contexts\n */\n public get size(): number {\n return this.contexts.size;\n }\n}\n","import { Auth0Client } from '../Auth0Client';\nimport type { TokenEndpointResponse } from '../global';\nimport type {\n Authenticator,\n EnrollParams,\n EnrollmentResponse,\n ChallengeAuthenticatorParams,\n ChallengeResponse,\n VerifyParams,\n OobChannel,\n ChallengeType,\n EnrollmentFactor\n} from './types';\nimport { getAuthJsEnrollParams, getGrantType } from './utils';\nimport {\n MfaClient as Auth0AuthJsMfaClient,\n MfaListAuthenticatorsError as Auth0JsMfaListAuthenticatorsError,\n MfaEnrollmentError as Auth0JsMfaEnrollmentError,\n MfaChallengeError as Auth0JsMfaChallengeError\n} from '@auth0/auth0-auth-js';\nimport {\n MfaListAuthenticatorsError,\n MfaEnrollmentError,\n MfaChallengeError,\n MfaVerifyError,\n MfaEnrollmentFactorsError\n} from './errors';\nimport { MfaRequirements, MfaRequiredError } from '../errors';\nimport { MfaContextManager } from './MfaContextManager';\n\n/**\n * Client for Auth0 MFA API operations\n *\n * Manages multi-factor authentication including:\n * - Listing enrolled authenticators\n * - Enrolling new authenticators (OTP, SMS, Voice, Push, Email)\n * - Initiating MFA challenges\n * - Verifying MFA challenges\n *\n * This is a wrapper around auth0-auth-js MfaClient that maintains\n * backward compatibility with the existing spa-js API.\n *\n * MFA context (scope, audience) is stored internally keyed by mfaToken,\n * enabling concurrent MFA flows without state conflicts.\n *\n * @example\n * ```typescript\n * try {\n * await auth0.getTokenSilently({ authorizationParams: { audience: 'https://api.example.com' } });\n * } catch (e) {\n * if (e instanceof MfaRequiredError) {\n * // SDK automatically stores context for this mfaToken\n * const authenticators = await auth0.mfa.getAuthenticators({ mfaToken: e.mfa_token });\n * // ... complete MFA flow\n * }\n * }\n * ```\n */\nexport class MfaApiClient {\n private authJsMfaClient: Auth0AuthJsMfaClient;\n private auth0Client: Auth0Client;\n private contextManager: MfaContextManager;\n\n /**\n * @internal\n * Do not instantiate directly. Use Auth0Client.mfa instead.\n */\n constructor(authJsMfaClient: Auth0AuthJsMfaClient, auth0Client: Auth0Client) {\n this.authJsMfaClient = authJsMfaClient;\n this.auth0Client = auth0Client;\n this.contextManager = new MfaContextManager();\n }\n\n /**\n * @internal\n * Stores authentication details (scope, audience, and MFA requirements) for MFA token verification.\n * This is automatically called by Auth0Client when an mfa_required error occurs.\n *\n * The context is stored keyed by the MFA token, enabling concurrent MFA flows.\n *\n * @param mfaToken - The MFA token from the mfa_required error response\n * @param scope - The OAuth scope from the original request (optional)\n * @param audience - The API audience from the original request (optional)\n * @param mfaRequirements - The MFA requirements from the mfa_required error (optional)\n */\n public setMFAAuthDetails(\n mfaToken: string,\n scope?: string,\n audience?: string,\n mfaRequirements?: MfaRequirements\n ) {\n this.contextManager.set(mfaToken, { scope, audience, mfaRequirements });\n }\n\n /**\n * Gets enrolled MFA authenticators filtered by challenge types from context.\n *\n * Challenge types are automatically resolved from the stored MFA context\n * (set when mfa_required error occurred).\n *\n * @param mfaToken - MFA token from mfa_required error\n * @returns Array of enrolled authenticators matching the challenge types\n * @throws {MfaListAuthenticatorsError} If the request fails or context not found\n *\n * @example Basic usage\n * ```typescript\n * try {\n * await auth0.getTokenSilently();\n * } catch (e) {\n * if (e instanceof MfaRequiredError) {\n * // SDK automatically uses challenge types from error context\n * const authenticators = await auth0.mfa.getAuthenticators(e.mfa_token);\n * }\n * }\n * ```\n */\n public async getAuthenticators(mfaToken: string): Promise<Authenticator[]> {\n // Auto-resolve challenge types from stored context\n const context = this.contextManager.get(mfaToken);\n\n // Single validation check for context and challenge types\n if (!context?.mfaRequirements?.challenge || context.mfaRequirements.challenge.length === 0) {\n throw new MfaListAuthenticatorsError(\n 'invalid_request',\n 'challengeType is required and must contain at least one challenge type, please check mfa_required error payload'\n );\n }\n\n const challengeTypes = context.mfaRequirements.challenge.map(\n c => c.type\n ) as ChallengeType[];\n\n try {\n const allAuthenticators = await this.authJsMfaClient.listAuthenticators({\n mfaToken\n });\n\n // Filter authenticators by challenge types from context\n return allAuthenticators.filter(auth => {\n if (!auth.type) return false;\n return challengeTypes.includes(auth.type as ChallengeType);\n });\n } catch (error: unknown) {\n if (error instanceof Auth0JsMfaListAuthenticatorsError) {\n throw new MfaListAuthenticatorsError(\n error.cause?.error!,\n error.message\n );\n }\n throw error;\n }\n }\n\n /**\n * Enrolls a new MFA authenticator\n *\n * Requires MFA access token with 'enroll' scope\n *\n * @param params - Enrollment parameters including mfaToken and factorType\n * @returns Enrollment response with authenticator details\n * @throws {MfaEnrollmentError} If enrollment fails\n *\n * @example OTP enrollment\n * ```typescript\n * const enrollment = await mfa.enroll({\n * mfaToken: mfaToken,\n * factorType: 'otp'\n * });\n * console.log(enrollment.secret); // Base32 secret\n * console.log(enrollment.barcodeUri); // QR code URI\n * ```\n *\n * @example SMS enrollment\n * ```typescript\n * const enrollment = await mfa.enroll({\n * mfaToken: mfaToken,\n * factorType: 'sms',\n * phoneNumber: '+12025551234'\n * });\n * ```\n */\n public async enroll(\n params: EnrollParams\n ): Promise<EnrollmentResponse> {\n const authJsParams = getAuthJsEnrollParams(params);\n\n try {\n // Type assertion is safe here because getAuthJsEnrollParams ensures correct mapping\n return await this.authJsMfaClient.enrollAuthenticator(authJsParams as any);\n } catch (error: unknown) {\n if (error instanceof Auth0JsMfaEnrollmentError) {\n throw new MfaEnrollmentError(\n error.cause?.error!,\n error.message\n );\n }\n throw error;\n }\n }\n\n /**\n * Initiates an MFA challenge\n *\n * Sends OTP via SMS, initiates push notification, or prepares for OTP entry\n *\n * @param params - Challenge parameters including mfaToken\n * @returns Challenge response with oobCode if applicable\n * @throws {MfaChallengeError} If challenge initiation fails\n *\n * @example OTP challenge\n * ```typescript\n * const challenge = await mfa.challenge({\n * mfaToken: mfaTokenFromLogin,\n * challengeType: 'otp',\n * authenticatorId: 'otp|dev_xxx'\n * });\n * // User enters OTP from their authenticator app\n * ```\n *\n * @example SMS challenge\n * ```typescript\n * const challenge = await mfa.challenge({\n * mfaToken: mfaTokenFromLogin,\n * challengeType: 'oob',\n * authenticatorId: 'sms|dev_xxx'\n * });\n * console.log(challenge.oobCode); // Use for verification\n * ```\n */\n public async challenge(\n params: ChallengeAuthenticatorParams\n ): Promise<ChallengeResponse> {\n try {\n const authJsParams: {\n challengeType: 'otp' | 'oob';\n authenticatorId?: string;\n oobChannel?: OobChannel;\n mfaToken: string;\n } = {\n challengeType: params.challengeType,\n mfaToken: params.mfaToken\n };\n\n if (params.authenticatorId) {\n authJsParams.authenticatorId = params.authenticatorId;\n }\n\n return await this.authJsMfaClient.challengeAuthenticator(authJsParams);\n } catch (error: unknown) {\n if (error instanceof Auth0JsMfaChallengeError) {\n throw new MfaChallengeError(\n error.cause?.error!,\n error.message\n );\n }\n throw error;\n }\n }\n\n /**\n * Gets available MFA enrollment factors from the stored context.\n *\n * This method exposes the enrollment options from the mfa_required error's\n * mfaRequirements.enroll array, eliminating the need for manual parsing.\n *\n * @param mfaToken - MFA token from mfa_required error\n * @returns Array of enrollment factors available for the user (empty array if no enrollment required)\n * @throws {MfaEnrollmentFactorsError} If MFA context not found\n *\n * @example Basic usage\n * ```typescript\n * try {\n * await auth0.getTokenSilently();\n * } catch (error) {\n * if (error.error === 'mfa_required') {\n * // Get enrollment options from SDK\n * const enrollOptions = await auth0.mfa.getEnrollmentFactors(error.mfa_token);\n * // [{ type: 'otp' }, { type: 'phone' }, { type: 'push-notification' }]\n *\n * showEnrollmentOptions(enrollOptions);\n * }\n * }\n * ```\n *\n * @example Check if enrollment is required\n * ```typescript\n * try {\n * const factors = await auth0.mfa.getEnrollmentFactors(mfaToken);\n * if (factors.length > 0) {\n * // User needs to enroll in MFA\n * renderEnrollmentUI(factors);\n * } else {\n * // No enrollment required, proceed with challenge\n * }\n * } catch (error) {\n * if (error instanceof MfaEnrollmentFactorsError) {\n * console.error('Context not found:', error.error_description);\n * }\n * }\n * ```\n */\n public async getEnrollmentFactors(\n mfaToken: string\n ): Promise<EnrollmentFactor[]> {\n const context = this.contextManager.get(mfaToken);\n\n if (!context || !context.mfaRequirements) {\n throw new MfaEnrollmentFactorsError(\n 'mfa_context_not_found',\n 'MFA context not found for this MFA token. Please retry the original request to get a new MFA token.'\n );\n }\n\n // Return empty array if no enrollment required (not an error case)\n if (!context.mfaRequirements.enroll || context.mfaRequirements.enroll.length === 0) {\n return [];\n }\n\n return context.mfaRequirements.enroll;\n }\n\n /**\n * Verifies an MFA challenge and completes authentication\n *\n * The scope and audience are retrieved from the stored context (set when the\n * mfa_required error occurred). The grant_type is automatically inferred from\n * which verification field is provided (otp, oobCode, or recoveryCode).\n *\n * @param params - Verification parameters with OTP, OOB code, or recovery code\n * @returns Token response with access_token, id_token, refresh_token\n * @throws {MfaVerifyError} If verification fails (invalid code, expired, rate limited)\n * @throws {MfaVerifyError} If MFA context not found\n * @throws {MfaVerifyError} If grant_type cannot be inferred\n *\n * Rate limits:\n * - 10 verification attempts allowed\n * - Refreshes at 1 attempt per 6 minutes\n *\n * @example OTP verification (grant_type inferred from otp field)\n * ```typescript\n * const tokens = await mfa.verify({\n * mfaToken: mfaTokenFromLogin,\n * otp: '123456'\n * });\n * console.log(tokens.access_token);\n * ```\n *\n * @example OOB verification (grant_type inferred from oobCode field)\n * ```typescript\n * const tokens = await mfa.verify({\n * mfaToken: mfaTokenFromLogin,\n * oobCode: challenge.oobCode,\n * bindingCode: '123456' // Code user received via SMS\n * });\n * ```\n *\n * @example Recovery code verification (grant_type inferred from recoveryCode field)\n * ```typescript\n * const tokens = await mfa.verify({\n * mfaToken: mfaTokenFromLogin,\n * recoveryCode: 'XXXX-XXXX-XXXX'\n * });\n * ```\n */\n public async verify(\n params: VerifyParams\n ): Promise<TokenEndpointResponse> {\n // Look up stored context for this MFA token\n const context = this.contextManager.get(params.mfaToken);\n\n // Use context values only (set when mfa_required error occurred)\n if (!context) {\n throw new MfaVerifyError(\n 'mfa_context_not_found',\n 'MFA context not found for this MFA token. Please retry the original request to get a new MFA token.'\n );\n }\n\n // Get grant type from verification fields\n const grantType = getGrantType(params);\n\n if (!grantType) {\n throw new MfaVerifyError(\n 'invalid_request',\n 'Unable to determine grant type. Provide one of: otp, oobCode, or recoveryCode.'\n );\n }\n\n const scope = context.scope;\n const audience = context.audience;\n\n try {\n const result = await this.auth0Client._requestTokenForMfa({\n grant_type: grantType,\n mfaToken: params.mfaToken,\n scope,\n audience,\n otp: params.otp,\n oob_code: params.oobCode,\n binding_code: params.bindingCode,\n recovery_code: params.recoveryCode\n });\n\n // Clean up context after successful verification\n this.contextManager.remove(params.mfaToken);\n\n return result;\n } catch (error: unknown) {\n if (error instanceof MfaRequiredError) {\n this.setMFAAuthDetails(\n error.mfa_token,\n scope,\n audience,\n error.mfa_requirements\n );\n } else if (error instanceof MfaVerifyError) {\n throw new MfaVerifyError(\n error.error,\n error.error_description\n );\n }\n throw error;\n }\n }\n}\n","import {\n createQueryParams,\n runPopup,\n parseAuthenticationResult,\n encode,\n createRandomString,\n runIframe,\n sha256,\n bufferToBase64UrlEncoded,\n validateCrypto,\n openPopup,\n getDomain,\n getTokenIssuer,\n parseNumber,\n stripAuth0Client\n} from './utils';\n\nimport { getLockManager, type ILockManager } from './lock';\n\nimport { oauthToken } from './api';\n\nimport { injectDefaultScopes, scopesToRequest } from './scope';\n\nimport {\n InMemoryCache,\n ICache,\n CacheKey,\n CacheManager,\n CacheEntry,\n IdTokenEntry,\n CACHE_KEY_ID_TOKEN_SUFFIX,\n DecodedToken\n} from './cache';\n\nimport { ConnectAccountTransaction, LoginTransaction, TransactionManager } from './transaction-manager';\nimport { verify as verifyIdToken } from './jwt';\nimport {\n AuthenticationError,\n ConnectError,\n GenericError,\n MfaRequiredError,\n MissingRefreshTokenError,\n MissingScopesError,\n PopupOpenError,\n TimeoutError\n} from './errors';\n\nimport {\n ClientStorage,\n CookieStorage,\n CookieStorageWithLegacySameSite,\n SessionStorage\n} from './storage';\n\nimport {\n CACHE_LOCATION_MEMORY,\n DEFAULT_POPUP_CONFIG_OPTIONS,\n DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS,\n MISSING_REFRESH_TOKEN_ERROR_MESSAGE,\n DEFAULT_SCOPE,\n DEFAULT_SESSION_CHECK_EXPIRY_DAYS,\n DEFAULT_AUTH0_CLIENT,\n INVALID_REFRESH_TOKEN_ERROR_MESSAGE,\n USER_BLOCKED_ERROR_MESSAGE,\n DEFAULT_NOW_PROVIDER,\n DEFAULT_FETCH_TIMEOUT_MS,\n DEFAULT_AUDIENCE\n} from './constants';\n\nimport {\n Auth0ClientOptions,\n AuthorizationParams,\n AuthorizeOptions,\n RedirectLoginOptions,\n PopupLoginOptions,\n PopupConfigOptions,\n RedirectLoginResult,\n GetTokenSilentlyOptions,\n GetTokenWithPopupOptions,\n LogoutOptions,\n CacheLocation,\n LogoutUrlOptions,\n User,\n IdToken,\n GetTokenSilentlyVerboseResponse,\n TokenEndpointResponse,\n AuthenticationResult,\n ConnectAccountRedirectResult,\n RedirectConnectAccountOptions,\n ResponseType,\n ClientAuthorizationParams,\n ClientConfiguration\n} from './global';\n\n// @ts-ignore\nimport TokenWorker from './worker/token.worker.ts';\nimport { singlePromise, retryPromise } from './promise-utils';\nimport { CacheKeyManifest } from './cache/key-manifest';\nimport {\n buildIsAuthenticatedCookieName,\n buildOrganizationHintCookieName,\n cacheFactory,\n getAuthorizeParams,\n buildGetTokenSilentlyLockKey,\n buildIframeLockKey,\n OLD_IS_AUTHENTICATED_COOKIE_NAME,\n patchOpenUrlWithOnRedirect,\n getScopeToRequest,\n allScopesAreIncluded,\n isRefreshWithMrrt,\n getMissingScopes\n} from './Auth0Client.utils';\nimport { CustomTokenExchangeOptions } from './TokenExchange';\nimport { Dpop } from './dpop/dpop';\nimport {\n Fetcher,\n type FetcherConfig,\n type CustomFetchMinimalOutput\n} from './fetcher';\nimport { MyAccountApiClient } from './MyAccountApiClient';\nimport { MfaApiClient } from './mfa';\nimport { AuthClient as Auth0AuthJsClient } from '@auth0/auth0-auth-js';\n\n/**\n * @ignore\n */\ntype GetTokenSilentlyResult = TokenEndpointResponse & {\n decodedToken: ReturnType<typeof verifyIdToken>;\n scope: string;\n oauthTokenScope?: string;\n audience: string;\n};\n\n/**\n * Auth0 SDK for Single Page Applications using [Authorization Code Grant Flow with PKCE](https://auth0.com/docs/api-auth/tutorials/authorization-code-grant-pkce).\n */\nexport class Auth0Client {\n private readonly transactionManager: TransactionManager;\n private readonly cacheManager: CacheManager;\n private readonly lockManager: ILockManager;\n private readonly domainUrl: string;\n private readonly tokenIssuer: string;\n private readonly scope: Record<string, string>;\n private readonly cookieStorage: ClientStorage;\n private readonly dpop: Dpop | undefined;\n private readonly sessionCheckExpiryDays: number;\n private readonly orgHintCookieName: string;\n private readonly isAuthenticatedCookieName: string;\n private readonly nowProvider: () => number | Promise<number>;\n private readonly httpTimeoutMs: number;\n private readonly options: Auth0ClientOptions & {\n authorizationParams: ClientAuthorizationParams,\n };\n private readonly userCache: ICache = new InMemoryCache().enclosedCache;\n private readonly myAccountApi: MyAccountApiClient;\n\n /**\n * MFA API client for multi-factor authentication operations.\n *\n * Provides methods for:\n * - Listing enrolled authenticators\n * - Enrolling new authenticators (OTP, SMS, Voice, Push, Email)\n * - Initiating MFA challenges\n * - Verifying MFA challenges\n */\n public readonly mfa: MfaApiClient;\n\n private worker?: Worker;\n private readonly authJsClient: Auth0AuthJsClient;\n\n private readonly defaultOptions: Partial<Auth0ClientOptions> = {\n authorizationParams: {\n scope: DEFAULT_SCOPE\n },\n useRefreshTokensFallback: false,\n useFormData: true\n };\n\n constructor(options: Auth0ClientOptions) {\n this.options = {\n ...this.defaultOptions,\n ...options,\n authorizationParams: {\n ...this.defaultOptions.authorizationParams,\n ...options.authorizationParams\n }\n };\n\n typeof window !== 'undefined' && validateCrypto();\n\n this.lockManager = getLockManager();\n\n if (options.cache && options.cacheLocation) {\n console.warn(\n 'Both `cache` and `cacheLocation` options have been specified in the Auth0Client configuration; ignoring `cacheLocation` and using `cache`.'\n );\n }\n\n let cacheLocation: CacheLocation | undefined;\n let cache: ICache;\n\n if (options.cache) {\n cache = options.cache;\n } else {\n cacheLocation = options.cacheLocation || CACHE_LOCATION_MEMORY;\n\n if (!cacheFactory(cacheLocation)) {\n throw new Error(`Invalid cache location \"${cacheLocation}\"`);\n }\n\n cache = cacheFactory(cacheLocation)();\n }\n\n this.httpTimeoutMs = options.httpTimeoutInSeconds\n ? options.httpTimeoutInSeconds * 1000\n : DEFAULT_FETCH_TIMEOUT_MS;\n\n this.cookieStorage =\n options.legacySameSiteCookie === false\n ? CookieStorage\n : CookieStorageWithLegacySameSite;\n\n this.orgHintCookieName = buildOrganizationHintCookieName(\n this.options.clientId\n );\n\n this.isAuthenticatedCookieName = buildIsAuthenticatedCookieName(\n this.options.clientId\n );\n\n this.sessionCheckExpiryDays =\n options.sessionCheckExpiryDays || DEFAULT_SESSION_CHECK_EXPIRY_DAYS;\n\n const transactionStorage = options.useCookiesForTransactions\n ? this.cookieStorage\n : SessionStorage;\n\n // Construct the scopes based on the following:\n // 1. Always include `openid`\n // 2. Include the scopes provided in `authorizationParams. This defaults to `profile email`\n // 3. Add `offline_access` if `useRefreshTokens` is enabled\n this.scope = injectDefaultScopes(\n this.options.authorizationParams.scope,\n 'openid',\n this.options.useRefreshTokens ? 'offline_access' : ''\n );\n\n this.transactionManager = new TransactionManager(\n transactionStorage,\n this.options.clientId,\n this.options.cookieDomain\n );\n\n this.nowProvider = this.options.nowProvider || DEFAULT_NOW_PROVIDER;\n\n this.cacheManager = new CacheManager(\n cache,\n !cache.allKeys\n ? new CacheKeyManifest(cache, this.options.clientId)\n : undefined,\n this.nowProvider\n );\n\n this.dpop = this.options.useDpop\n ? new Dpop(this.options.clientId)\n : undefined;\n\n this.domainUrl = getDomain(this.options.domain);\n this.tokenIssuer = getTokenIssuer(this.options.issuer, this.domainUrl);\n\n const myAccountApiIdentifier = `${this.domainUrl}/me/`;\n const myAccountFetcher = this.createFetcher({\n ...(this.options.useDpop && { dpopNonceId: '__auth0_my_account_api__' }),\n getAccessToken: () =>\n this.getTokenSilently({\n authorizationParams: {\n scope: 'create:me:connected_accounts',\n audience: myAccountApiIdentifier\n },\n detailedResponse: true\n })\n });\n this.myAccountApi = new MyAccountApiClient(\n myAccountFetcher,\n myAccountApiIdentifier\n );\n\n // Initialize auth-js client foundational Oauth feature support\n this.authJsClient = new Auth0AuthJsClient({\n domain: this.options.domain,\n clientId: this.options.clientId,\n });\n this.mfa = new MfaApiClient(this.authJsClient.mfa, this);\n\n\n // Don't use web workers unless using refresh tokens in memory\n if (\n typeof window !== 'undefined' &&\n window.Worker &&\n this.options.useRefreshTokens &&\n cacheLocation === CACHE_LOCATION_MEMORY\n ) {\n if (this.options.workerUrl) {\n this.worker = new Worker(this.options.workerUrl);\n } else {\n this.worker = new TokenWorker();\n }\n }\n }\n\n /**\n * Returns a readonly copy of the initialization configuration.\n *\n * @returns An object containing domain and clientId\n *\n * @example\n * ```typescript\n * const auth0 = new Auth0Client({\n * domain: 'tenant.auth0.com',\n * clientId: 'abc123'\n * });\n *\n * const config = auth0.getConfiguration();\n * // { domain: 'tenant.auth0.com', clientId: 'abc123' }\n * ```\n */\n public getConfiguration(): Readonly<ClientConfiguration> {\n return Object.freeze({\n domain: this.options.domain,\n clientId: this.options.clientId\n });\n }\n\n private _url(path: string) {\n const auth0ClientObj = this.options.auth0Client || DEFAULT_AUTH0_CLIENT;\n // Strip env from auth0Client for /authorize to prevent query param truncation\n const strippedAuth0Client = stripAuth0Client(auth0ClientObj, true);\n const auth0Client = encodeURIComponent(\n btoa(JSON.stringify(strippedAuth0Client))\n );\n return `${this.domainUrl}${path}&auth0Client=${auth0Client}`;\n }\n\n private _authorizeUrl(authorizeOptions: AuthorizeOptions) {\n return this._url(`/authorize?${createQueryParams(authorizeOptions)}`);\n }\n\n private async _verifyIdToken(\n id_token: string,\n nonce?: string,\n organization?: string\n ) {\n const now = await this.nowProvider();\n\n return verifyIdToken({\n iss: this.tokenIssuer,\n aud: this.options.clientId,\n id_token,\n nonce,\n organization,\n leeway: this.options.leeway,\n max_age: parseNumber(this.options.authorizationParams.max_age),\n now\n });\n }\n\n private _processOrgHint(organization?: string) {\n if (organization) {\n this.cookieStorage.save(this.orgHintCookieName, organization, {\n daysUntilExpire: this.sessionCheckExpiryDays,\n cookieDomain: this.options.cookieDomain\n });\n } else {\n this.cookieStorage.remove(this.orgHintCookieName, {\n cookieDomain: this.options.cookieDomain\n });\n }\n }\n\n private async _prepareAuthorizeUrl(\n authorizationParams: AuthorizationParams,\n authorizeOptions?: Partial<AuthorizeOptions>,\n fallbackRedirectUri?: string\n ): Promise<{\n scope: string;\n audience: string;\n redirect_uri?: string;\n nonce: string;\n code_verifier: string;\n state: string;\n url: string;\n }> {\n const state = encode(createRandomString());\n const nonce = encode(createRandomString());\n const code_verifier = createRandomString();\n const code_challengeBuffer = await sha256(code_verifier);\n const code_challenge = bufferToBase64UrlEncoded(code_challengeBuffer);\n const thumbprint = await this.dpop?.calculateThumbprint();\n\n const params = getAuthorizeParams(\n this.options,\n this.scope,\n authorizationParams,\n state,\n nonce,\n code_challenge,\n authorizationParams.redirect_uri ||\n this.options.authorizationParams.redirect_uri ||\n fallbackRedirectUri,\n authorizeOptions?.response_mode,\n thumbprint\n );\n\n const url = this._authorizeUrl(params);\n\n return {\n nonce,\n code_verifier,\n scope: params.scope,\n audience: params.audience || DEFAULT_AUDIENCE,\n redirect_uri: params.redirect_uri,\n state,\n url\n };\n }\n\n /**\n * ```js\n * try {\n * await auth0.loginWithPopup(options);\n * } catch(e) {\n * if (e instanceof PopupCancelledError) {\n * // Popup was closed before login completed\n * }\n * }\n * ```\n *\n * Opens a popup with the `/authorize` URL using the parameters\n * provided as arguments. Random and secure `state` and `nonce`\n * parameters will be auto-generated. If the response is successful,\n * results will be valid according to their expiration times.\n *\n * IMPORTANT: This method has to be called from an event handler\n * that was started by the user like a button click, for example,\n * otherwise the popup will be blocked in most browsers.\n *\n * @param options\n * @param config\n */\n public async loginWithPopup(\n options?: PopupLoginOptions,\n config?: PopupConfigOptions\n ) {\n options = options || {};\n config = config || {};\n\n if (!config.popup) {\n config.popup = openPopup('');\n\n if (!config.popup) {\n throw new PopupOpenError();\n }\n }\n\n const params = await this._prepareAuthorizeUrl(\n options.authorizationParams || {},\n { response_mode: 'web_message' },\n window.location.origin\n );\n\n config.popup.location.href = params.url;\n\n const codeResult = await runPopup({\n ...config,\n timeoutInSeconds:\n config.timeoutInSeconds ||\n this.options.authorizeTimeoutInSeconds ||\n DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS\n });\n\n if (params.state !== codeResult.state) {\n throw new GenericError('state_mismatch', 'Invalid state');\n }\n\n const organization =\n options.authorizationParams?.organization ||\n this.options.authorizationParams.organization;\n\n await this._requestToken(\n {\n audience: params.audience,\n scope: params.scope,\n code_verifier: params.code_verifier,\n grant_type: 'authorization_code',\n code: codeResult.code as string,\n redirect_uri: params.redirect_uri\n },\n {\n nonceIn: params.nonce,\n organization\n }\n );\n }\n\n /**\n * ```js\n * const user = await auth0.getUser();\n * ```\n *\n * Returns the user information if available (decoded\n * from the `id_token`).\n *\n * @typeparam TUser The type to return, has to extend {@link User}.\n */\n public async getUser<TUser extends User>(): Promise<TUser | undefined> {\n const cache = await this._getIdTokenFromCache();\n\n return cache?.decodedToken?.user as TUser;\n }\n\n /**\n * ```js\n * const claims = await auth0.getIdTokenClaims();\n * ```\n *\n * Returns all claims from the id_token if available.\n */\n public async getIdTokenClaims(): Promise<IdToken | undefined> {\n const cache = await this._getIdTokenFromCache();\n\n return cache?.decodedToken?.claims;\n }\n\n /**\n * ```js\n * await auth0.loginWithRedirect(options);\n * ```\n *\n * Performs a redirect to `/authorize` using the parameters\n * provided as arguments. Random and secure `state` and `nonce`\n * parameters will be auto-generated.\n *\n * @param options\n */\n public async loginWithRedirect<TAppState = any>(\n options: RedirectLoginOptions<TAppState> = {}\n ) {\n const { openUrl, fragment, appState, ...urlOptions } =\n patchOpenUrlWithOnRedirect(options);\n\n const organization =\n urlOptions.authorizationParams?.organization ||\n this.options.authorizationParams.organization;\n\n const { url, ...transaction } = await this._prepareAuthorizeUrl(\n urlOptions.authorizationParams || {}\n );\n\n this.transactionManager.create<LoginTransaction>({\n ...transaction,\n appState,\n response_type: ResponseType.Code,\n ...(organization && { organization })\n });\n\n const urlWithFragment = fragment ? `${url}#${fragment}` : url;\n\n if (openUrl) {\n await openUrl(urlWithFragment);\n } else {\n window.location.assign(urlWithFragment);\n }\n }\n\n /**\n * After the browser redirects back to the callback page,\n * call `handleRedirectCallback` to handle success and error\n * responses from Auth0. If the response is successful, results\n * will be valid according to their expiration times.\n */\n public async handleRedirectCallback<TAppState = any>(\n url: string = window.location.href\n ): Promise<\n RedirectLoginResult<TAppState> | ConnectAccountRedirectResult<TAppState>\n > {\n const queryStringFragments = url.split('?').slice(1);\n\n if (queryStringFragments.length === 0) {\n throw new Error('There are no query params available for parsing.');\n }\n\n const transaction = this.transactionManager.get<\n LoginTransaction | ConnectAccountTransaction\n >();\n\n if (!transaction) {\n throw new GenericError('missing_transaction', 'Invalid state');\n }\n\n this.transactionManager.remove();\n\n const authenticationResult = parseAuthenticationResult(\n queryStringFragments.join('')\n );\n\n if (transaction.response_type === ResponseType.ConnectCode) {\n return this._handleConnectAccountRedirectCallback<TAppState>(\n authenticationResult,\n transaction\n );\n }\n return this._handleLoginRedirectCallback<TAppState>(\n authenticationResult,\n transaction\n );\n }\n\n /**\n * Handles the redirect callback from the login flow.\n *\n * @template AppState - The application state persisted from the /authorize redirect.\n * @param {string} authenticationResult - The parsed authentication result from the URL.\n * @param {string} transaction - The login transaction.\n *\n * @returns {RedirectLoginResult} Resolves with the persisted app state.\n * @throws {GenericError | Error} If the transaction is missing, invalid, or the code exchange fails.\n */\n private async _handleLoginRedirectCallback<TAppState>(\n authenticationResult: AuthenticationResult,\n transaction: LoginTransaction\n ): Promise<RedirectLoginResult<TAppState>> {\n const { code, state, error, error_description } = authenticationResult;\n\n if (error) {\n throw new AuthenticationError(\n error,\n error_description || error,\n state,\n transaction.appState\n );\n }\n\n // Transaction should have a `code_verifier` to do PKCE for CSRF protection\n if (\n !transaction.code_verifier ||\n (transaction.state && transaction.state !== state)\n ) {\n throw new GenericError('state_mismatch', 'Invalid state');\n }\n\n const organization = transaction.organization;\n const nonceIn = transaction.nonce;\n const redirect_uri = transaction.redirect_uri;\n\n await this._requestToken(\n {\n audience: transaction.audience,\n scope: transaction.scope,\n code_verifier: transaction.code_verifier,\n grant_type: 'authorization_code',\n code: code as string,\n ...(redirect_uri ? { redirect_uri } : {})\n },\n { nonceIn, organization }\n );\n\n return {\n appState: transaction.appState,\n response_type: ResponseType.Code\n };\n }\n\n /**\n * Handles the redirect callback from the connect account flow.\n * This works the same as the redirect from the login flow expect it verifies the `connect_code`\n * with the My Account API rather than the `code` with the Authorization Server.\n *\n * @template AppState - The application state persisted from the connect redirect.\n * @param {string} connectResult - The parsed connect accounts result from the URL.\n * @param {string} transaction - The login transaction.\n * @returns {Promise<ConnectAccountRedirectResult>} The result of the My Account API, including any persisted app state.\n * @throws {GenericError | MyAccountApiError} If the transaction is missing, invalid, or an error is returned from the My Account API.\n */\n private async _handleConnectAccountRedirectCallback<TAppState>(\n connectResult: AuthenticationResult,\n transaction: ConnectAccountTransaction\n ): Promise<ConnectAccountRedirectResult<TAppState>> {\n const { connect_code, state, error, error_description } = connectResult;\n\n if (error) {\n throw new ConnectError(\n error,\n error_description || error,\n transaction.connection,\n state,\n transaction.appState\n );\n }\n\n if (!connect_code) {\n throw new GenericError('missing_connect_code', 'Missing connect code');\n }\n\n if (\n !transaction.code_verifier ||\n !transaction.state ||\n !transaction.auth_session ||\n !transaction.redirect_uri ||\n transaction.state !== state\n ) {\n throw new GenericError('state_mismatch', 'Invalid state');\n }\n\n const data = await this.myAccountApi.completeAccount({\n auth_session: transaction.auth_session,\n connect_code,\n redirect_uri: transaction.redirect_uri,\n code_verifier: transaction.code_verifier\n });\n\n return {\n ...data,\n appState: transaction.appState,\n response_type: ResponseType.ConnectCode,\n };\n }\n\n /**\n * ```js\n * await auth0.checkSession();\n * ```\n *\n * Check if the user is logged in using `getTokenSilently`. The difference\n * with `getTokenSilently` is that this doesn't return a token, but it will\n * pre-fill the token cache.\n *\n * This method also heeds the `auth0.{clientId}.is.authenticated` cookie, as an optimization\n * to prevent calling Auth0 unnecessarily. If the cookie is not present because\n * there was no previous login (or it has expired) then tokens will not be refreshed.\n *\n * It should be used for silently logging in the user when you instantiate the\n * `Auth0Client` constructor. You should not need this if you are using the\n * `createAuth0Client` factory.\n *\n * **Note:** the cookie **may not** be present if running an app using a private tab, as some\n * browsers clear JS cookie data and local storage when the tab or page is closed, or on page reload. This effectively\n * means that `checkSession` could silently return without authenticating the user on page refresh when\n * using a private tab, despite having previously logged in. As a workaround, use `getTokenSilently` instead\n * and handle the possible `login_required` error [as shown in the readme](https://github.com/auth0/auth0-spa-js#creating-the-client).\n *\n * @param options\n */\n public async checkSession(options?: GetTokenSilentlyOptions) {\n if (!this.cookieStorage.get(this.isAuthenticatedCookieName)) {\n if (!this.cookieStorage.get(OLD_IS_AUTHENTICATED_COOKIE_NAME)) {\n return;\n } else {\n // Migrate the existing cookie to the new name scoped by client ID\n this.cookieStorage.save(this.isAuthenticatedCookieName, true, {\n daysUntilExpire: this.sessionCheckExpiryDays,\n cookieDomain: this.options.cookieDomain\n });\n\n this.cookieStorage.remove(OLD_IS_AUTHENTICATED_COOKIE_NAME);\n }\n }\n\n try {\n await this.getTokenSilently(options);\n } catch (_) { }\n }\n\n /**\n * Fetches a new access token and returns the response from the /oauth/token endpoint, omitting the refresh token.\n *\n * @param options\n */\n public async getTokenSilently(\n options: GetTokenSilentlyOptions & { detailedResponse: true }\n ): Promise<GetTokenSilentlyVerboseResponse>;\n\n /**\n * Fetches a new access token and returns it.\n *\n * @param options\n */\n public async getTokenSilently(\n options?: GetTokenSilentlyOptions\n ): Promise<string>;\n\n /**\n * Fetches a new access token, and either returns just the access token (the default) or the response from the /oauth/token endpoint, depending on the `detailedResponse` option.\n *\n * ```js\n * const token = await auth0.getTokenSilently(options);\n * ```\n *\n * If there's a valid token stored and it has more than 60 seconds\n * remaining before expiration, return the token. Otherwise, attempt\n * to obtain a new token.\n *\n * A new token will be obtained either by opening an iframe or a\n * refresh token (if `useRefreshTokens` is `true`).\n\n * If iframes are used, opens an iframe with the `/authorize` URL\n * using the parameters provided as arguments. Random and secure `state`\n * and `nonce` parameters will be auto-generated. If the response is successful,\n * results will be validated according to their expiration times.\n *\n * If refresh tokens are used, the token endpoint is called directly with the\n * 'refresh_token' grant. If no refresh token is available to make this call,\n * the SDK will only fall back to using an iframe to the '/authorize' URL if\n * the `useRefreshTokensFallback` setting has been set to `true`. By default this\n * setting is `false`.\n *\n * This method may use a web worker to perform the token call if the in-memory\n * cache is used.\n *\n * If an `audience` value is given to this function, the SDK always falls\n * back to using an iframe to make the token exchange.\n *\n * Note that in all cases, falling back to an iframe requires access to\n * the `auth0` cookie.\n *\n * @param options\n */\n public async getTokenSilently(\n options: GetTokenSilentlyOptions = {}\n ): Promise<undefined | string | GetTokenSilentlyVerboseResponse> {\n const localOptions: GetTokenSilentlyOptions & {\n authorizationParams: AuthorizationParams & { scope: string };\n } = {\n cacheMode: 'on',\n ...options,\n authorizationParams: {\n ...this.options.authorizationParams,\n ...options.authorizationParams,\n scope: scopesToRequest(\n this.scope,\n options.authorizationParams?.scope,\n options.authorizationParams?.audience || this.options.authorizationParams.audience,\n )\n }\n };\n\n const result = await singlePromise(\n () => this._getTokenSilently(localOptions),\n `${this.options.clientId}::${localOptions.authorizationParams.audience}::${localOptions.authorizationParams.scope}`\n );\n\n return options.detailedResponse ? result : result?.access_token;\n }\n\n private async _getTokenSilently(\n options: GetTokenSilentlyOptions & {\n authorizationParams: AuthorizationParams & { scope: string };\n }\n ): Promise<undefined | GetTokenSilentlyVerboseResponse> {\n const { cacheMode, ...getTokenOptions } = options;\n\n // Check the cache before acquiring the lock to avoid the latency of\n // `lock.acquireLock` when the cache is populated.\n if (cacheMode !== 'off') {\n const entry = await this._getEntryFromCache({\n scope: getTokenOptions.authorizationParams.scope,\n audience: getTokenOptions.authorizationParams.audience || DEFAULT_AUDIENCE,\n clientId: this.options.clientId,\n cacheMode,\n });\n\n if (entry) {\n return entry;\n }\n }\n\n if (cacheMode === 'cache-only') {\n return;\n }\n\n // Generate lock key based on client ID and audience for better isolation\n const lockKey = buildGetTokenSilentlyLockKey(\n this.options.clientId,\n getTokenOptions.authorizationParams.audience || 'default'\n );\n\n return await this.lockManager.runWithLock(lockKey, 5000, async () => {\n // Check the cache a second time, because it may have been populated\n // by a previous call while this call was waiting to acquire the lock.\n if (cacheMode !== 'off') {\n const entry = await this._getEntryFromCache({\n scope: getTokenOptions.authorizationParams.scope,\n audience:\n getTokenOptions.authorizationParams.audience || DEFAULT_AUDIENCE,\n clientId: this.options.clientId\n });\n\n if (entry) {\n return entry;\n }\n }\n\n const authResult = this.options.useRefreshTokens\n ? await this._getTokenUsingRefreshToken(getTokenOptions)\n : await this._getTokenFromIFrame(getTokenOptions);\n\n const { id_token, token_type, access_token, oauthTokenScope, expires_in } =\n authResult;\n\n return {\n id_token,\n token_type,\n access_token,\n ...(oauthTokenScope ? { scope: oauthTokenScope } : null),\n expires_in\n };\n });\n }\n\n /**\n * ```js\n * const token = await auth0.getTokenWithPopup(options);\n * ```\n * Opens a popup with the `/authorize` URL using the parameters\n * provided as arguments. Random and secure `state` and `nonce`\n * parameters will be auto-generated. If the response is successful,\n * results will be valid according to their expiration times.\n *\n * @param options\n * @param config\n */\n public async getTokenWithPopup(\n options: GetTokenWithPopupOptions = {},\n config: PopupConfigOptions = {}\n ) {\n const localOptions = {\n ...options,\n authorizationParams: {\n ...this.options.authorizationParams,\n ...options.authorizationParams,\n scope: scopesToRequest(\n this.scope,\n options.authorizationParams?.scope,\n options.authorizationParams?.audience || this.options.authorizationParams.audience\n )\n }\n };\n\n config = {\n ...DEFAULT_POPUP_CONFIG_OPTIONS,\n ...config\n };\n\n await this.loginWithPopup(localOptions, config);\n\n const cache = await this.cacheManager.get(\n new CacheKey({\n scope: localOptions.authorizationParams.scope,\n audience: localOptions.authorizationParams.audience || DEFAULT_AUDIENCE,\n clientId: this.options.clientId\n }),\n undefined,\n this.options.useMrrt\n );\n\n return cache!.access_token;\n }\n\n /**\n * ```js\n * const isAuthenticated = await auth0.isAuthenticated();\n * ```\n *\n * Returns `true` if there's valid information stored,\n * otherwise returns `false`.\n *\n */\n public async isAuthenticated() {\n const user = await this.getUser();\n return !!user;\n }\n\n /**\n * ```js\n * await auth0.buildLogoutUrl(options);\n * ```\n *\n * Builds a URL to the logout endpoint using the parameters provided as arguments.\n * @param options\n */\n private _buildLogoutUrl(options: LogoutUrlOptions): string {\n if (options.clientId !== null) {\n options.clientId = options.clientId || this.options.clientId;\n } else {\n delete options.clientId;\n }\n\n const { federated, ...logoutOptions } = options.logoutParams || {};\n const federatedQuery = federated ? `&federated` : '';\n const url = this._url(\n `/v2/logout?${createQueryParams({\n clientId: options.clientId,\n ...logoutOptions\n })}`\n );\n\n return url + federatedQuery;\n }\n\n /**\n * ```js\n * await auth0.logout(options);\n * ```\n *\n * Clears the application session and performs a redirect to `/v2/logout`, using\n * the parameters provided as arguments, to clear the Auth0 session.\n *\n * If the `federated` option is specified it also clears the Identity Provider session.\n * [Read more about how Logout works at Auth0](https://auth0.com/docs/logout).\n *\n * @param options\n */\n public async logout(options: LogoutOptions = {}): Promise<void> {\n const { openUrl, ...logoutOptions } = patchOpenUrlWithOnRedirect(options);\n\n if (options.clientId === null) {\n await this.cacheManager.clear();\n } else {\n await this.cacheManager.clear(options.clientId || this.options.clientId);\n }\n\n this.cookieStorage.remove(this.orgHintCookieName, {\n cookieDomain: this.options.cookieDomain\n });\n this.cookieStorage.remove(this.isAuthenticatedCookieName, {\n cookieDomain: this.options.cookieDomain\n });\n this.userCache.remove(CACHE_KEY_ID_TOKEN_SUFFIX);\n\n await this.dpop?.clear();\n\n const url = this._buildLogoutUrl(logoutOptions);\n\n if (openUrl) {\n await openUrl(url);\n } else if (openUrl !== false) {\n window.location.assign(url);\n }\n }\n\n private async _getTokenFromIFrame(\n options: GetTokenSilentlyOptions & {\n authorizationParams: AuthorizationParams & { scope: string };\n }\n ): Promise<GetTokenSilentlyResult> {\n const iframeLockKey = buildIframeLockKey(this.options.clientId);\n\n // Acquire global iframe lock to serialize iframe authorization flows.\n // This is necessary because the SDK does not support multiple simultaneous transactions.\n // Since https://github.com/auth0/auth0-spa-js/pull/1408, when calling\n // `getTokenSilently()`, the global locking will lock per `audience` instead of locking\n // only per `client_id`.\n // This means that calls for different audiences would happen in parallel, which does\n // not work when using silent authentication (prompt=none) from within the SDK, as that\n // relies on the same transaction context as a top-level `loginWithRedirect`.\n // To resolve that, we add a second-level locking that locks only the iframe calls in\n // the same way as was done before https://github.com/auth0/auth0-spa-js/pull/1408.\n try {\n return await this.lockManager.runWithLock(\n iframeLockKey,\n 5000,\n async () => {\n const params: AuthorizationParams & { scope: string } = {\n ...options.authorizationParams,\n prompt: 'none'\n };\n\n const orgHint = this.cookieStorage.get<string>(\n this.orgHintCookieName\n );\n\n if (orgHint && !params.organization) {\n params.organization = orgHint;\n }\n\n const {\n url,\n state: stateIn,\n nonce: nonceIn,\n code_verifier,\n redirect_uri,\n scope,\n audience\n } = await this._prepareAuthorizeUrl(\n params,\n { response_mode: 'web_message' },\n window.location.origin\n );\n\n // When a browser is running in a Cross-Origin Isolated context, using iframes is not possible.\n // It doesn't throw an error but times out instead, so we should exit early and inform the user about the reason.\n // https://developer.mozilla.org/en-US/docs/Web/API/crossOriginIsolated\n if ((window as any).crossOriginIsolated) {\n throw new GenericError(\n 'login_required',\n 'The application is running in a Cross-Origin Isolated context, silently retrieving a token without refresh token is not possible.'\n );\n }\n\n const authorizeTimeout =\n options.timeoutInSeconds || this.options.authorizeTimeoutInSeconds;\n\n // Extract origin from domainUrl, fallback to domainUrl if URL parsing fails\n let eventOrigin: string;\n try {\n eventOrigin = new URL(this.domainUrl).origin;\n } catch {\n eventOrigin = this.domainUrl;\n }\n\n const codeResult = await runIframe(\n url,\n eventOrigin,\n authorizeTimeout\n );\n\n if (stateIn !== codeResult.state) {\n throw new GenericError('state_mismatch', 'Invalid state');\n }\n\n const tokenResult = await this._requestToken(\n {\n ...options.authorizationParams,\n code_verifier,\n code: codeResult.code as string,\n grant_type: 'authorization_code',\n redirect_uri,\n timeout: options.authorizationParams.timeout || this.httpTimeoutMs\n },\n {\n nonceIn,\n organization: params.organization\n }\n );\n\n return {\n ...tokenResult,\n scope: scope,\n oauthTokenScope: tokenResult.scope,\n audience: audience\n };\n }\n );\n } catch (e) {\n if (e.error === 'login_required') {\n this.logout({\n openUrl: false\n });\n }\n throw e;\n }\n }\n\n private async _getTokenUsingRefreshToken(\n options: GetTokenSilentlyOptions & {\n authorizationParams: AuthorizationParams & { scope: string };\n }\n ): Promise<GetTokenSilentlyResult> {\n const cache = await this.cacheManager.get(\n new CacheKey({\n scope: options.authorizationParams.scope,\n audience: options.authorizationParams.audience || DEFAULT_AUDIENCE,\n clientId: this.options.clientId\n }),\n undefined,\n this.options.useMrrt\n );\n\n // If you don't have a refresh token in memory\n // and you don't have a refresh token in web worker memory\n // and useRefreshTokensFallback was explicitly enabled\n // fallback to an iframe\n if ((!cache || !cache.refresh_token) && !this.worker) {\n if (this.options.useRefreshTokensFallback) {\n return await this._getTokenFromIFrame(options);\n }\n\n throw new MissingRefreshTokenError(\n options.authorizationParams.audience || DEFAULT_AUDIENCE,\n options.authorizationParams.scope\n );\n }\n\n const redirect_uri =\n options.authorizationParams.redirect_uri ||\n this.options.authorizationParams.redirect_uri ||\n window.location.origin;\n\n const timeout =\n typeof options.timeoutInSeconds === 'number'\n ? options.timeoutInSeconds * 1000\n : null;\n\n const scopesToRequest = getScopeToRequest(\n this.options.useMrrt,\n options.authorizationParams,\n cache?.audience,\n cache?.scope,\n );\n\n try {\n const tokenResult = await this._requestToken({\n ...options.authorizationParams,\n grant_type: 'refresh_token',\n refresh_token: cache && cache.refresh_token,\n redirect_uri,\n ...(timeout && { timeout })\n },\n {\n scopesToRequest,\n }\n );\n\n // If is refreshed with MRRT, we update all entries that have the old\n // refresh_token with the new one if the server responded with one\n if (tokenResult.refresh_token && cache?.refresh_token) {\n await this.cacheManager.updateEntry(\n cache.refresh_token,\n tokenResult.refresh_token\n );\n }\n\n // Some scopes requested to the server might not be inside the refresh policies\n // In order to return a token with all requested scopes when using MRRT we should\n // check if all scopes are returned. If not, we will try to use an iframe to request\n // a token.\n if (this.options.useMrrt) {\n const isRefreshMrrt = isRefreshWithMrrt(\n cache?.audience,\n cache?.scope,\n options.authorizationParams.audience,\n options.authorizationParams.scope,\n );\n\n if (isRefreshMrrt) {\n const tokenHasAllScopes = allScopesAreIncluded(\n scopesToRequest,\n tokenResult.scope,\n );\n\n if (!tokenHasAllScopes) {\n if (this.options.useRefreshTokensFallback) {\n return await this._getTokenFromIFrame(options);\n }\n\n // Before throwing MissingScopesError, we have to remove the previously created entry\n // to avoid storing wrong data\n await this.cacheManager.remove(\n this.options.clientId,\n options.authorizationParams.audience,\n options.authorizationParams.scope,\n );\n\n const missingScopes = getMissingScopes(\n scopesToRequest,\n tokenResult.scope,\n );\n\n throw new MissingScopesError(\n options.authorizationParams.audience || 'default',\n missingScopes,\n );\n }\n }\n }\n\n return {\n ...tokenResult,\n scope: options.authorizationParams.scope,\n oauthTokenScope: tokenResult.scope,\n audience: options.authorizationParams.audience || DEFAULT_AUDIENCE\n };\n } catch (e) {\n if (e.message) {\n // Blocked users should be logged out immediately. No point attempting\n // iframe fallback as the authorization server will reject the request.\n if (e.message.includes(USER_BLOCKED_ERROR_MESSAGE)) {\n await this.logout({ openUrl: false });\n throw e;\n }\n\n // For missing or invalid refresh tokens, attempt iframe fallback if configured.\n // The iframe may succeed if the user still has a valid session.\n if (\n (e.message.includes(MISSING_REFRESH_TOKEN_ERROR_MESSAGE) ||\n e.message.includes(INVALID_REFRESH_TOKEN_ERROR_MESSAGE)) &&\n this.options.useRefreshTokensFallback\n ) {\n return await this._getTokenFromIFrame(options);\n }\n }\n\n if (e instanceof MfaRequiredError) {\n this.mfa.setMFAAuthDetails(\n e.mfa_token,\n options.authorizationParams?.scope,\n options.authorizationParams?.audience,\n e.mfa_requirements\n );\n }\n\n throw e;\n }\n }\n\n private async _saveEntryInCache(\n entry: CacheEntry & { id_token: string; decodedToken: DecodedToken }\n ) {\n const { id_token, decodedToken, ...entryWithoutIdToken } = entry;\n\n this.userCache.set(CACHE_KEY_ID_TOKEN_SUFFIX, {\n id_token,\n decodedToken\n });\n\n await this.cacheManager.setIdToken(\n this.options.clientId,\n entry.id_token,\n entry.decodedToken\n );\n\n await this.cacheManager.set(entryWithoutIdToken);\n }\n\n private async _getIdTokenFromCache() {\n const audience = this.options.authorizationParams.audience || DEFAULT_AUDIENCE;\n const scope = this.scope[audience];\n\n const cache = await this.cacheManager.getIdToken(\n new CacheKey({\n clientId: this.options.clientId,\n audience,\n scope,\n })\n );\n\n const currentCache = this.userCache.get<IdTokenEntry>(\n CACHE_KEY_ID_TOKEN_SUFFIX\n ) as IdTokenEntry;\n\n // If the id_token in the cache matches the value we previously cached in memory return the in-memory\n // value so that object comparison will work\n if (cache && cache.id_token === currentCache?.id_token) {\n return currentCache;\n }\n\n this.userCache.set(CACHE_KEY_ID_TOKEN_SUFFIX, cache);\n return cache;\n }\n\n private async _getEntryFromCache({\n scope,\n audience,\n clientId,\n cacheMode,\n }: {\n scope: string;\n audience: string;\n clientId: string;\n cacheMode?: string;\n }): Promise<undefined | GetTokenSilentlyVerboseResponse> {\n const entry = await this.cacheManager.get(\n new CacheKey({\n scope,\n audience,\n clientId\n }),\n 60, // get a new token if within 60 seconds of expiring\n this.options.useMrrt,\n cacheMode,\n );\n\n if (entry && entry.access_token) {\n const { token_type, access_token, oauthTokenScope, expires_in } =\n entry as CacheEntry;\n const cache = await this._getIdTokenFromCache();\n return (\n cache && {\n id_token: cache.id_token,\n token_type: token_type ? token_type : 'Bearer',\n access_token,\n ...(oauthTokenScope ? { scope: oauthTokenScope } : null),\n expires_in\n }\n );\n }\n }\n\n private async _requestToken(\n options:\n | PKCERequestTokenOptions\n | RefreshTokenRequestTokenOptions\n | TokenExchangeRequestOptions,\n additionalParameters?: RequestTokenAdditionalParameters\n ) {\n const { nonceIn, organization, scopesToRequest } = additionalParameters || {};\n const authResult = await oauthToken(\n {\n baseUrl: this.domainUrl,\n client_id: this.options.clientId,\n auth0Client: this.options.auth0Client,\n useFormData: this.options.useFormData,\n timeout: this.httpTimeoutMs,\n useMrrt: this.options.useMrrt,\n dpop: this.dpop,\n ...options,\n scope: scopesToRequest || options.scope,\n },\n this.worker\n );\n\n const decodedToken = await this._verifyIdToken(\n authResult.id_token,\n nonceIn,\n organization\n );\n\n // When logging in with authorization_code, check if a different user is authenticating\n // If so, clear the cache to prevent tokens from multiple users coexisting\n if (options.grant_type === 'authorization_code') {\n const existingIdToken = await this._getIdTokenFromCache();\n\n if (existingIdToken?.decodedToken?.claims?.sub &&\n existingIdToken.decodedToken.claims.sub !== decodedToken.claims.sub) {\n // Different user detected - clear cached tokens\n await this.cacheManager.clear(this.options.clientId);\n this.userCache.remove(CACHE_KEY_ID_TOKEN_SUFFIX);\n }\n }\n\n await this._saveEntryInCache({\n ...authResult,\n decodedToken,\n scope: options.scope,\n audience: options.audience || DEFAULT_AUDIENCE,\n ...(authResult.scope ? { oauthTokenScope: authResult.scope } : null),\n client_id: this.options.clientId\n });\n\n this.cookieStorage.save(this.isAuthenticatedCookieName, true, {\n daysUntilExpire: this.sessionCheckExpiryDays,\n cookieDomain: this.options.cookieDomain\n });\n\n this._processOrgHint(organization || decodedToken.claims.org_id);\n\n return { ...authResult, decodedToken };\n }\n\n /*\n Custom Token Exchange\n * **Implementation Notes:**\n * - Ensure that the `subject_token` provided has been securely obtained and is valid according\n * to your external identity provider's policies before invoking this function.\n * - The function leverages internal helper methods:\n * - `validateTokenType` confirms that the `subject_token_type` is supported.\n * - `getUniqueScopes` merges and de-duplicates scopes between the provided options and\n * the instance's default scopes.\n * - `_requestToken` performs the actual HTTP request to the token endpoint.\n */\n\n /**\n * ```js\n * await auth0.loginWithCustomTokenExchange(options);\n * ```\n *\n * Exchanges an external subject token for Auth0 tokens and logs the user in.\n * This method implements the Custom Token Exchange grant as specified in RFC 8693.\n *\n * The exchanged tokens are automatically cached, establishing an authenticated session.\n * After calling this method, you can use `getUser()`, `getIdTokenClaims()`, and\n * `getTokenSilently()` to access the user's information and tokens.\n *\n * @param {CustomTokenExchangeOptions} options - The options required to perform the token exchange.\n *\n * @returns {Promise<TokenEndpointResponse>} A promise that resolves to the token endpoint response,\n * which contains the issued Auth0 tokens (access_token, id_token, etc.).\n *\n * The request includes the following parameters:\n * - `grant_type`: \"urn:ietf:params:oauth:grant-type:token-exchange\"\n * - `subject_token`: The external token to exchange\n * - `subject_token_type`: The type identifier of the external token\n * - `scope`: Merged scopes from the request and SDK defaults\n * - `audience`: Target audience (defaults to SDK configuration)\n * - `organization`: Optional organization ID/name for org-scoped authentication\n *\n * **Example Usage:**\n *\n * ```js\n * const options = {\n * subject_token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6Ikp...',\n * subject_token_type: 'urn:acme:legacy-system-token',\n * scope: 'openid profile email',\n * audience: 'https://api.example.com',\n * organization: 'org_12345'\n * };\n *\n * try {\n * const tokenResponse = await auth0.loginWithCustomTokenExchange(options);\n * console.log('Access token:', tokenResponse.access_token);\n *\n * // User is now logged in - access user info\n * const user = await auth0.getUser();\n * console.log('Logged in user:', user);\n * } catch (error) {\n * console.error('Token exchange failed:', error);\n * }\n * ```\n */\n async loginWithCustomTokenExchange(\n options: CustomTokenExchangeOptions\n ): Promise<TokenEndpointResponse> {\n return this._requestToken({\n ...options,\n grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',\n subject_token: options.subject_token,\n subject_token_type: options.subject_token_type,\n scope: scopesToRequest(\n this.scope,\n options.scope,\n options.audience || this.options.authorizationParams.audience\n ),\n audience: options.audience || this.options.authorizationParams.audience,\n organization: options.organization || this.options.authorizationParams.organization\n });\n }\n\n /**\n * @deprecated Use `loginWithCustomTokenExchange()` instead. This method will be removed in the next major version.\n *\n * Exchanges an external subject token for Auth0 tokens.\n *\n * @param {CustomTokenExchangeOptions} options - The options required to perform the token exchange.\n * @returns {Promise<TokenEndpointResponse>} A promise that resolves to the token endpoint response.\n *\n * **Example:**\n * ```js\n * // Instead of:\n * const tokens = await auth0.exchangeToken(options);\n *\n * // Use:\n * const tokens = await auth0.loginWithCustomTokenExchange(options);\n * ```\n */\n async exchangeToken(\n options: CustomTokenExchangeOptions\n ): Promise<TokenEndpointResponse> {\n return this.loginWithCustomTokenExchange(options);\n }\n\n protected _assertDpop(dpop: Dpop | undefined): asserts dpop is Dpop {\n if (!dpop) {\n throw new Error('`useDpop` option must be enabled before using DPoP.');\n }\n }\n\n /**\n * Returns the current DPoP nonce used for making requests to Auth0.\n *\n * It can return `undefined` because when starting fresh it will not\n * be populated until after the first response from the server.\n *\n * It requires enabling the {@link Auth0ClientOptions.useDpop} option.\n *\n * @param nonce The nonce value.\n * @param id The identifier of a nonce: if absent, it will get the nonce\n * used for requests to Auth0. Otherwise, it will be used to\n * select a specific non-Auth0 nonce.\n */\n public getDpopNonce(id?: string): Promise<string | undefined> {\n this._assertDpop(this.dpop);\n\n return this.dpop.getNonce(id);\n }\n\n /**\n * Sets the current DPoP nonce used for making requests to Auth0.\n *\n * It requires enabling the {@link Auth0ClientOptions.useDpop} option.\n *\n * @param nonce The nonce value.\n * @param id The identifier of a nonce: if absent, it will set the nonce\n * used for requests to Auth0. Otherwise, it will be used to\n * select a specific non-Auth0 nonce.\n */\n public setDpopNonce(nonce: string, id?: string): Promise<void> {\n this._assertDpop(this.dpop);\n\n return this.dpop.setNonce(nonce, id);\n }\n\n /**\n * Returns a string to be used to demonstrate possession of the private\n * key used to cryptographically bind access tokens with DPoP.\n *\n * It requires enabling the {@link Auth0ClientOptions.useDpop} option.\n */\n public generateDpopProof(params: {\n url: string;\n method: string;\n nonce?: string;\n accessToken: string;\n }): Promise<string> {\n this._assertDpop(this.dpop);\n\n return this.dpop.generateProof(params);\n }\n\n /**\n * Returns a new `Fetcher` class that will contain a `fetchWithAuth()` method.\n * This is a drop-in replacement for the Fetch API's `fetch()` method, but will\n * handle certain authentication logic for you, like building the proper auth\n * headers or managing DPoP nonces and retries automatically.\n *\n * Check the `EXAMPLES.md` file for a deeper look into this method.\n */\n public createFetcher<TOutput extends CustomFetchMinimalOutput = Response>(\n config: FetcherConfig<TOutput> = {}\n ): Fetcher<TOutput> {\n return new Fetcher(config, {\n isDpopEnabled: () => !!this.options.useDpop,\n getAccessToken: authParams =>\n this.getTokenSilently({\n authorizationParams: {\n scope: authParams?.scope?.join(' '),\n audience: authParams?.audience\n },\n detailedResponse: true\n }),\n getDpopNonce: () => this.getDpopNonce(config.dpopNonceId),\n setDpopNonce: nonce => this.setDpopNonce(nonce, config.dpopNonceId),\n generateDpopProof: params => this.generateDpopProof(params)\n });\n }\n\n\n /**\n * Initiates a redirect to connect the user's account with a specified connection.\n * This method generates PKCE parameters, creates a transaction, and redirects to the /connect endpoint.\n * \n * You must enable `Offline Access` from the Connection Permissions settings to be able to use the connection with Connected Accounts.\n *\n * @template TAppState - The application state to persist through the transaction.\n * @param {RedirectConnectAccountOptions<TAppState>} options - Options for the connect account redirect flow.\n * @param {string} options.connection - The name of the connection to link (e.g. 'google-oauth2').\n * @param {string[]} [options.scopes] - Array of scopes to request from the Identity Provider during the connect account flow.\n * @param {AuthorizationParams} [options.authorization_params] - Additional authorization parameters for the request to the upstream IdP.\n * @param {string} [options.redirectUri] - The URI to redirect back to after connecting the account.\n * @param {TAppState} [options.appState] - Application state to persist through the transaction.\n * @param {(url: string) => Promise<void>} [options.openUrl] - Custom function to open the URL.\n *\n * @returns {Promise<void>} Resolves when the redirect is initiated.\n * @throws {MyAccountApiError} If the connect request to the My Account API fails.\n */\n public async connectAccountWithRedirect<TAppState = any>(\n options: RedirectConnectAccountOptions<TAppState>\n ) {\n const {\n openUrl,\n appState,\n connection,\n scopes,\n authorization_params,\n redirectUri = this.options.authorizationParams.redirect_uri ||\n window.location.origin\n } = options;\n\n if (!connection) {\n throw new Error('connection is required');\n }\n\n const state = encode(createRandomString());\n const code_verifier = createRandomString();\n const code_challengeBuffer = await sha256(code_verifier);\n const code_challenge = bufferToBase64UrlEncoded(code_challengeBuffer);\n\n const { connect_uri, connect_params, auth_session } =\n await this.myAccountApi.connectAccount({\n connection,\n scopes,\n redirect_uri: redirectUri,\n state,\n code_challenge,\n code_challenge_method: 'S256',\n authorization_params\n });\n\n this.transactionManager.create<ConnectAccountTransaction>({\n state,\n code_verifier,\n auth_session,\n redirect_uri: redirectUri,\n appState,\n connection,\n response_type: ResponseType.ConnectCode\n });\n\n const url = new URL(connect_uri);\n url.searchParams.set('ticket', connect_params.ticket);\n if (openUrl) {\n await openUrl(url.toString());\n } else {\n window.location.assign(url);\n }\n }\n\n /**\n * @internal\n * Internal method used by MfaApiClient to exchange MFA tokens for access tokens.\n * This method should not be called directly by applications.\n */\n async _requestTokenForMfa(\n options: {\n grant_type: string;\n mfaToken: string;\n scope?: string;\n audience?: string;\n otp?: string;\n binding_code?: string;\n oob_code?: string;\n recovery_code?: string;\n },\n additionalParameters?: RequestTokenAdditionalParameters\n ): Promise<TokenEndpointResponse> {\n // Need to add better typing here\n const { mfaToken, ...restOptions } = options;\n return this._requestToken({ ...restOptions, mfa_token: mfaToken } as any, additionalParameters);\n }\n}\n\ninterface BaseRequestTokenOptions {\n audience?: string;\n scope: string;\n timeout?: number;\n redirect_uri?: string;\n}\n\ninterface PKCERequestTokenOptions extends BaseRequestTokenOptions {\n code: string;\n grant_type: 'authorization_code';\n code_verifier: string;\n}\n\ninterface RefreshTokenRequestTokenOptions extends BaseRequestTokenOptions {\n grant_type: 'refresh_token';\n refresh_token?: string;\n}\n\ninterface TokenExchangeRequestOptions extends BaseRequestTokenOptions {\n grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange';\n subject_token: string;\n subject_token_type: string;\n actor_token?: string;\n actor_token_type?: string;\n organization?: string;\n}\n\ninterface RequestTokenAdditionalParameters {\n nonceIn?: string;\n organization?: string;\n scopesToRequest?: string;\n}\n","import { Auth0Client } from './Auth0Client';\nimport { Auth0ClientOptions } from './global';\n\nimport './global';\n\nexport * from './global';\n\n/**\n * Asynchronously creates the Auth0Client instance and calls `checkSession`.\n *\n * **Note:** There are caveats to using this in a private browser tab, which may not silently authenticae\n * a user on page refresh. Please see [the checkSession docs](https://auth0.github.io/auth0-spa-js/classes/Auth0Client.html#checksession) for more info.\n *\n * @param options The client options\n * @returns An instance of Auth0Client\n */\nexport async function createAuth0Client(options: Auth0ClientOptions) {\n const auth0 = new Auth0Client(options);\n await auth0.checkSession();\n return auth0;\n}\n\nexport { Auth0Client };\n\nexport {\n ConnectError,\n GenericError,\n AuthenticationError,\n TimeoutError,\n PopupTimeoutError,\n PopupCancelledError,\n PopupOpenError,\n MfaRequiredError,\n MissingRefreshTokenError,\n UseDpopNonceError\n} from './errors';\n\nexport {\n MfaError,\n MfaListAuthenticatorsError,\n MfaEnrollmentError,\n MfaChallengeError,\n MfaVerifyError,\n MfaEnrollmentFactorsError\n} from './mfa/errors';\n\nexport { MfaApiClient } from './mfa';\n\nexport type {\n MfaFactorType,\n EnrollParams,\n EnrollOtpParams,\n EnrollSmsParams,\n EnrollVoiceParams,\n EnrollEmailParams,\n EnrollPushParams,\n VerifyParams\n} from './mfa';\n\nexport {\n ICache,\n LocalStorageCache,\n InMemoryCache,\n Cacheable,\n DecodedToken,\n CacheEntry,\n WrappedCacheEntry,\n KeyManifestEntry,\n MaybePromise,\n CacheKey,\n CacheKeyData\n} from './cache';\n\nexport type {\n FetcherConfig,\n Fetcher,\n CustomFetchMinimalOutput\n} from './fetcher';\n\nexport { MyAccountApiError } from './MyAccountApiClient';\n\nexport { CustomTokenExchangeOptions } from './TokenExchange';\n"],"names":["version","DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS","DEFAULT_POPUP_CONFIG_OPTIONS","timeoutInSeconds","DEFAULT_SILENT_TOKEN_RETRY_COUNT","CLEANUP_IFRAME_TIMEOUT_IN_SECONDS","DEFAULT_FETCH_TIMEOUT_MS","CACHE_LOCATION_MEMORY","MISSING_REFRESH_TOKEN_ERROR_MESSAGE","INVALID_REFRESH_TOKEN_ERROR_MESSAGE","USER_BLOCKED_ERROR_MESSAGE","DEFAULT_SCOPE","DEFAULT_SESSION_CHECK_EXPIRY_DAYS","DEFAULT_AUTH0_CLIENT","name","DEFAULT_NOW_PROVIDER","Date","now","DEFAULT_AUDIENCE","GenericError","Error","constructor","error","error_description","super","this","Object","setPrototypeOf","prototype","static","_ref","AuthenticationError","state","appState","ConnectError","connection","arguments","length","undefined","TimeoutError","PopupTimeoutError","popup","PopupCancelledError","PopupOpenError","MfaRequiredError","mfa_token","mfa_requirements","MissingRefreshTokenError","audience","scope","concat","valueOrEmptyString","MissingScopesError","UseDpopNonceError","newDpopNonce","value","exclude","includes","parseAuthenticationResult","queryString","indexOf","substring","searchParams","URLSearchParams","get","code","connect_code","runIframe","authorizeUrl","eventOrigin","Promise","res","rej","iframe","window","document","createElement","setAttribute","style","display","removeIframe","body","contains","removeChild","removeEventListener","iframeEventHandler","timeoutSetTimeoutId","setTimeout","e","origin","data","type","eventSource","source","close","response","fromPayload","clearTimeout","addEventListener","appendChild","openPopup","url","width","height","left","screenX","innerWidth","top","screenY","innerHeight","open","runPopup","config","resolve","reject","popupEventListener","popupTimer","setInterval","closed","clearInterval","timeoutId","closePopup","getCrypto","crypto","createRandomString","charset","random","randomValues","Array","from","getRandomValues","Uint8Array","forEach","v","encode","btoa","stripUndefined","params","keys","filter","k","reduce","acc","key","assign","ALLOWED_AUTH0CLIENT_PROPERTIES","stripAuth0Client","auth0Client","excludeEnv","allowedProperty","find","p","createQueryParams","_a","clientId","client_id","__rest","toString","sha256","async","digestOp","subtle","digest","TextEncoder","s","urlEncodeB64","input","b64Chars","replace","m","decodeB64","decodeURIComponent","atob","split","map","c","charCodeAt","slice","join","urlDecodeB64","bufferToBase64UrlEncoded","ie11SafeInput","String","fromCharCode","validateCrypto","getDomain","domainUrl","test","getTokenIssuer","issuer","startsWith","parseNumber","parseInt","fromEntries","iterable","obj","val","defineProperty","processLock","ProcessLocking","_this","locked","Map","addToLocked","toAdd","callbacks","set","unshift","isLocked","has","lock","unlock","delete","toCall","pop","getInstance","instance","getLock","default","__awaiter","thisArg","_arguments","P","generator","fulfilled","step","next","rejected","result","done","then","apply","__generator","_","label","sent","t","trys","ops","f","y","g","verb","throw","return","Symbol","iterator","n","op","TypeError","call","push","browserTabsLock","processLock_1","require$$0","LOCK_STORAGE_KEY","DEFAULT_STORAGE_HANDLER","index","getItem","clear","localStorage","removeItem","setItem","keySync","getItemSync","clearSync","removeItemSync","setItemSync","delay","milliseconds","generateRandomString","CHARS","randomstring","i","INDEX","Math","floor","getLockId","SuperTokensLock","storageHandler","acquiredIatSet","Set","id","acquireLock","bind","releaseLock","releaseLock__private__","waitForSomethingToChange","refreshLockWhileAcquired","waiters","lockKey","timeout","iat","MAX_TIME","STORAGE_KEY","STORAGE","lockObj","TIMEOUT_KEY","lockObjPostDelay","parsedLockObjPostDelay","JSON","stringify","timeoutKey","timeAcquired","timeRefreshed","parse","add","lockCorrector","storageKey","parsedLockObj","resolvedCalled","startedAt","MIN_TIME_TO_WAIT","removedListeners","stopWaiting","removeFromWaiting","timeOutId","timeToWait","addToWaiting","max","func","notifyWaiters","parsedlockObj","MIN_ALLOWED_TIME","KEYS","currIndex","LOCK_KEY","_default","WebLocksApiManager","callback","controller","AbortController","abort","navigator","locks","request","mode","signal","LegacyLockManager","activeLocks","BrowserTabsLock","pagehideHandler","retryAttempts","acquired","size","isWebLocksSupported","createLockManager","lockManager","getLockManager","encoder","decoder","TextDecoder","buf","decode","checkRsaKeyAlgorithm","algorithm","modulusLength","OperationProcessingError","subtleAlgorithm","hash","saltLength","UnsupportedOperationError","jwt","header","claimsSet","usages","b64u","signature","sign","encodeBase64Url","toBase64","ArrayBuffer","alphabet","omitPadding","CHUNK_SIZE","arr","byteLength","subarray","message","captureStackTrace","psAlg","rsAlg","esAlg","namedCurve","determineJWSAlgorithm","isCryptoKey","CryptoKey","isPrivateKey","isPublicKey","epochTime","generateProof","keypair","htu","htm","nonce","accessToken","additional","privateKey","publicKey","extractable","isArray","alg","typ","jwk","publicJwk","jti","randomUUID","ath","kty","x","crv","exportKey","generateKeyPair","options","publicExponent","generateKey","calculateThumbprint","components","DPOP_NONCE_HEADER","KEY_PAIR_ALGORITHM","SUPPORTED_GRANT_TYPES","dpopLib","keyPair","normalizeUrl","parsedUrl","URL","search","href","method","normalizedUrl","isGrantTypeSupported","grantType","sendMessage","to","messageChannel","MessageChannel","port1","onmessage","event","postMessage","port2","createAbortController","dofetch","fetchUrl","fetchOptions","fetch","ok","json","headers","fetchWithoutWorker","race","finally","fetchWithWorker","worker","useFormData","useMrrt","auth","switchFetch","getJSON","dpop","isDpopRetry","dpopProof","getNonce","fetchError","setNonce","errorMessage","oauthToken","baseUrl","isTokenExchange","grant_type","refreshWithMrrt","allParams","isDpopSupported","dpopUtils","dedupe","getUniqueScopes","_len","scopes","_key","Boolean","trim","injectDefaultScopes","authScopes","openIdScope","_len2","extraScopes","_key2","requestedScopes","audienceScopes","scopesToRequest","methodScopes","CACHE_KEY_PREFIX","CACHE_KEY_ID_TOKEN_SUFFIX","CacheKey","prefix","suffix","toKey","entry","LocalStorageCache","payload","remove","allKeys","InMemoryCache","enclosedCache","cache","cacheEntry","DEFAULT_EXPIRY_ADJUSTMENT_SECONDS","CacheManager","keyManifest","nowProvider","idToken","decodedToken","cacheKey","getIdTokenCacheKey","id_token","entryByScope","expiryAdjustmentSeconds","cacheMode","wrappedEntry","getCacheKeys","matchedKey","matchExistingCacheKey","getEntryWithRefreshToken","nowSeconds","expiresAt","refresh_token","modifiedCachedEntry","wrapCacheEntry","memo","expiresInTime","expires_in","keyToMatch","fromKey","scopeSet","scopesToMatch","hasAllScopes","current","cachedEntry","oldRefreshToken","newRefreshToken","TRANSACTION_STORAGE_KEY_PREFIX","TransactionManager","storage","cookieDomain","create","transaction","save","daysUntilExpire","isNumber","idTokendecoded","token","parts","payloadJSON","claims","__raw","user","encoded","verify","decoded","iss","sub","aud","azp","max_age","auth_time","exp","leeway","expDate","setUTCSeconds","nbf","nbfDate","authTimeDate","organization","org","orgId","org_id","orgName","toLowerCase","org_name","__assign","hasOwnProperty","stringifyAttribute","stringified","stringifyAttributes","attributes","expires","setMilliseconds","getMilliseconds","toUTCString","domain","path","secure","sameSite","encodeURIComponent","cookieString","cookies","rdecode","cookie","charAt","name_1","getAll","get_1","set_1","remove_1","CookieStorage","Cookies","cookieAttributes","location","protocol","LEGACY_PREFIX","CookieStorageWithLegacySameSite","SessionStorage","sessionStorage","exports","ResponseType","User","singlePromiseMap","singlePromise","cb","promise","CacheKeyManifest","manifestKey","createManifestKeyFrom","GET_TOKEN_SILENTLY_LOCK_KEY","GET_TOKEN_FROM_IFRAME_LOCK_KEY","buildGetTokenSilentlyLockKey","buildIframeLockKey","buildOrganizationHintCookieName","OLD_IS_AUTHENTICATED_COOKIE_NAME","buildIsAuthenticatedCookieName","cacheLocationBuilders","memory","localstorage","cacheFactory","getAuthorizeParams","clientOptions","authorizationParams","code_challenge","redirect_uri","response_mode","thumbprint","response_type","code_challenge_method","dpop_jkt","patchOpenUrlWithOnRedirect","openUrl","onRedirect","originalOptions","allScopesAreIncluded","scopeToInclude","scopeGroup","scopesToInclude","every","getMissingScopes","requestedScope","respondedScope","respondedScopes","missingScopes","getScopeToRequest","cachedAudience","cachedScope","cachedScopes","newScopes","newScopesAreIncluded","isRefreshWithMrrt","requestAudience","requestScope","VERSION","NAME","TABLES","NONCE","KEYPAIR","AUTH0_NONCE_ID","DpopStorage","getVersion","createDbHandle","req","indexedDB","onupgradeneeded","values","createObjectStore","onerror","onsuccess","dbHandle","table","requestFactory","db","getDbHandle","txn","store","objectStore","buildKey","finalId","setKeyPair","executeDbRequest","put","findNonce","findKeyPair","predicate","getAllKeys","deleteByClientId","deleteBy","clearNonces","clearKeyPairs","Dpop","getOrGenerateKeyPair","all","TokenType","Fetcher","hooks","isAbsoluteUrl","buildUrl","getAccessToken","authParams","extractUrl","info","buildBaseRequest","init","Request","finalUrl","finalInfo","setAuthorizationHeader","tokenType","Bearer","dpopNonceId","dpopNonce","getDpopNonce","generateDpopProof","accessTokenResponse","DPoP","token_type","access_token","setDpopProofHeader","getHeader","Headers","hasUseDpopNonceError","status","wwwAuthHeader","setDpopNonce","onUseDpopNonceError","prepareRequest","handleResponse","fetchWithAuth","internalFetchWithAuth","MyAccountApiClient","myAccountFetcher","apiBase","_handleResponse","text","err","MyAccountApiError","title","detail","validation_errors","FACTOR_MAPPING","otp","authenticatorTypes","sms","oobChannels","email","voice","MfaGrantTypes","OTP","OOB","RECOVERY_CODE","getAuthJsEnrollParams","mapping","factorType","mfaToken","phoneNumber","getGrantType","oobCode","recoveryCode","USER_AGENT","_navigator$userAgent","userAgent","_navigator$userAgent$","expected","getPrototypeOf","toStringTag","_unused","ERR_INVALID_ARG_VALUE","ERR_INVALID_ARG_TYPE","CodedTypeError","cause","allowInsecureRequests","clockSkew","customFetch","modifyAssertion","jweDecrypt","fromBase64","decodeBase64Url","binary","bytes","_Error$captureStackTr","_defineProperty","UNSUPPORTED_OPERATION","_Error$captureStackTr2","OPE","assertCryptoKey","it","assertPrivateKey","isJsonObject","prepareHeaders","looseInstanceOf","entries","AbortSignal","pathname","wellKnown","allowTerminatingSlash","appendWellKnown","replaceDoubleSlash","performDiscovery","urlName","checkProtocol","transform","redirect","discoveryRequest","issuerIdentifier","prependWellKnown","assertNumber","Number","isFinite","assertString","processDiscoveryResponse","expectedIssuerIdentifier","_nodiscoverycheck","Response","RESPONSE_IS_NOT_CONFORM","getResponseJsonBody","JSON_ATTRIBUTE_COMPARISON","attribute","notJson","types","last","msg","RESPONSE_IS_NOT_JSON","assertContentType","getContentType","contentType","randomBytes","calculatePKCECodeChallenge","codeVerifier","getKeyAndKid","kid","keyToJws","getClockSkew","client","skew","getClockTolerance","tolerance","clockTolerance","as","clientSecret","_as","_headers","clientAssertionPayload","clientPrivateKey","_options$modifyAssert","signJwt","None","TlsClientAuth","keyToSubtle","URLParse","base","_unused2","enforceHttps","HTTP_REQUEST_FORBIDDEN","REQUEST_PROTOCOL_FORBIDDEN","validateEndpoint","endpoint","useMtlsAlias","MISSING_SERVER_METADATA","INVALID_SERVER_METADATA","resolveEndpoint","mtls_endpoint_aliases","pushedAuthorizationRequest","parameters","_options$DPoP","assertAs","assertClient","use_mtls_endpoint_aliases","assertDPoP","addProof","authenticatedRequest","clientAuthentication","cacheNonce","isDPoPNonceError","WWWAuthenticateChallengeError","challenge","scheme","ResponseBodyError","_Error$captureStackTr3","RESPONSE_BODY_ERROR","enumerable","AuthorizationResponseError","buffers","buffer","string","decodeBase64","JOSEError","JWTClaimValidationFailed","claim","reason","JWTExpired","JOSEAlgNotAllowed","JOSENotSupported","JWEDecryptionFailed","JWEInvalid","JWSInvalid","JWTInvalid","JWKInvalid","JWKSInvalid","JWKSNoMatchingKey","JWKSMultipleMatchingKeys","asyncIterator","JWKSTimeout","JWSSignatureVerificationFailed","unusable","prop","isAlgorithm","getHashLength","getNamedCurve","checkUsage","usage","checkSigCryptoKey","actual","_actual$constructor","invalidKeyInput","withAlg","_len3","_key3","isKeyObject","isKeyLike","isDisjoint","sources","parameter","isObjectLike","isObject","proto","checkKeyLength","bytesEqual","a","b","createASN1State","pos","parseLength","first","lengthOfLen","expectTag","expectedTag","getSubarray","parseAlgorithmOID","oidLen","parsePKCS8Header","verLen","algIdLen","algIdStart","algIdLength","parseECAlgorithmIdentifier","algOid","curveOidLen","curveOid","oid","genericImport","keyFormat","keyData","_options$extractable","keyUsages","isPublic","getSigUsages","getEncUsages","curveMap","ES256","ES384","ES512","importKey","processPEMData","pem","pattern","fromPKCS8","_alg$startsWith","opts","subtleMapping","priv","d","jwkToKey","_jwk$ext","_jwk$key_ops","_objectSpread","use","ext","key_ops","importPKCS8","pkcs8","importJWK","decodeBase64URL","oth","validateCrit","Err","recognizedDefault","recognizedOption","protectedHeader","joseHeader","crit","some","recognized","validateAlgorithms","option","algorithms","isJWK","isPrivateJWK","isPublicJWK","isSecretJWK","handleJWK","freeze","WeakMap","cached","cryptoKey","handleKeyObject","keyObject","asymmetricKeyType","toCryptoKey","toUpperCase","_keyObject$asymmetric","nist","asymmetricKeyDetails","normalizeKey","export","format","tag","jwkMatchesOp","_key$key_ops","_key$key_ops$includes","expectedKeyOp","endsWith","symmetricTypeCheck","asymmetricTypeCheck","checkKeyType","int","props","tbi","ClientSecretPost","client_secret","oauth","PrivateKeyJwt","randomPKCECodeVerifier","ClientError","errorHandler","DOMException","handleEntraId","server","kEntraId","handleB2Clogin","hostname","discovery","metadata","Configuration","internals","execute","extension","getSigKey","flattenedVerify","jws","protected","parsedProt","extensions","b64","resolvedKey","verified","_unused3","unprotectedHeader","compactVerify","epoch","date","getTime","minute","hour","day","week","year","REGEX","secs","str","matched","exec","parseFloat","unit","numericDate","round","normalizeTyp","checkAudiencePresence","audPayload","audOption","validateClaimsSet","encodedPayload","requiredClaims","subject","maxTokenAge","presenceCheck","reverse","currentDate","age","jwtVerify","_verified$protectedHe","getKtyFromAlg","isJWKSLike","jwks","isJWKLike","_jwks","_cached2","LocalJWKSet","_classPrivateFieldInitSpec","_classPrivateFieldSet","structuredClone","_classPrivateFieldGet","candidates","candidate","_cached","_wrapAsyncGenerator","_awaitAsyncGenerator","importWithAlgCache","createLocalJWKSet","localJWKSet","getKey","defineProperties","configurable","writable","isCloudflareWorkers","WebSocketPair","EdgeRuntime","fetchJwks","fetchImpl","catch","jwksCache","isFreshJwksCache","cacheMaxAge","uat","_url","_timeoutDuration","_cooldownDuration","_cacheMaxAge","_jwksTimestamp","_pendingFetch","_customFetch","_local","_cache","RemoteJWKSet","timeoutDuration","cooldownDuration","append","pendingFetch","coolingDown","fresh","_classPrivateFieldGet2","reload","createRemoteJWKSet","remoteJWKSet","reloading","DEFAULT_SCOPES","MAX_ARRAY_VALUES_PER_KEY","PARAM_DENYLIST","validateSubjectToken","TokenExchangeError","appendExtraParams","extra","parameterKey","parameterValue","arrayItem","TOKEN_EXCHANGE_GRANT_TYPE","SUBJECT_TYPE_REFRESH_TOKEN","SUBJECT_TYPE_ACCESS_TOKEN","REQUESTED_TOKEN_TYPE_FEDERATED_CONNECTION_ACCESS_TOKEN","AuthClient","_configuration","_serverMetadata","_options","_Class8_brand","WeakSet","_classPrivateMethodInitSpec","useMtls","NotSupportedError","mfa","MfaClient","serverMetadata","_assertClassBrand","_discover","pushedAuthorizationRequests","pushed_authorization_request_endpoint","_buildAuthorizationUrl","BuildAuthorizationUrlError","requested_connection","requested_connection_scope","connectionScope","id_token_hint","linkUserUrl","authorizationUrl","BuildLinkUserUrlError","unlinkUserUrl","BuildUnlinkUserUrlError","configuration","additionalParams","stripUndefinedProperties","binding_message","bindingMessage","login_hint","loginHint","requestedExpiry","authorizationDetails","tokenEndpointResponse","backchannelAuthenticationResponse","TokenResponse","fromTokenEndpointResponse","BackchannelAuthenticationError","auth_req_id","expiresIn","interval","_ref2","authReqId","_options$accessToken","refreshToken","TokenForConnectionError","subjectTokenValue","exchangeToken","subjectToken","subjectTokenType","_exchangeTokenVaultToken","_exchangeProfileToken","pkceCodeVerifier","TokenByRefreshTokenError","TokenByClientCredentialsError","end_session_endpoint","returnTo","post_logout_redirect_uri","jwks_uri","customFetch2","logoutToken","VerifyLogoutTokenError","sid","events","clientAuth","_getClientAuth","customFetch$1","_options$subjectToken","_options$requestedTok","subject_token","subject_token_type","requested_token_type","requestedTokenType","tokenRequestParams","GRANT_TYPE_FEDERATED_CONNECTION_ACCESS_TOKEN","clientAssertionSigningKey","MissingClientAuthError","clientAssertionSigningAlg","codeChallengeMethod","codeChallenge","MfaError","MfaListAuthenticatorsError","MfaEnrollmentError","MfaChallengeError","MfaVerifyError","MfaEnrollmentFactorsError","DEFAULT_TTL_MS","MfaContextManager","ttlMs","contexts","context","cleanup","createdAt","MfaApiClient","authJsMfaClient","contextManager","setMFAAuthDetails","mfaRequirements","challengeTypes","allAuthenticators","listAuthenticators","Auth0JsMfaListAuthenticatorsError","_b","authJsParams","enrollAuthenticator","Auth0JsMfaEnrollmentError","challengeType","authenticatorId","challengeAuthenticator","Auth0JsMfaChallengeError","enroll","_requestTokenForMfa","oob_code","binding_code","bindingCode","recovery_code","Auth0Client","userCache","defaultOptions","useRefreshTokensFallback","cacheLocation","console","warn","httpTimeoutMs","httpTimeoutInSeconds","cookieStorage","legacySameSiteCookie","orgHintCookieName","isAuthenticatedCookieName","sessionCheckExpiryDays","transactionStorage","useCookiesForTransactions","useRefreshTokens","transactionManager","cacheManager","useDpop","tokenIssuer","myAccountApiIdentifier","createFetcher","getTokenSilently","detailedResponse","myAccountApi","authJsClient","Auth0AuthJsClient","Worker","workerUrl","TokenWorker","getConfiguration","auth0ClientObj","strippedAuth0Client","_authorizeUrl","authorizeOptions","verifyIdToken","_processOrgHint","fallbackRedirectUri","code_verifier","code_challengeBuffer","_prepareAuthorizeUrl","codeResult","authorizeTimeoutInSeconds","_requestToken","nonceIn","_getIdTokenFromCache","fragment","urlOptions","_c","Code","urlWithFragment","queryStringFragments","authenticationResult","ConnectCode","_handleConnectAccountRedirectCallback","_handleLoginRedirectCallback","connectResult","auth_session","completeAccount","localOptions","_getTokenSilently","getTokenOptions","_getEntryFromCache","runWithLock","authResult","_getTokenUsingRefreshToken","_getTokenFromIFrame","oauthTokenScope","loginWithPopup","getUser","_buildLogoutUrl","logoutParams","federated","logoutOptions","federatedQuery","iframeLockKey","prompt","orgHint","stateIn","crossOriginIsolated","authorizeTimeout","tokenResult","logout","updateEntry","isRefreshMrrt","tokenHasAllScopes","entryWithoutIdToken","setIdToken","getIdToken","currentCache","additionalParameters","_verifyIdToken","existingIdToken","_saveEntryInCache","loginWithCustomTokenExchange","_assertDpop","isDpopEnabled","authorization_params","redirectUri","connect_uri","connect_params","connectAccount","ticket","restOptions","createAuth0Client","auth0","checkSession"],"mappings":";;;;;;;;;;;;;;;;;IAAA,IAAAA,UAAe;ICMR,MAAMC,uCAAuC;IAK7C,MAAMC,+BAAmD;QAC9DC,kBAAkBF;;IAMb,MAAMG,mCAAmC;IAKzC,MAAMC,oCAAoC;IAK1C,MAAMC,2BAA2B;IAEjC,MAAMC,wBAAwB;IAM9B,MAAMC,sCAAsC;IAK5C,MAAMC,sCAAsC;IAK5C,MAAMC,6BAA6B;IAKnC,MAAMC,gBAAgB;IAKtB,MAAMC,oCAAoC;IAK1C,MAAMC,uBAAuB;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-js.development.js","sources":["../src/version.ts","../src/constants.ts","../src/errors.ts","../src/utils.ts","../node_modules/browser-tabs-lock/processLock.js","../node_modules/browser-tabs-lock/index.js","../src/lock.ts","../node_modules/dpop/src/index.ts","../src/dpop/utils.ts","../src/worker/worker.utils.ts","../src/http.ts","../src/api.ts","../src/scope.ts","../src/cache/shared.ts","../src/cache/cache-localstorage.ts","../src/cache/cache-memory.ts","../src/cache/cache-manager.ts","../src/transaction-manager.ts","../src/jwt.ts","../node_modules/es-cookie/src/es-cookie.js","../src/storage.ts","../src/global.ts","../src/promise-utils.ts","../src/cache/key-manifest.ts","../src/Auth0Client.utils.ts","../src/dpop/storage.ts","../src/dpop/dpop.ts","../src/fetcher.ts","../src/MyAccountApiClient.ts","../src/mfa/constants.ts","../src/mfa/utils.ts","../node_modules/oauth4webapi/src/index.ts","../node_modules/jose/dist/webapi/lib/buffer_utils.js","../node_modules/jose/dist/webapi/lib/base64.js","../node_modules/jose/dist/webapi/util/base64url.js","../node_modules/jose/dist/webapi/util/errors.js","../node_modules/jose/dist/webapi/lib/crypto_key.js","../node_modules/jose/dist/webapi/lib/invalid_key_input.js","../node_modules/jose/dist/webapi/lib/is_key_like.js","../node_modules/jose/dist/webapi/lib/is_disjoint.js","../node_modules/jose/dist/webapi/lib/is_object.js","../node_modules/jose/dist/webapi/lib/check_key_length.js","../node_modules/jose/dist/webapi/lib/asn1.js","../node_modules/jose/dist/webapi/lib/jwk_to_key.js","../node_modules/jose/dist/webapi/key/import.js","../node_modules/jose/dist/webapi/lib/validate_crit.js","../node_modules/jose/dist/webapi/lib/validate_algorithms.js","../node_modules/jose/dist/webapi/lib/is_jwk.js","../node_modules/jose/dist/webapi/lib/normalize_key.js","../node_modules/jose/dist/webapi/lib/check_key_type.js","../node_modules/openid-client/src/index.ts","../node_modules/jose/dist/webapi/lib/subtle_dsa.js","../node_modules/jose/dist/webapi/lib/get_sign_verify_key.js","../node_modules/jose/dist/webapi/lib/verify.js","../node_modules/jose/dist/webapi/jws/flattened/verify.js","../node_modules/jose/dist/webapi/jws/compact/verify.js","../node_modules/jose/dist/webapi/lib/jwt_claims_set.js","../node_modules/jose/dist/webapi/jwt/verify.js","../node_modules/jose/dist/webapi/jwks/local.js","../node_modules/jose/dist/webapi/jwks/remote.js","../node_modules/@auth0/auth0-auth-js/src/errors.ts","../node_modules/@auth0/auth0-auth-js/src/utils.ts","../node_modules/@auth0/auth0-auth-js/src/mfa/errors.ts","../node_modules/@auth0/auth0-auth-js/src/mfa/utils.ts","../node_modules/@auth0/auth0-auth-js/src/mfa/mfa-client.ts","../node_modules/@auth0/auth0-auth-js/src/types.ts","../node_modules/@auth0/auth0-auth-js/src/auth-client.ts","../src/mfa/errors.ts","../src/mfa/MfaContextManager.ts","../src/mfa/MfaApiClient.ts","../src/Auth0Client.ts","../src/index.ts"],"sourcesContent":["export default '2.16.0';\n","import { PopupConfigOptions } from './global';\nimport version from './version';\n\n/**\n * @ignore\n */\nexport const DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS = 60;\n\n/**\n * @ignore\n */\nexport const DEFAULT_POPUP_CONFIG_OPTIONS: PopupConfigOptions = {\n timeoutInSeconds: DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS\n};\n\n/**\n * @ignore\n */\nexport const DEFAULT_SILENT_TOKEN_RETRY_COUNT = 3;\n\n/**\n * @ignore\n */\nexport const CLEANUP_IFRAME_TIMEOUT_IN_SECONDS = 2;\n\n/**\n * @ignore\n */\nexport const DEFAULT_FETCH_TIMEOUT_MS = 10000;\n\nexport const CACHE_LOCATION_MEMORY = 'memory';\nexport const CACHE_LOCATION_LOCAL_STORAGE = 'localstorage';\n\n/**\n * @ignore\n */\nexport const MISSING_REFRESH_TOKEN_ERROR_MESSAGE = 'Missing Refresh Token';\n\n/**\n * @ignore\n */\nexport const INVALID_REFRESH_TOKEN_ERROR_MESSAGE = 'invalid refresh token';\n\n/**\n * @ignore\n */\nexport const USER_BLOCKED_ERROR_MESSAGE = 'user is blocked';\n\n/**\n * @ignore\n */\nexport const DEFAULT_SCOPE = 'openid profile email';\n\n/**\n * @ignore\n */\nexport const DEFAULT_SESSION_CHECK_EXPIRY_DAYS = 1;\n\n/**\n * @ignore\n */\nexport const DEFAULT_AUTH0_CLIENT = {\n name: 'auth0-spa-js',\n version: version\n};\n\nexport const DEFAULT_NOW_PROVIDER = () => Date.now();\n\nexport const DEFAULT_AUDIENCE = 'default';\n","/**\n * MFA requirements from an mfa_required error response\n */\nexport interface MfaRequirements {\n /** Required enrollment types */\n enroll?: Array<{ type: string }>;\n /** Required challenge types */\n challenge?: Array<{ type: string }>;\n}\n\n/**\n * Thrown when network requests to the Auth server fail.\n */\nexport class GenericError extends Error {\n constructor(public error: string, public error_description: string) {\n super(error_description);\n Object.setPrototypeOf(this, GenericError.prototype);\n }\n\n static fromPayload({\n error,\n error_description\n }: {\n error: string;\n error_description: string;\n }) {\n return new GenericError(error, error_description);\n }\n}\n\n/**\n * Thrown when handling the redirect callback fails, will be one of Auth0's\n * Authentication API's Standard Error Responses: https://auth0.com/docs/api/authentication?javascript#standard-error-responses\n */\nexport class AuthenticationError extends GenericError {\n constructor(\n error: string,\n error_description: string,\n public state: string,\n public appState: any = null\n ) {\n super(error, error_description);\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, AuthenticationError.prototype);\n }\n}\n\n/**\n * Thrown when handling the redirect callback for the connect flow fails, will be one of Auth0's\n * Authentication API's Standard Error Responses: https://auth0.com/docs/api/authentication?javascript#standard-error-responses\n */\nexport class ConnectError extends GenericError {\n constructor(\n error: string,\n error_description: string,\n public connection: string,\n public state: string,\n public appState: any = null\n ) {\n super(error, error_description);\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, ConnectError.prototype);\n }\n}\n\n/**\n * Thrown when silent auth times out (usually due to a configuration issue) or\n * when network requests to the Auth server timeout.\n */\nexport class TimeoutError extends GenericError {\n constructor() {\n super('timeout', 'Timeout');\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, TimeoutError.prototype);\n }\n}\n\n/**\n * Error thrown when the login popup times out (if the user does not complete auth)\n */\nexport class PopupTimeoutError extends TimeoutError {\n constructor(public popup: Window) {\n super();\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, PopupTimeoutError.prototype);\n }\n}\n\nexport class PopupCancelledError extends GenericError {\n constructor(public popup: Window) {\n super('cancelled', 'Popup closed');\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, PopupCancelledError.prototype);\n }\n}\n\nexport class PopupOpenError extends GenericError {\n constructor() {\n super('popup_open', 'Unable to open a popup for loginWithPopup - window.open returned `null`');\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, PopupOpenError.prototype);\n }\n}\n\n/**\n * Error thrown when the token exchange results in a `mfa_required` error\n */\nexport class MfaRequiredError extends GenericError {\n constructor(\n error: string,\n error_description: string,\n public mfa_token: string,\n public mfa_requirements: MfaRequirements\n ) {\n super(error, error_description);\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, MfaRequiredError.prototype);\n }\n}\n\n/**\n * Error thrown when there is no refresh token to use\n */\nexport class MissingRefreshTokenError extends GenericError {\n constructor(public audience: string, public scope: string) {\n super(\n 'missing_refresh_token',\n `Missing Refresh Token (audience: '${valueOrEmptyString(audience, [\n 'default'\n ])}', scope: '${valueOrEmptyString(scope)}')`\n );\n Object.setPrototypeOf(this, MissingRefreshTokenError.prototype);\n }\n}\n\n/**\n * Error thrown when there are missing scopes after refreshing a token\n */\nexport class MissingScopesError extends GenericError {\n constructor(public audience: string, public scope: string) {\n super(\n 'missing_scopes',\n `Missing requested scopes after refresh (audience: '${valueOrEmptyString(audience, [\n 'default'\n ])}', missing scope: '${valueOrEmptyString(scope)}')`\n );\n Object.setPrototypeOf(this, MissingScopesError.prototype);\n }\n}\n\n/**\n * Error thrown when the wrong DPoP nonce is used and a potential subsequent retry wasn't able to fix it.\n */\nexport class UseDpopNonceError extends GenericError {\n constructor(public newDpopNonce: string | undefined) {\n super('use_dpop_nonce', 'Server rejected DPoP proof: wrong nonce');\n\n Object.setPrototypeOf(this, UseDpopNonceError.prototype);\n }\n}\n\n/**\n * Returns an empty string when value is falsy, or when it's value is included in the exclude argument.\n * @param value The value to check\n * @param exclude An array of values that should result in an empty string.\n * @returns The value, or an empty string when falsy or included in the exclude argument.\n */\nfunction valueOrEmptyString(value: string, exclude: string[] = []) {\n return value && !exclude.includes(value) ? value : '';\n}\n","import { AuthenticationResult, PopupConfigOptions } from './global';\n\nimport {\n DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS,\n CLEANUP_IFRAME_TIMEOUT_IN_SECONDS\n} from './constants';\n\nimport {\n PopupTimeoutError,\n TimeoutError,\n GenericError,\n PopupCancelledError\n} from './errors';\n\nexport const parseAuthenticationResult = (\n queryString: string\n): AuthenticationResult => {\n if (queryString.indexOf('#') > -1) {\n queryString = queryString.substring(0, queryString.indexOf('#'));\n }\n\n const searchParams = new URLSearchParams(queryString);\n\n return {\n state: searchParams.get('state')!,\n code: searchParams.get('code') || undefined,\n connect_code: searchParams.get('connect_code') || undefined,\n error: searchParams.get('error') || undefined,\n error_description: searchParams.get('error_description') || undefined\n };\n};\n\nexport const runIframe = (\n authorizeUrl: string,\n eventOrigin: string,\n timeoutInSeconds: number = DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS\n) => {\n return new Promise<AuthenticationResult>((res, rej) => {\n const iframe = window.document.createElement('iframe');\n\n iframe.setAttribute('width', '0');\n iframe.setAttribute('height', '0');\n iframe.style.display = 'none';\n\n const removeIframe = () => {\n if (window.document.body.contains(iframe)) {\n window.document.body.removeChild(iframe);\n window.removeEventListener('message', iframeEventHandler, false);\n }\n };\n\n let iframeEventHandler: (e: MessageEvent) => void;\n\n const timeoutSetTimeoutId = setTimeout(() => {\n rej(new TimeoutError());\n removeIframe();\n }, timeoutInSeconds * 1000);\n\n iframeEventHandler = function (e: MessageEvent) {\n if (e.origin != eventOrigin) return;\n if (!e.data || e.data.type !== 'authorization_response') return;\n\n const eventSource = e.source;\n\n if (eventSource) {\n (eventSource as any).close();\n }\n\n e.data.response.error\n ? rej(GenericError.fromPayload(e.data.response))\n : res(e.data.response);\n\n clearTimeout(timeoutSetTimeoutId);\n window.removeEventListener('message', iframeEventHandler, false);\n\n // Delay the removal of the iframe to prevent hanging loading status\n // in Chrome: https://github.com/auth0/auth0-spa-js/issues/240\n setTimeout(removeIframe, CLEANUP_IFRAME_TIMEOUT_IN_SECONDS * 1000);\n };\n\n window.addEventListener('message', iframeEventHandler, false);\n window.document.body.appendChild(iframe);\n iframe.setAttribute('src', authorizeUrl);\n });\n};\n\nexport const openPopup = (url: string) => {\n const width = 400;\n const height = 600;\n const left = window.screenX + (window.innerWidth - width) / 2;\n const top = window.screenY + (window.innerHeight - height) / 2;\n\n return window.open(\n url,\n 'auth0:authorize:popup',\n `left=${left},top=${top},width=${width},height=${height},resizable,scrollbars=yes,status=1`\n );\n};\n\nexport const runPopup = (config: PopupConfigOptions) => {\n return new Promise<AuthenticationResult>((resolve, reject) => {\n let popupEventListener: (e: MessageEvent) => void;\n\n // Check each second if the popup is closed triggering a PopupCancelledError\n const popupTimer = setInterval(() => {\n if (config.popup && config.popup.closed) {\n clearInterval(popupTimer);\n clearTimeout(timeoutId);\n window.removeEventListener('message', popupEventListener, false);\n reject(new PopupCancelledError(config.popup));\n }\n }, 1000);\n\n const timeoutId = setTimeout(() => {\n clearInterval(popupTimer);\n reject(new PopupTimeoutError(config.popup));\n window.removeEventListener('message', popupEventListener, false);\n }, (config.timeoutInSeconds || DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS) * 1000);\n\n popupEventListener = function (e: MessageEvent) {\n if (!e.data || e.data.type !== 'authorization_response') {\n return;\n }\n\n clearTimeout(timeoutId);\n clearInterval(popupTimer);\n window.removeEventListener('message', popupEventListener, false);\n\n // Close popup automatically unless closePopup is explicitly set to false\n if (config.closePopup !== false) {\n config.popup.close();\n }\n\n if (e.data.response.error) {\n return reject(GenericError.fromPayload(e.data.response));\n }\n\n resolve(e.data.response);\n };\n\n window.addEventListener('message', popupEventListener);\n });\n};\n\nexport const getCrypto = () => {\n return window.crypto;\n};\n\nexport const createRandomString = () => {\n const charset =\n '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_~.';\n let random = '';\n const randomValues = Array.from(\n getCrypto().getRandomValues(new Uint8Array(43))\n );\n randomValues.forEach(v => (random += charset[v % charset.length]));\n return random;\n};\n\nexport const encode = (value: string) => btoa(value);\nexport const decode = (value: string) => atob(value);\n\nconst stripUndefined = (params: any) => {\n return Object.keys(params)\n .filter(k => typeof params[k] !== 'undefined')\n .reduce((acc, key) => ({ ...acc, [key]: params[key] }), {});\n};\n\nconst ALLOWED_AUTH0CLIENT_PROPERTIES = [\n {\n key: 'name',\n type: ['string']\n },\n {\n key: 'version',\n type: ['string', 'number']\n },\n {\n key: 'env',\n type: ['object']\n }\n];\n\n/**\n * Strips any property that is not present in ALLOWED_AUTH0CLIENT_PROPERTIES\n * @param auth0Client - The full auth0Client object\n * @param excludeEnv - If true, excludes the 'env' property from the result\n * @returns The stripped auth0Client object\n */\nexport const stripAuth0Client = (auth0Client: any, excludeEnv = false) => {\n return Object.keys(auth0Client).reduce((acc: any, key: string) => {\n // Exclude 'env' if requested (for /authorize query params to prevent truncation)\n if (excludeEnv && key === 'env') {\n return acc;\n }\n\n const allowedProperty = ALLOWED_AUTH0CLIENT_PROPERTIES.find(\n p => p.key === key\n );\n if (\n allowedProperty &&\n allowedProperty.type.includes(typeof auth0Client[key])\n ) {\n acc[key] = auth0Client[key];\n }\n\n return acc;\n }, {});\n};\n\nexport const createQueryParams = ({ clientId: client_id, ...params }: any) => {\n return new URLSearchParams(\n stripUndefined({ client_id, ...params })\n ).toString();\n};\n\nexport const sha256 = async (s: string) => {\n const digestOp: any = getCrypto().subtle.digest(\n { name: 'SHA-256' },\n new TextEncoder().encode(s)\n );\n\n return await digestOp;\n};\n\nconst urlEncodeB64 = (input: string) => {\n const b64Chars: { [index: string]: string } = { '+': '-', '/': '_', '=': '' };\n return input.replace(/[+/=]/g, (m: string) => b64Chars[m]);\n};\n\n// https://stackoverflow.com/questions/30106476/\nconst decodeB64 = (input: string) =>\n decodeURIComponent(\n atob(input)\n .split('')\n .map(c => {\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);\n })\n .join('')\n );\n\nexport const urlDecodeB64 = (input: string) =>\n decodeB64(input.replace(/_/g, '/').replace(/-/g, '+'));\n\nexport const bufferToBase64UrlEncoded = (input: number[] | Uint8Array) => {\n const ie11SafeInput = new Uint8Array(input);\n return urlEncodeB64(\n window.btoa(String.fromCharCode(...Array.from(ie11SafeInput)))\n );\n};\n\nexport const validateCrypto = () => {\n if (!getCrypto()) {\n throw new Error(\n 'For security reasons, `window.crypto` is required to run `auth0-spa-js`.'\n );\n }\n if (typeof getCrypto().subtle === 'undefined') {\n throw new Error(`\n auth0-spa-js must run on a secure origin. See https://github.com/auth0/auth0-spa-js/blob/main/FAQ.md#why-do-i-get-auth0-spa-js-must-run-on-a-secure-origin for more information.\n `);\n }\n};\n\n/**\n * @ignore\n */\nexport const getDomain = (domainUrl: string) => {\n if (!/^https?:\\/\\//.test(domainUrl)) {\n return `https://${domainUrl}`;\n }\n\n return domainUrl;\n};\n\n/**\n * @ignore\n */\nexport const getTokenIssuer = (\n issuer: string | undefined,\n domainUrl: string\n) => {\n if (issuer) {\n return issuer.startsWith('https://') ? issuer : `https://${issuer}/`;\n }\n\n return `${domainUrl}/`;\n};\n\nexport const parseNumber = (value: any): number | undefined => {\n if (typeof value !== 'string') {\n return value;\n }\n return parseInt(value, 10) || undefined;\n};\n\n/**\n * Ponyfill for `Object.fromEntries()`, which is not available until ES2020.\n *\n * When the target of this project reaches ES2020, this can be removed.\n */\nexport const fromEntries = <T = any>(\n iterable: Iterable<[PropertyKey, T]>\n): Record<PropertyKey, T> => {\n return [...iterable].reduce((obj, [key, val]) => {\n obj[key] = val;\n\n return obj;\n }, {} as Record<PropertyKey, T>);\n};\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ProcessLocking = /** @class */ (function () {\n function ProcessLocking() {\n var _this = this;\n this.locked = new Map();\n this.addToLocked = function (key, toAdd) {\n var callbacks = _this.locked.get(key);\n if (callbacks === undefined) {\n if (toAdd === undefined) {\n _this.locked.set(key, []);\n }\n else {\n _this.locked.set(key, [toAdd]);\n }\n }\n else {\n if (toAdd !== undefined) {\n callbacks.unshift(toAdd);\n _this.locked.set(key, callbacks);\n }\n }\n };\n this.isLocked = function (key) {\n return _this.locked.has(key);\n };\n this.lock = function (key) {\n return new Promise(function (resolve, reject) {\n if (_this.isLocked(key)) {\n _this.addToLocked(key, resolve);\n }\n else {\n _this.addToLocked(key);\n resolve();\n }\n });\n };\n this.unlock = function (key) {\n var callbacks = _this.locked.get(key);\n if (callbacks === undefined || callbacks.length === 0) {\n _this.locked.delete(key);\n return;\n }\n var toCall = callbacks.pop();\n _this.locked.set(key, callbacks);\n if (toCall !== undefined) {\n setTimeout(toCall, 0);\n }\n };\n }\n ProcessLocking.getInstance = function () {\n if (ProcessLocking.instance === undefined) {\n ProcessLocking.instance = new ProcessLocking();\n }\n return ProcessLocking.instance;\n };\n return ProcessLocking;\n}());\nfunction getLock() {\n return ProcessLocking.getInstance();\n}\nexports.default = getLock;\n","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nvar _this = this;\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar processLock_1 = require(\"./processLock\");\n/**\n * @author: SuperTokens (https://github.com/supertokens)\n * This library was created as a part of a larger project, SuperTokens(https://supertokens.io) - the best session management solution.\n * You can also check out our other projects on https://github.com/supertokens\n *\n * To contribute to this package visit https://github.com/supertokens/browser-tabs-lock\n * If you face any problems you can file an issue on https://github.com/supertokens/browser-tabs-lock/issues\n *\n * If you have any questions or if you just want to say hi visit https://supertokens.io/discord\n */\n/**\n * @constant\n * @type {string}\n * @default\n * @description All the locks taken by this package will have this as prefix\n*/\nvar LOCK_STORAGE_KEY = 'browser-tabs-lock-key';\nvar DEFAULT_STORAGE_HANDLER = {\n key: function (index) { return __awaiter(_this, void 0, void 0, function () {\n return __generator(this, function (_a) {\n throw new Error(\"Unsupported\");\n });\n }); },\n getItem: function (key) { return __awaiter(_this, void 0, void 0, function () {\n return __generator(this, function (_a) {\n throw new Error(\"Unsupported\");\n });\n }); },\n clear: function () { return __awaiter(_this, void 0, void 0, function () {\n return __generator(this, function (_a) {\n return [2 /*return*/, window.localStorage.clear()];\n });\n }); },\n removeItem: function (key) { return __awaiter(_this, void 0, void 0, function () {\n return __generator(this, function (_a) {\n throw new Error(\"Unsupported\");\n });\n }); },\n setItem: function (key, value) { return __awaiter(_this, void 0, void 0, function () {\n return __generator(this, function (_a) {\n throw new Error(\"Unsupported\");\n });\n }); },\n keySync: function (index) {\n return window.localStorage.key(index);\n },\n getItemSync: function (key) {\n return window.localStorage.getItem(key);\n },\n clearSync: function () {\n return window.localStorage.clear();\n },\n removeItemSync: function (key) {\n return window.localStorage.removeItem(key);\n },\n setItemSync: function (key, value) {\n return window.localStorage.setItem(key, value);\n },\n};\n/**\n * @function delay\n * @param {number} milliseconds - How long the delay should be in terms of milliseconds\n * @returns {Promise<void>}\n */\nfunction delay(milliseconds) {\n return new Promise(function (resolve) { return setTimeout(resolve, milliseconds); });\n}\n/**\n * @function generateRandomString\n * @params {number} length - How long the random string should be\n * @returns {string}\n * @description returns random string whose length is equal to the length passed as parameter\n */\nfunction generateRandomString(length) {\n var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz';\n var randomstring = '';\n for (var i = 0; i < length; i++) {\n var INDEX = Math.floor(Math.random() * CHARS.length);\n randomstring += CHARS[INDEX];\n }\n return randomstring;\n}\n/**\n * @function getLockId\n * @returns {string}\n * @description Generates an id which will be unique for the browser tab\n */\nfunction getLockId() {\n return Date.now().toString() + generateRandomString(15);\n}\nvar SuperTokensLock = /** @class */ (function () {\n function SuperTokensLock(storageHandler) {\n this.acquiredIatSet = new Set();\n this.storageHandler = undefined;\n this.id = getLockId();\n this.acquireLock = this.acquireLock.bind(this);\n this.releaseLock = this.releaseLock.bind(this);\n this.releaseLock__private__ = this.releaseLock__private__.bind(this);\n this.waitForSomethingToChange = this.waitForSomethingToChange.bind(this);\n this.refreshLockWhileAcquired = this.refreshLockWhileAcquired.bind(this);\n this.storageHandler = storageHandler;\n if (SuperTokensLock.waiters === undefined) {\n SuperTokensLock.waiters = [];\n }\n }\n /**\n * @async\n * @memberOf Lock\n * @function acquireLock\n * @param {string} lockKey - Key for which the lock is being acquired\n * @param {number} [timeout=5000] - Maximum time for which the function will wait to acquire the lock\n * @returns {Promise<boolean>}\n * @description Will return true if lock is being acquired, else false.\n * Also the lock can be acquired for maximum 10 secs\n */\n SuperTokensLock.prototype.acquireLock = function (lockKey, timeout) {\n if (timeout === void 0) { timeout = 5000; }\n return __awaiter(this, void 0, void 0, function () {\n var iat, MAX_TIME, STORAGE_KEY, STORAGE, lockObj, TIMEOUT_KEY, lockObjPostDelay, parsedLockObjPostDelay;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n iat = Date.now() + generateRandomString(4);\n MAX_TIME = Date.now() + timeout;\n STORAGE_KEY = LOCK_STORAGE_KEY + \"-\" + lockKey;\n STORAGE = this.storageHandler === undefined ? DEFAULT_STORAGE_HANDLER : this.storageHandler;\n _a.label = 1;\n case 1:\n if (!(Date.now() < MAX_TIME)) return [3 /*break*/, 8];\n return [4 /*yield*/, delay(30)];\n case 2:\n _a.sent();\n lockObj = STORAGE.getItemSync(STORAGE_KEY);\n if (!(lockObj === null)) return [3 /*break*/, 5];\n TIMEOUT_KEY = this.id + \"-\" + lockKey + \"-\" + iat;\n // there is a problem if setItem happens at the exact same time for 2 different processes.. so we add some random delay here.\n return [4 /*yield*/, delay(Math.floor(Math.random() * 25))];\n case 3:\n // there is a problem if setItem happens at the exact same time for 2 different processes.. so we add some random delay here.\n _a.sent();\n STORAGE.setItemSync(STORAGE_KEY, JSON.stringify({\n id: this.id,\n iat: iat,\n timeoutKey: TIMEOUT_KEY,\n timeAcquired: Date.now(),\n timeRefreshed: Date.now()\n }));\n return [4 /*yield*/, delay(30)];\n case 4:\n _a.sent(); // this is to prevent race conditions. This time must be more than the time it takes for storage.setItem\n lockObjPostDelay = STORAGE.getItemSync(STORAGE_KEY);\n if (lockObjPostDelay !== null) {\n parsedLockObjPostDelay = JSON.parse(lockObjPostDelay);\n if (parsedLockObjPostDelay.id === this.id && parsedLockObjPostDelay.iat === iat) {\n this.acquiredIatSet.add(iat);\n this.refreshLockWhileAcquired(STORAGE_KEY, iat);\n return [2 /*return*/, true];\n }\n }\n return [3 /*break*/, 7];\n case 5:\n SuperTokensLock.lockCorrector(this.storageHandler === undefined ? DEFAULT_STORAGE_HANDLER : this.storageHandler);\n return [4 /*yield*/, this.waitForSomethingToChange(MAX_TIME)];\n case 6:\n _a.sent();\n _a.label = 7;\n case 7:\n iat = Date.now() + generateRandomString(4);\n return [3 /*break*/, 1];\n case 8: return [2 /*return*/, false];\n }\n });\n });\n };\n SuperTokensLock.prototype.refreshLockWhileAcquired = function (storageKey, iat) {\n return __awaiter(this, void 0, void 0, function () {\n var _this = this;\n return __generator(this, function (_a) {\n setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {\n var STORAGE, lockObj, parsedLockObj;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, processLock_1.default().lock(iat)];\n case 1:\n _a.sent();\n if (!this.acquiredIatSet.has(iat)) {\n processLock_1.default().unlock(iat);\n return [2 /*return*/];\n }\n STORAGE = this.storageHandler === undefined ? DEFAULT_STORAGE_HANDLER : this.storageHandler;\n lockObj = STORAGE.getItemSync(storageKey);\n if (lockObj !== null) {\n parsedLockObj = JSON.parse(lockObj);\n parsedLockObj.timeRefreshed = Date.now();\n STORAGE.setItemSync(storageKey, JSON.stringify(parsedLockObj));\n processLock_1.default().unlock(iat);\n }\n else {\n processLock_1.default().unlock(iat);\n return [2 /*return*/];\n }\n this.refreshLockWhileAcquired(storageKey, iat);\n return [2 /*return*/];\n }\n });\n }); }, 1000);\n return [2 /*return*/];\n });\n });\n };\n SuperTokensLock.prototype.waitForSomethingToChange = function (MAX_TIME) {\n return __awaiter(this, void 0, void 0, function () {\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, new Promise(function (resolve) {\n var resolvedCalled = false;\n var startedAt = Date.now();\n var MIN_TIME_TO_WAIT = 50; // ms\n var removedListeners = false;\n function stopWaiting() {\n if (!removedListeners) {\n window.removeEventListener('storage', stopWaiting);\n SuperTokensLock.removeFromWaiting(stopWaiting);\n clearTimeout(timeOutId);\n removedListeners = true;\n }\n if (!resolvedCalled) {\n resolvedCalled = true;\n var timeToWait = MIN_TIME_TO_WAIT - (Date.now() - startedAt);\n if (timeToWait > 0) {\n setTimeout(resolve, timeToWait);\n }\n else {\n resolve(null);\n }\n }\n }\n window.addEventListener('storage', stopWaiting);\n SuperTokensLock.addToWaiting(stopWaiting);\n var timeOutId = setTimeout(stopWaiting, Math.max(0, MAX_TIME - Date.now()));\n })];\n case 1:\n _a.sent();\n return [2 /*return*/];\n }\n });\n });\n };\n SuperTokensLock.addToWaiting = function (func) {\n this.removeFromWaiting(func);\n if (SuperTokensLock.waiters === undefined) {\n return;\n }\n SuperTokensLock.waiters.push(func);\n };\n SuperTokensLock.removeFromWaiting = function (func) {\n if (SuperTokensLock.waiters === undefined) {\n return;\n }\n SuperTokensLock.waiters = SuperTokensLock.waiters.filter(function (i) { return i !== func; });\n };\n SuperTokensLock.notifyWaiters = function () {\n if (SuperTokensLock.waiters === undefined) {\n return;\n }\n var waiters = SuperTokensLock.waiters.slice(); // so that if Lock.waiters is changed it's ok.\n waiters.forEach(function (i) { return i(); });\n };\n /**\n * @function releaseLock\n * @memberOf Lock\n * @param {string} lockKey - Key for which lock is being released\n * @returns {void}\n * @description Release a lock.\n */\n SuperTokensLock.prototype.releaseLock = function (lockKey) {\n return __awaiter(this, void 0, void 0, function () {\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, this.releaseLock__private__(lockKey)];\n case 1: return [2 /*return*/, _a.sent()];\n }\n });\n });\n };\n /**\n * @function releaseLock\n * @memberOf Lock\n * @param {string} lockKey - Key for which lock is being released\n * @returns {void}\n * @description Release a lock.\n */\n SuperTokensLock.prototype.releaseLock__private__ = function (lockKey) {\n return __awaiter(this, void 0, void 0, function () {\n var STORAGE, STORAGE_KEY, lockObj, parsedlockObj;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n STORAGE = this.storageHandler === undefined ? DEFAULT_STORAGE_HANDLER : this.storageHandler;\n STORAGE_KEY = LOCK_STORAGE_KEY + \"-\" + lockKey;\n lockObj = STORAGE.getItemSync(STORAGE_KEY);\n if (lockObj === null) {\n return [2 /*return*/];\n }\n parsedlockObj = JSON.parse(lockObj);\n if (!(parsedlockObj.id === this.id)) return [3 /*break*/, 2];\n return [4 /*yield*/, processLock_1.default().lock(parsedlockObj.iat)];\n case 1:\n _a.sent();\n this.acquiredIatSet.delete(parsedlockObj.iat);\n STORAGE.removeItemSync(STORAGE_KEY);\n processLock_1.default().unlock(parsedlockObj.iat);\n SuperTokensLock.notifyWaiters();\n _a.label = 2;\n case 2: return [2 /*return*/];\n }\n });\n });\n };\n /**\n * @function lockCorrector\n * @returns {void}\n * @description If a lock is acquired by a tab and the tab is closed before the lock is\n * released, this function will release those locks\n */\n SuperTokensLock.lockCorrector = function (storageHandler) {\n var MIN_ALLOWED_TIME = Date.now() - 5000;\n var STORAGE = storageHandler;\n var KEYS = [];\n var currIndex = 0;\n while (true) {\n var key = STORAGE.keySync(currIndex);\n if (key === null) {\n break;\n }\n KEYS.push(key);\n currIndex++;\n }\n var notifyWaiters = false;\n for (var i = 0; i < KEYS.length; i++) {\n var LOCK_KEY = KEYS[i];\n if (LOCK_KEY.includes(LOCK_STORAGE_KEY)) {\n var lockObj = STORAGE.getItemSync(LOCK_KEY);\n if (lockObj !== null) {\n var parsedlockObj = JSON.parse(lockObj);\n if ((parsedlockObj.timeRefreshed === undefined && parsedlockObj.timeAcquired < MIN_ALLOWED_TIME) ||\n (parsedlockObj.timeRefreshed !== undefined && parsedlockObj.timeRefreshed < MIN_ALLOWED_TIME)) {\n STORAGE.removeItemSync(LOCK_KEY);\n notifyWaiters = true;\n }\n }\n }\n }\n if (notifyWaiters) {\n SuperTokensLock.notifyWaiters();\n }\n };\n SuperTokensLock.waiters = undefined;\n return SuperTokensLock;\n}());\nexports.default = SuperTokensLock;\n","import BrowserTabsLock from 'browser-tabs-lock';\nimport { TimeoutError } from './errors';\n\n/**\n * Lock manager abstraction for cross-tab synchronization.\n * Supports both modern Web Locks API and legacy localStorage-based locking.\n */\n\n/** Lock manager interface - callback pattern ensures automatic lock release */\nexport interface ILockManager {\n /**\n * Run callback while holding a lock.\n * Lock is automatically released when callback completes or throws.\n *\n * @param key - Lock identifier\n * @param timeout - Maximum time to wait for lock acquisition (ms)\n * @param callback - Function to execute while holding the lock\n * @returns Promise resolving to callback's return value\n * @throws Error if lock cannot be acquired within timeout\n */\n runWithLock<T>(\n key: string,\n timeout: number,\n callback: () => Promise<T>\n ): Promise<T>;\n}\n\n/** Web Locks API implementation - true mutex with OS-level queuing */\nexport class WebLocksApiManager implements ILockManager {\n async runWithLock<T>(\n key: string,\n timeout: number,\n callback: () => Promise<T>\n ): Promise<T> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n try {\n return await navigator.locks.request(\n key,\n { mode: 'exclusive', signal: controller.signal },\n async lock => {\n clearTimeout(timeoutId);\n if (!lock) throw new Error('Lock not available');\n return await callback();\n }\n );\n } catch (error: any) {\n clearTimeout(timeoutId);\n if (error?.name === 'AbortError') throw new TimeoutError();\n throw error;\n }\n }\n}\n\n/** Legacy localStorage-based locking with retry logic for older browsers */\nexport class LegacyLockManager implements ILockManager {\n private lock: BrowserTabsLock;\n private activeLocks: Set<string> = new Set();\n private pagehideHandler: () => void;\n\n constructor() {\n this.lock = new BrowserTabsLock();\n\n this.pagehideHandler = () => {\n this.activeLocks.forEach(key => this.lock.releaseLock(key));\n this.activeLocks.clear();\n };\n }\n\n async runWithLock<T>(\n key: string,\n timeout: number,\n callback: () => Promise<T>\n ): Promise<T> {\n // Retry logic to handle race conditions in localStorage-based locking\n const retryAttempts = 10;\n let acquired = false;\n\n for (let i = 0; i < retryAttempts && !acquired; i++) {\n acquired = await this.lock.acquireLock(key, timeout);\n }\n\n if (!acquired) {\n throw new TimeoutError();\n }\n\n this.activeLocks.add(key);\n\n // Add pagehide listener when acquiring first lock\n if (this.activeLocks.size === 1 && typeof window !== 'undefined') {\n window.addEventListener('pagehide', this.pagehideHandler);\n }\n\n try {\n return await callback();\n } finally {\n this.activeLocks.delete(key);\n await this.lock.releaseLock(key);\n\n // Remove pagehide listener when all locks are released\n if (this.activeLocks.size === 0 && typeof window !== 'undefined') {\n window.removeEventListener('pagehide', this.pagehideHandler);\n }\n }\n }\n}\n\n/**\n * Feature detection for Web Locks API support\n */\nfunction isWebLocksSupported(): boolean {\n return (\n typeof navigator !== 'undefined' &&\n typeof navigator.locks?.request === 'function'\n );\n}\n\nfunction createLockManager(): ILockManager {\n return isWebLocksSupported()\n ? new WebLocksApiManager()\n : new LegacyLockManager();\n}\n\n/**\n * Get the singleton lock manager instance.\n * Uses Web Locks API in modern browsers, falls back to localStorage in older browsers.\n */\nlet lockManager: ILockManager | null = null;\n\nexport function getLockManager(): ILockManager {\n if (!lockManager) {\n lockManager = createLockManager();\n }\n return lockManager;\n}\n\n// For testing: allow resetting the singleton\nexport function resetLockManager(): void {\n lockManager = null;\n}\n",null,"import * as dpopLib from 'dpop';\n\nexport const DPOP_NONCE_HEADER = 'dpop-nonce';\n\nconst KEY_PAIR_ALGORITHM: dpopLib.JWSAlgorithm = 'ES256';\n\nconst SUPPORTED_GRANT_TYPES = [\n 'authorization_code',\n 'refresh_token',\n 'urn:ietf:params:oauth:grant-type:token-exchange',\n 'http://auth0.com/oauth/grant-type/mfa-oob',\n 'http://auth0.com/oauth/grant-type/mfa-otp',\n 'http://auth0.com/oauth/grant-type/mfa-recovery-code'\n];\n\nexport type KeyPair = Readonly<dpopLib.KeyPair>;\n\ntype GenerateProofParams = {\n keyPair: KeyPair;\n url: string;\n method: string;\n nonce?: string;\n accessToken?: string;\n};\n\nexport function generateKeyPair(): Promise<KeyPair> {\n return dpopLib.generateKeyPair(KEY_PAIR_ALGORITHM, { extractable: false });\n}\n\nexport function calculateThumbprint(\n keyPair: Pick<KeyPair, 'publicKey'>\n): Promise<string> {\n return dpopLib.calculateThumbprint(keyPair.publicKey);\n}\n\nfunction normalizeUrl(url: string): string {\n const parsedUrl = new URL(url);\n\n /**\n * \"The HTTP target URI (...) without query and fragment parts\"\n * @see {@link https://www.rfc-editor.org/rfc/rfc9449.html#section-4.2-4.6}\n */\n parsedUrl.search = '';\n parsedUrl.hash = '';\n\n return parsedUrl.href;\n}\n\nexport function generateProof({\n keyPair,\n url,\n method,\n nonce,\n accessToken\n}: GenerateProofParams): Promise<string> {\n const normalizedUrl = normalizeUrl(url);\n\n return dpopLib.generateProof(\n keyPair,\n normalizedUrl,\n method,\n nonce,\n accessToken\n );\n}\n\nexport function isGrantTypeSupported(grantType: string): boolean {\n return SUPPORTED_GRANT_TYPES.includes(grantType);\n}\n","import { WorkerRefreshTokenMessage } from './worker.types';\n\n/**\n * Sends the specified message to the web worker\n * @param message The message to send\n * @param to The worker to send the message to\n */\nexport const sendMessage = (message: WorkerRefreshTokenMessage, to: Worker) =>\n new Promise(function (resolve, reject) {\n const messageChannel = new MessageChannel();\n\n messageChannel.port1.onmessage = function (event) {\n // Only for fetch errors, as these get retried\n if (event.data.error) {\n reject(new Error(event.data.error));\n } else {\n resolve(event.data);\n }\n messageChannel.port1.close();\n };\n\n to.postMessage(message, [messageChannel.port2]);\n });\n","import {\n DEFAULT_FETCH_TIMEOUT_MS,\n DEFAULT_SILENT_TOKEN_RETRY_COUNT\n} from './constants';\n\nimport { fromEntries } from './utils';\nimport { sendMessage } from './worker/worker.utils';\nimport { FetchOptions, FetchResponse } from './global';\nimport {\n GenericError,\n MfaRequiredError,\n MissingRefreshTokenError,\n UseDpopNonceError\n} from './errors';\nimport { Dpop } from './dpop/dpop';\nimport { DPOP_NONCE_HEADER } from './dpop/utils';\n\nexport const createAbortController = () => new AbortController();\n\nconst dofetch = async (fetchUrl: string, fetchOptions: FetchOptions) => {\n const response = await fetch(fetchUrl, fetchOptions);\n\n return {\n ok: response.ok,\n json: await response.json(),\n\n /**\n * This is not needed, but do it anyway so the object shape is the\n * same as when using a Web Worker (which *does* need this, see\n * src/worker/token.worker.ts).\n */\n headers: fromEntries(response.headers)\n };\n};\n\nconst fetchWithoutWorker = async (\n fetchUrl: string,\n fetchOptions: FetchOptions,\n timeout: number\n) => {\n const controller = createAbortController();\n fetchOptions.signal = controller.signal;\n\n let timeoutId: NodeJS.Timeout;\n\n // The promise will resolve with one of these two promises (the fetch or the timeout), whichever completes first.\n return Promise.race([\n dofetch(fetchUrl, fetchOptions),\n\n new Promise((_, reject) => {\n timeoutId = setTimeout(() => {\n controller.abort();\n reject(new Error(\"Timeout when executing 'fetch'\"));\n }, timeout);\n })\n ]).finally(() => {\n clearTimeout(timeoutId);\n });\n};\n\nconst fetchWithWorker = async (\n fetchUrl: string,\n audience: string,\n scope: string,\n fetchOptions: FetchOptions,\n timeout: number,\n worker: Worker,\n useFormData?: boolean,\n useMrrt?: boolean\n) => {\n return sendMessage(\n {\n auth: {\n audience,\n scope\n },\n timeout,\n fetchUrl,\n fetchOptions,\n useFormData,\n useMrrt\n },\n worker\n );\n};\n\nexport const switchFetch = async (\n fetchUrl: string,\n audience: string,\n scope: string,\n fetchOptions: FetchOptions,\n worker?: Worker,\n useFormData?: boolean,\n timeout = DEFAULT_FETCH_TIMEOUT_MS,\n useMrrt?: boolean,\n): Promise<any> => {\n if (worker) {\n return fetchWithWorker(\n fetchUrl,\n audience,\n scope,\n fetchOptions,\n timeout,\n worker,\n useFormData,\n useMrrt\n );\n } else {\n return fetchWithoutWorker(fetchUrl, fetchOptions, timeout);\n }\n};\n\nexport async function getJSON<T>(\n url: string,\n timeout: number | undefined,\n audience: string,\n scope: string,\n options: FetchOptions,\n worker?: Worker,\n useFormData?: boolean,\n useMrrt?: boolean,\n dpop?: Pick<Dpop, 'generateProof' | 'getNonce' | 'setNonce'>,\n isDpopRetry?: boolean\n): Promise<T> {\n if (dpop) {\n const dpopProof = await dpop.generateProof({\n url,\n method: options.method || 'GET',\n nonce: await dpop.getNonce()\n });\n\n options.headers = { ...options.headers, dpop: dpopProof };\n }\n\n let fetchError: null | Error = null;\n let response!: FetchResponse;\n\n for (let i = 0; i < DEFAULT_SILENT_TOKEN_RETRY_COUNT; i++) {\n try {\n response = await switchFetch(\n url,\n audience,\n scope,\n options,\n worker,\n useFormData,\n timeout,\n useMrrt,\n );\n fetchError = null;\n break;\n } catch (e) {\n // Fetch only fails in the case of a network issue, so should be\n // retried here. Failure status (4xx, 5xx, etc) return a resolved Promise\n // with the failure in the body.\n // https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API\n fetchError = e;\n }\n }\n\n if (fetchError) {\n throw fetchError;\n }\n\n const {\n json: { error, error_description, ...data },\n headers,\n ok\n } = response;\n\n let newDpopNonce: string | undefined;\n\n if (dpop) {\n /**\n * Note that a new DPoP nonce can appear in both error and success responses!\n *\n * @see {@link https://www.rfc-editor.org/rfc/rfc9449.html#section-8.2-3}\n */\n newDpopNonce = headers[DPOP_NONCE_HEADER];\n\n if (newDpopNonce) {\n await dpop.setNonce(newDpopNonce);\n }\n }\n\n if (!ok) {\n const errorMessage =\n error_description || `HTTP error. Unable to fetch ${url}`;\n\n if (error === 'mfa_required') {\n throw new MfaRequiredError(error, errorMessage, data.mfa_token, data.mfa_requirements);\n }\n\n if (error === 'missing_refresh_token') {\n throw new MissingRefreshTokenError(audience, scope);\n }\n\n /**\n * When DPoP is used and we get a `use_dpop_nonce` error from the server,\n * we must retry ONCE with any new nonce received in the rejected request.\n *\n * If a new nonce was not received or the retry fails again, we give up and\n * throw the error as is.\n */\n if (error === 'use_dpop_nonce') {\n if (!dpop || !newDpopNonce || isDpopRetry) {\n throw new UseDpopNonceError(newDpopNonce);\n }\n\n // repeat the call but with isDpopRetry=true to avoid any more retries\n return getJSON(\n url,\n timeout,\n audience,\n scope,\n options,\n worker,\n useFormData,\n useMrrt,\n dpop,\n true // !\n );\n }\n\n throw new GenericError(error || 'request_error', errorMessage);\n }\n\n return data;\n}\n","import { TokenEndpointOptions, TokenEndpointResponse } from './global';\nimport { DEFAULT_AUTH0_CLIENT, DEFAULT_AUDIENCE } from './constants';\nimport * as dpopUtils from './dpop/utils';\nimport { getJSON } from './http';\nimport { createQueryParams, stripAuth0Client } from './utils';\n\nexport async function oauthToken(\n {\n baseUrl,\n timeout,\n audience,\n scope,\n auth0Client,\n useFormData,\n useMrrt,\n dpop,\n ...options\n }: TokenEndpointOptions,\n worker?: Worker\n) {\n const isTokenExchange =\n options.grant_type === 'urn:ietf:params:oauth:grant-type:token-exchange';\n\n const refreshWithMrrt = options.grant_type === 'refresh_token' && useMrrt;\n\n const allParams = {\n ...options,\n ...(isTokenExchange && audience && { audience }),\n ...(isTokenExchange && scope && { scope }),\n ...(refreshWithMrrt && { audience, scope })\n };\n\n const body = useFormData\n ? createQueryParams(allParams)\n : JSON.stringify(allParams);\n\n const isDpopSupported = dpopUtils.isGrantTypeSupported(options.grant_type);\n\n return await getJSON<TokenEndpointResponse>(\n `${baseUrl}/oauth/token`,\n timeout,\n audience || DEFAULT_AUDIENCE,\n scope,\n {\n method: 'POST',\n body,\n headers: {\n 'Content-Type': useFormData\n ? 'application/x-www-form-urlencoded'\n : 'application/json',\n 'Auth0-Client': btoa(\n JSON.stringify(stripAuth0Client(auth0Client || DEFAULT_AUTH0_CLIENT))\n )\n }\n },\n worker,\n useFormData,\n useMrrt,\n isDpopSupported ? dpop : undefined\n );\n}\n","import { DEFAULT_AUDIENCE } from \"./constants\";\n\n/**\n * @ignore\n */\nconst dedupe = (arr: string[]) => Array.from(new Set(arr));\n\n/**\n * @ignore\n */\n/**\n * Returns a string of unique scopes by removing duplicates and unnecessary whitespace.\n *\n * @param {...(string | undefined)[]} scopes - A list of scope strings or undefined values.\n * @returns {string} A string containing unique scopes separated by a single space.\n */\nexport const getUniqueScopes = (...scopes: (string | undefined)[]) => {\n return dedupe(scopes.filter(Boolean).join(' ').trim().split(/\\s+/)).join(' ');\n};\n\n/**\n * @ignore\n */\n/**\n * We will check if the developer has created the client with a string or object of audience:scopes. We will inject\n * the base scopes to each audience, and store the base ones inside default key. As well, if the developer created the Auth0Client\n * with a string of scopes, we will store the requested ones with the base scopes inside the default key as well.\n * @param authScopes The scopes requested by the user when creating the Auth0Client\n * @param openIdScope openId scope\n * @param extraScopes Other scopes to accumulate such as offline_access\n * @returns {Record<string, string>} An object with all scopes that are going to be accumulated.\n */\nexport const injectDefaultScopes = (authScopes: string | Record<string, string> | undefined, openIdScope: string, ...extraScopes: string[]): Record<string, string> => {\n if (typeof authScopes !== 'object') {\n return { [DEFAULT_AUDIENCE]: getUniqueScopes(openIdScope, authScopes, ...extraScopes) };\n }\n\n let requestedScopes: Record<string, string> = {\n [DEFAULT_AUDIENCE]: getUniqueScopes(openIdScope, ...extraScopes),\n };\n\n Object.keys(authScopes).forEach((key) => {\n const audienceScopes = authScopes[key];\n\n requestedScopes[key] = getUniqueScopes(openIdScope, audienceScopes, ...extraScopes);\n });\n\n return requestedScopes;\n}\n\n/**\n * @ignore\n */\n/**\n * Will return a string of scopes. If a specific audience was requested and it exist inside the scopes object, we will return those\n * related to that audience that we want to accumulate. If not, we will return the ones stored inside the default key.\n * @param authScopes Object of audience:scopes that are going to be accumulated\n * @param methodScopes The scopes requested for the developer in a specific request\n * @param audience The audience the developer requested for an specific request or the one they configured in the Auth0Client\n * @returns {string} A combination of Auth0Client scopes and the ones requested by the developer for a specific request\n */\nexport const scopesToRequest = (authScopes: Record<string, string>, methodScopes: string | undefined, audience: string | undefined): string => {\n let scope: string | undefined;\n\n if (audience) {\n scope = authScopes[audience];\n }\n\n if (!scope) {\n scope = authScopes[DEFAULT_AUDIENCE];\n }\n\n return getUniqueScopes(scope, methodScopes);\n}","import { IdToken, User } from '../global';\n\nexport const CACHE_KEY_PREFIX = '@@auth0spajs@@';\nexport const CACHE_KEY_ID_TOKEN_SUFFIX = '@@user@@';\n\nexport type CacheKeyData = {\n audience?: string;\n scope?: string;\n clientId: string;\n};\n\nexport class CacheKey {\n public clientId: string;\n public scope?: string;\n public audience?: string;\n\n constructor(\n data: CacheKeyData,\n public prefix: string = CACHE_KEY_PREFIX,\n public suffix?: string\n ) {\n this.clientId = data.clientId;\n this.scope = data.scope;\n this.audience = data.audience;\n }\n\n /**\n * Converts this `CacheKey` instance into a string for use in a cache\n * @returns A string representation of the key\n */\n toKey(): string {\n return [this.prefix, this.clientId, this.audience, this.scope, this.suffix]\n .filter(Boolean)\n .join('::');\n }\n\n /**\n * Converts a cache key string into a `CacheKey` instance.\n * @param key The key to convert\n * @returns An instance of `CacheKey`\n */\n static fromKey(key: string): CacheKey {\n const [prefix, clientId, audience, scope] = key.split('::');\n\n return new CacheKey({ clientId, scope, audience }, prefix);\n }\n\n /**\n * Utility function to build a `CacheKey` instance from a cache entry\n * @param entry The entry\n * @returns An instance of `CacheKey`\n */\n static fromCacheEntry(entry: CacheEntry): CacheKey {\n const { scope, audience, client_id: clientId } = entry;\n\n return new CacheKey({\n scope,\n audience,\n clientId\n });\n }\n}\n\nexport interface DecodedToken {\n claims: IdToken;\n user: User;\n}\n\nexport interface IdTokenEntry {\n id_token: string;\n decodedToken: DecodedToken;\n}\n\nexport type CacheEntry = {\n id_token?: string;\n token_type?: string;\n access_token: string;\n expires_in: number;\n decodedToken?: DecodedToken;\n audience: string;\n scope: string;\n client_id: string;\n refresh_token?: string;\n oauthTokenScope?: string;\n};\n\nexport type WrappedCacheEntry = {\n body: Partial<CacheEntry>;\n expiresAt: number;\n};\n\nexport type KeyManifestEntry = {\n keys: string[];\n};\n\nexport type Cacheable = WrappedCacheEntry | KeyManifestEntry;\n\nexport type MaybePromise<T> = Promise<T> | T;\n\nexport interface ICache {\n set<T = Cacheable>(key: string, entry: T): MaybePromise<void>;\n get<T = Cacheable>(key: string): MaybePromise<T | undefined>;\n remove(key: string): MaybePromise<void>;\n allKeys?(): MaybePromise<string[]>;\n}\n","import { ICache, Cacheable, CACHE_KEY_PREFIX, MaybePromise } from './shared';\n\nexport class LocalStorageCache implements ICache {\n public set<T = Cacheable>(key: string, entry: T) {\n localStorage.setItem(key, JSON.stringify(entry));\n }\n\n public get<T = Cacheable>(key: string): MaybePromise<T | undefined> {\n const json = window.localStorage.getItem(key);\n\n if (!json) return;\n\n try {\n const payload = JSON.parse(json) as T;\n return payload;\n /* c8 ignore next 3 */\n } catch (e) {\n return;\n }\n }\n\n public remove(key: string) {\n localStorage.removeItem(key);\n }\n\n public allKeys() {\n return Object.keys(window.localStorage).filter(key =>\n key.startsWith(CACHE_KEY_PREFIX)\n );\n }\n}\n","import { Cacheable, ICache, MaybePromise } from './shared';\n\nexport class InMemoryCache {\n public enclosedCache: ICache = (function () {\n let cache: Record<string, unknown> = {};\n\n return {\n set<T = Cacheable>(key: string, entry: T) {\n cache[key] = entry;\n },\n\n get<T = Cacheable>(key: string): MaybePromise<T | undefined> {\n const cacheEntry = cache[key] as T;\n\n if (!cacheEntry) {\n return;\n }\n\n return cacheEntry;\n },\n\n remove(key: string) {\n delete cache[key];\n },\n\n allKeys(): string[] {\n return Object.keys(cache);\n }\n };\n })();\n}\n","import { DEFAULT_NOW_PROVIDER } from '../constants';\nimport { CacheKeyManifest } from './key-manifest';\n\nimport {\n CacheEntry,\n ICache,\n CacheKey,\n CACHE_KEY_PREFIX,\n WrappedCacheEntry,\n DecodedToken,\n CACHE_KEY_ID_TOKEN_SUFFIX,\n IdTokenEntry\n} from './shared';\n\nconst DEFAULT_EXPIRY_ADJUSTMENT_SECONDS = 0;\n\nexport class CacheManager {\n private nowProvider: () => number | Promise<number>;\n\n constructor(\n private cache: ICache,\n private keyManifest?: CacheKeyManifest,\n nowProvider?: () => number | Promise<number>\n ) {\n this.nowProvider = nowProvider || DEFAULT_NOW_PROVIDER;\n }\n\n async setIdToken(\n clientId: string,\n idToken: string,\n decodedToken: DecodedToken\n ): Promise<void> {\n const cacheKey = this.getIdTokenCacheKey(clientId);\n await this.cache.set(cacheKey, {\n id_token: idToken,\n decodedToken\n });\n await this.keyManifest?.add(cacheKey);\n }\n\n async getIdToken(cacheKey: CacheKey): Promise<IdTokenEntry | undefined> {\n const entry = await this.cache.get<IdTokenEntry>(\n this.getIdTokenCacheKey(cacheKey.clientId)\n );\n\n if (!entry && cacheKey.scope && cacheKey.audience) {\n const entryByScope = await this.get(cacheKey);\n\n if (!entryByScope) {\n return;\n }\n\n if (!entryByScope.id_token || !entryByScope.decodedToken) {\n return;\n }\n\n return {\n id_token: entryByScope.id_token,\n decodedToken: entryByScope.decodedToken\n };\n }\n\n if (!entry) {\n return;\n }\n\n return { id_token: entry.id_token, decodedToken: entry.decodedToken };\n }\n\n async get(\n cacheKey: CacheKey,\n expiryAdjustmentSeconds = DEFAULT_EXPIRY_ADJUSTMENT_SECONDS,\n useMrrt = false,\n cacheMode?: string\n ): Promise<Partial<CacheEntry> | undefined> {\n let wrappedEntry = await this.cache.get<WrappedCacheEntry>(\n cacheKey.toKey()\n );\n\n if (!wrappedEntry) {\n const keys = await this.getCacheKeys();\n\n if (!keys) return;\n\n const matchedKey = this.matchExistingCacheKey(cacheKey, keys);\n\n if (matchedKey) {\n wrappedEntry = await this.cache.get<WrappedCacheEntry>(matchedKey);\n }\n\n // To refresh using MRRT we need to send a request to the server\n // If cacheMode is 'cache-only', this will make us unable to call the server\n // so it won't be needed to find a valid refresh token\n if (!wrappedEntry && useMrrt && cacheMode !== 'cache-only') {\n return this.getEntryWithRefreshToken(cacheKey, keys);\n }\n }\n\n // If we still don't have an entry, exit.\n if (!wrappedEntry) {\n return;\n }\n\n const now = await this.nowProvider();\n const nowSeconds = Math.floor(now / 1000);\n\n if (wrappedEntry.expiresAt - expiryAdjustmentSeconds < nowSeconds) {\n if (wrappedEntry.body.refresh_token) {\n return this.modifiedCachedEntry(wrappedEntry, cacheKey);\n }\n\n await this.cache.remove(cacheKey.toKey());\n await this.keyManifest?.remove(cacheKey.toKey());\n\n return;\n }\n\n return wrappedEntry.body;\n }\n\n private async modifiedCachedEntry(wrappedEntry: WrappedCacheEntry, cacheKey: CacheKey): Promise<Partial<CacheEntry>> {\n // We need to keep audience and scope in order to check them later when doing refresh\n // using MRRT. See getScopeToRequest method.\n wrappedEntry.body = {\n refresh_token: wrappedEntry.body.refresh_token,\n audience: wrappedEntry.body.audience,\n scope: wrappedEntry.body.scope,\n };\n\n await this.cache.set(cacheKey.toKey(), wrappedEntry);\n\n return {\n refresh_token: wrappedEntry.body.refresh_token,\n audience: wrappedEntry.body.audience,\n scope: wrappedEntry.body.scope,\n };\n }\n\n async set(entry: CacheEntry): Promise<void> {\n const cacheKey = new CacheKey({\n clientId: entry.client_id,\n scope: entry.scope,\n audience: entry.audience\n });\n\n const wrappedEntry = await this.wrapCacheEntry(entry);\n\n await this.cache.set(cacheKey.toKey(), wrappedEntry);\n await this.keyManifest?.add(cacheKey.toKey());\n }\n\n async remove(\n client_id: string,\n audience?: string,\n scope?: string,\n ): Promise<void> {\n const cacheKey = new CacheKey({\n clientId: client_id,\n scope: scope,\n audience: audience\n });\n\n await this.cache.remove(cacheKey.toKey());\n }\n\n async clear(clientId?: string): Promise<void> {\n const keys = await this.getCacheKeys();\n\n /* c8 ignore next */\n if (!keys) return;\n\n await keys\n .filter(key => (clientId ? key.includes(clientId) : true))\n .reduce(async (memo, key) => {\n await memo;\n await this.cache.remove(key);\n }, Promise.resolve());\n\n await this.keyManifest?.clear();\n }\n\n private async wrapCacheEntry(entry: CacheEntry): Promise<WrappedCacheEntry> {\n const now = await this.nowProvider();\n const expiresInTime = Math.floor(now / 1000) + entry.expires_in;\n\n return {\n body: entry,\n expiresAt: expiresInTime\n };\n }\n\n private async getCacheKeys(): Promise<string[] | undefined> {\n if (this.keyManifest) {\n return (await this.keyManifest.get())?.keys;\n } else if (this.cache.allKeys) {\n return this.cache.allKeys();\n }\n }\n\n /**\n * Returns the cache key to be used to store the id token\n * @param clientId The client id used to link to the id token\n * @returns The constructed cache key, as a string, to store the id token\n */\n private getIdTokenCacheKey(clientId: string) {\n return new CacheKey(\n { clientId },\n CACHE_KEY_PREFIX,\n CACHE_KEY_ID_TOKEN_SUFFIX\n ).toKey();\n }\n\n /**\n * Finds the corresponding key in the cache based on the provided cache key.\n * The keys inside the cache are in the format {prefix}::{clientId}::{audience}::{scope}.\n * The first key in the cache that satisfies the following conditions is returned\n * - `prefix` is strict equal to Auth0's internally configured `keyPrefix`\n * - `clientId` is strict equal to the `cacheKey.clientId`\n * - `audience` is strict equal to the `cacheKey.audience`\n * - `scope` contains at least all the `cacheKey.scope` values\n * *\n * @param keyToMatch The provided cache key\n * @param allKeys A list of existing cache keys\n */\n private matchExistingCacheKey(keyToMatch: CacheKey, allKeys: Array<string>) {\n return allKeys.filter(key => {\n const cacheKey = CacheKey.fromKey(key);\n const scopeSet = new Set(cacheKey.scope && cacheKey.scope.split(' '));\n const scopesToMatch = keyToMatch.scope?.split(' ') || [];\n\n const hasAllScopes =\n cacheKey.scope &&\n scopesToMatch.reduce(\n (acc, current) => acc && scopeSet.has(current),\n true\n );\n\n return (\n cacheKey.prefix === CACHE_KEY_PREFIX &&\n cacheKey.clientId === keyToMatch.clientId &&\n cacheKey.audience === keyToMatch.audience &&\n hasAllScopes\n );\n })[0];\n }\n\n /**\n * Returns the first entry that contains a refresh_token that satisfies the following conditions\n * The keys inside the cache are in the format {prefix}::{clientId}::{audience}::{scope}.\n * - `prefix` is strict equal to Auth0's internally configured `keyPrefix`\n * - `clientId` is strict equal to the `cacheKey.clientId`\n * @param keyToMatch The provided cache key\n * @param allKeys A list of existing cache keys\n */\n private async getEntryWithRefreshToken(keyToMatch: CacheKey, allKeys: Array<string>): Promise<Partial<CacheEntry> | undefined> {\n for (const key of allKeys) {\n const cacheKey = CacheKey.fromKey(key);\n\n if (cacheKey.prefix === CACHE_KEY_PREFIX &&\n cacheKey.clientId === keyToMatch.clientId) {\n const cachedEntry = await this.cache.get<WrappedCacheEntry>(key);\n\n if (cachedEntry?.body?.refresh_token) {\n return this.modifiedCachedEntry(cachedEntry, keyToMatch);\n }\n }\n }\n\n return undefined;\n }\n\n /**\n * Updates the refresh token in all cache entries that contain the old refresh token.\n *\n * When a refresh token is rotated, multiple cache entries (for different audiences/scopes)\n * may share the same refresh token. This method propagates the new refresh token to all\n * matching entries.\n *\n * @param oldRefreshToken The refresh token that was used and is now invalid\n * @param newRefreshToken The new refresh token received from the server\n */\n async updateEntry(\n oldRefreshToken: string,\n newRefreshToken: string,\n ): Promise<void> {\n const allKeys = await this.getCacheKeys();\n\n if (!allKeys) return;\n\n for (const key of allKeys) {\n const entry = await this.cache.get<WrappedCacheEntry>(key);\n\n if (entry?.body?.refresh_token === oldRefreshToken) {\n entry.body.refresh_token = newRefreshToken;\n await this.cache.set(key, entry);\n }\n }\n }\n}\n","import { ClientStorage } from './storage';\n\nconst TRANSACTION_STORAGE_KEY_PREFIX = 'a0.spajs.txs';\n\nexport interface LoginTransaction {\n nonce: string;\n scope: string;\n audience: string;\n appState?: any;\n code_verifier: string;\n redirect_uri?: string;\n organization?: string;\n state?: string;\n response_type: 'code';\n}\n\nexport interface ConnectAccountTransaction {\n appState?: any;\n audience?: string;\n auth_session: string;\n code_verifier: string;\n redirect_uri: string;\n scope?: string;\n state: string;\n connection: string;\n response_type: 'connect_code';\n}\n\nexport class TransactionManager {\n private storageKey: string;\n\n constructor(\n private storage: ClientStorage,\n private clientId: string,\n private cookieDomain?: string\n ) {\n this.storageKey = `${TRANSACTION_STORAGE_KEY_PREFIX}.${this.clientId}`;\n }\n\n public create<T extends Object = LoginTransaction>(transaction: T) {\n this.storage.save(this.storageKey, transaction, {\n daysUntilExpire: 1,\n cookieDomain: this.cookieDomain\n });\n }\n\n public get<T extends Object = LoginTransaction>(): T | undefined {\n return this.storage.get(this.storageKey);\n }\n\n public remove() {\n this.storage.remove(this.storageKey, {\n cookieDomain: this.cookieDomain\n });\n }\n}","import { urlDecodeB64 } from './utils';\nimport { IdToken, JWTVerifyOptions } from './global';\n\nconst isNumber = (n: any) => typeof n === 'number';\n\nconst idTokendecoded = [\n 'iss',\n 'aud',\n 'exp',\n 'nbf',\n 'iat',\n 'jti',\n 'azp',\n 'nonce',\n 'auth_time',\n 'at_hash',\n 'c_hash',\n 'acr',\n 'amr',\n 'sub_jwk',\n 'cnf',\n 'sip_from_tag',\n 'sip_date',\n 'sip_callid',\n 'sip_cseq_num',\n 'sip_via_branch',\n 'orig',\n 'dest',\n 'mky',\n 'events',\n 'toe',\n 'txn',\n 'rph',\n 'sid',\n 'vot',\n 'vtm'\n];\n\nexport const decode = (token: string) => {\n const parts = token.split('.');\n const [header, payload, signature] = parts;\n\n if (parts.length !== 3 || !header || !payload || !signature) {\n throw new Error('ID token could not be decoded');\n }\n const payloadJSON = JSON.parse(urlDecodeB64(payload));\n const claims: IdToken = { __raw: token };\n const user: any = {};\n Object.keys(payloadJSON).forEach(k => {\n claims[k] = payloadJSON[k];\n if (!idTokendecoded.includes(k)) {\n user[k] = payloadJSON[k];\n }\n });\n return {\n encoded: { header, payload, signature },\n header: JSON.parse(urlDecodeB64(header)),\n claims,\n user\n };\n};\n\nexport const verify = (options: JWTVerifyOptions) => {\n if (!options.id_token) {\n throw new Error('ID token is required but missing');\n }\n\n const decoded = decode(options.id_token);\n\n if (!decoded.claims.iss) {\n throw new Error(\n 'Issuer (iss) claim must be a string present in the ID token'\n );\n }\n\n if (decoded.claims.iss !== options.iss) {\n throw new Error(\n `Issuer (iss) claim mismatch in the ID token; expected \"${options.iss}\", found \"${decoded.claims.iss}\"`\n );\n }\n\n if (!decoded.user.sub) {\n throw new Error(\n 'Subject (sub) claim must be a string present in the ID token'\n );\n }\n\n if (decoded.header.alg !== 'RS256') {\n throw new Error(\n `Signature algorithm of \"${decoded.header.alg}\" is not supported. Expected the ID token to be signed with \"RS256\".`\n );\n }\n\n if (\n !decoded.claims.aud ||\n !(\n typeof decoded.claims.aud === 'string' ||\n Array.isArray(decoded.claims.aud)\n )\n ) {\n throw new Error(\n 'Audience (aud) claim must be a string or array of strings present in the ID token'\n );\n }\n if (Array.isArray(decoded.claims.aud)) {\n if (!decoded.claims.aud.includes(options.aud)) {\n throw new Error(\n `Audience (aud) claim mismatch in the ID token; expected \"${\n options.aud\n }\" but was not one of \"${decoded.claims.aud.join(', ')}\"`\n );\n }\n if (decoded.claims.aud.length > 1) {\n if (!decoded.claims.azp) {\n throw new Error(\n 'Authorized Party (azp) claim must be a string present in the ID token when Audience (aud) claim has multiple values'\n );\n }\n if (decoded.claims.azp !== options.aud) {\n throw new Error(\n `Authorized Party (azp) claim mismatch in the ID token; expected \"${options.aud}\", found \"${decoded.claims.azp}\"`\n );\n }\n }\n } else if (decoded.claims.aud !== options.aud) {\n throw new Error(\n `Audience (aud) claim mismatch in the ID token; expected \"${options.aud}\" but found \"${decoded.claims.aud}\"`\n );\n }\n if (options.nonce) {\n if (!decoded.claims.nonce) {\n throw new Error(\n 'Nonce (nonce) claim must be a string present in the ID token'\n );\n }\n if (decoded.claims.nonce !== options.nonce) {\n throw new Error(\n `Nonce (nonce) claim mismatch in the ID token; expected \"${options.nonce}\", found \"${decoded.claims.nonce}\"`\n );\n }\n }\n\n if (options.max_age && !isNumber(decoded.claims.auth_time)) {\n throw new Error(\n 'Authentication Time (auth_time) claim must be a number present in the ID token when Max Age (max_age) is specified'\n );\n }\n\n /* c8 ignore next 5 */\n if (decoded.claims.exp == null || !isNumber(decoded.claims.exp)) {\n throw new Error(\n 'Expiration Time (exp) claim must be a number present in the ID token'\n );\n }\n if (!isNumber(decoded.claims.iat)) {\n throw new Error(\n 'Issued At (iat) claim must be a number present in the ID token'\n );\n }\n\n const leeway = options.leeway || 60;\n const now = new Date(options.now || Date.now());\n const expDate = new Date(0);\n\n expDate.setUTCSeconds(decoded.claims.exp + leeway);\n\n if (now > expDate) {\n throw new Error(\n `Expiration Time (exp) claim error in the ID token; current time (${now}) is after expiration time (${expDate})`\n );\n }\n\n if (decoded.claims.nbf != null && isNumber(decoded.claims.nbf)) {\n const nbfDate = new Date(0);\n nbfDate.setUTCSeconds(decoded.claims.nbf - leeway);\n if (now < nbfDate) {\n throw new Error(\n `Not Before time (nbf) claim in the ID token indicates that this token can't be used just yet. Current time (${now}) is before ${nbfDate}`\n );\n }\n }\n\n if (decoded.claims.auth_time != null && isNumber(decoded.claims.auth_time)) {\n const authTimeDate = new Date(0);\n authTimeDate.setUTCSeconds(\n parseInt(decoded.claims.auth_time) + (options.max_age as number) + leeway\n );\n\n if (now > authTimeDate) {\n throw new Error(\n `Authentication Time (auth_time) claim in the ID token indicates that too much time has passed since the last end-user authentication. Current time (${now}) is after last auth at ${authTimeDate}`\n );\n }\n }\n\n if (options.organization) {\n const org = options.organization.trim();\n if (org.startsWith('org_')) {\n const orgId = org;\n if (!decoded.claims.org_id) {\n throw new Error(\n 'Organization ID (org_id) claim must be a string present in the ID token'\n );\n } else if (orgId !== decoded.claims.org_id) {\n throw new Error(\n `Organization ID (org_id) claim mismatch in the ID token; expected \"${orgId}\", found \"${decoded.claims.org_id}\"`\n );\n }\n } else {\n const orgName = org.toLowerCase();\n // TODO should we verify if there is an `org_id` claim?\n if (!decoded.claims.org_name) {\n throw new Error(\n 'Organization Name (org_name) claim must be a string present in the ID token'\n );\n } else if (orgName !== decoded.claims.org_name) {\n throw new Error(\n `Organization Name (org_name) claim mismatch in the ID token; expected \"${orgName}\", found \"${decoded.claims.org_name}\"`\n );\n }\n }\n }\n\n return decoded;\n};\n","\"use strict\";\r\nvar __assign = (this && this.__assign) || function () {\r\n __assign = Object.assign || function(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\r\n t[p] = s[p];\r\n }\r\n return t;\r\n };\r\n return __assign.apply(this, arguments);\r\n};\r\nexports.__esModule = true;\r\nfunction stringifyAttribute(name, value) {\r\n if (!value) {\r\n return '';\r\n }\r\n var stringified = '; ' + name;\r\n if (value === true) {\r\n return stringified; // boolean attributes shouldn't have a value\r\n }\r\n return stringified + '=' + value;\r\n}\r\nfunction stringifyAttributes(attributes) {\r\n if (typeof attributes.expires === 'number') {\r\n var expires = new Date();\r\n expires.setMilliseconds(expires.getMilliseconds() + attributes.expires * 864e+5);\r\n attributes.expires = expires;\r\n }\r\n return stringifyAttribute('Expires', attributes.expires ? attributes.expires.toUTCString() : '')\r\n + stringifyAttribute('Domain', attributes.domain)\r\n + stringifyAttribute('Path', attributes.path)\r\n + stringifyAttribute('Secure', attributes.secure)\r\n + stringifyAttribute('SameSite', attributes.sameSite);\r\n}\r\nfunction encode(name, value, attributes) {\r\n return encodeURIComponent(name)\r\n .replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent) // allowed special characters\r\n .replace(/\\(/g, '%28').replace(/\\)/g, '%29') // replace opening and closing parens\r\n + '=' + encodeURIComponent(value)\r\n // allowed special characters\r\n .replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent)\r\n + stringifyAttributes(attributes);\r\n}\r\nexports.encode = encode;\r\nfunction parse(cookieString) {\r\n var result = {};\r\n var cookies = cookieString ? cookieString.split('; ') : [];\r\n var rdecode = /(%[\\dA-F]{2})+/gi;\r\n for (var i = 0; i < cookies.length; i++) {\r\n var parts = cookies[i].split('=');\r\n var cookie = parts.slice(1).join('=');\r\n if (cookie.charAt(0) === '\"') {\r\n cookie = cookie.slice(1, -1);\r\n }\r\n try {\r\n var name_1 = parts[0].replace(rdecode, decodeURIComponent);\r\n result[name_1] = cookie.replace(rdecode, decodeURIComponent);\r\n }\r\n catch (e) {\r\n // ignore cookies with invalid name/value encoding\r\n }\r\n }\r\n return result;\r\n}\r\nexports.parse = parse;\r\nfunction getAll() {\r\n return parse(document.cookie);\r\n}\r\nexports.getAll = getAll;\r\nfunction get(name) {\r\n return getAll()[name];\r\n}\r\nexports.get = get;\r\nfunction set(name, value, attributes) {\r\n document.cookie = encode(name, value, __assign({ path: '/' }, attributes));\r\n}\r\nexports.set = set;\r\nfunction remove(name, attributes) {\r\n set(name, '', __assign(__assign({}, attributes), { expires: -1 }));\r\n}\r\nexports.remove = remove;\r\n","import * as Cookies from 'es-cookie';\n\ninterface ClientStorageOptions {\n daysUntilExpire?: number;\n cookieDomain?: string;\n}\n\n/**\n * Defines a type that handles storage to/from a storage location\n */\nexport type ClientStorage = {\n get<T extends Object>(key: string): T | undefined;\n save(key: string, value: any, options?: ClientStorageOptions): void;\n remove(key: string, options?: ClientStorageOptions): void;\n};\n\n/**\n * A storage protocol for marshalling data to/from cookies\n */\nexport const CookieStorage = {\n get<T extends Object>(key: string) {\n const value = Cookies.get(key);\n\n if (typeof value === 'undefined') {\n return;\n }\n\n return <T>JSON.parse(value);\n },\n\n save(key: string, value: any, options?: ClientStorageOptions): void {\n let cookieAttributes: Cookies.CookieAttributes = {};\n\n if ('https:' === window.location.protocol) {\n cookieAttributes = {\n secure: true,\n sameSite: 'none'\n };\n }\n\n if (options?.daysUntilExpire) {\n cookieAttributes.expires = options.daysUntilExpire;\n }\n\n if (options?.cookieDomain) {\n cookieAttributes.domain = options.cookieDomain;\n }\n\n Cookies.set(key, JSON.stringify(value), cookieAttributes);\n },\n\n remove(key: string, options?: ClientStorageOptions) {\n let cookieAttributes: Cookies.CookieAttributes = {};\n\n if (options?.cookieDomain) {\n cookieAttributes.domain = options.cookieDomain;\n }\n\n Cookies.remove(key, cookieAttributes);\n }\n} as ClientStorage;\n\n/**\n * @ignore\n */\nconst LEGACY_PREFIX = '_legacy_';\n\n/**\n * Cookie storage that creates a cookie for modern and legacy browsers.\n * See: https://web.dev/samesite-cookie-recipes/#handling-incompatible-clients\n */\nexport const CookieStorageWithLegacySameSite = {\n get<T extends Object>(key: string) {\n const value = CookieStorage.get<T>(key);\n\n if (value) {\n return value;\n }\n\n return CookieStorage.get<T>(`${LEGACY_PREFIX}${key}`);\n },\n\n save(key: string, value: any, options?: ClientStorageOptions): void {\n let cookieAttributes: Cookies.CookieAttributes = {};\n\n if ('https:' === window.location.protocol) {\n cookieAttributes = { secure: true };\n }\n\n if (options?.daysUntilExpire) {\n cookieAttributes.expires = options.daysUntilExpire;\n }\n\n if (options?.cookieDomain) {\n cookieAttributes.domain = options.cookieDomain;\n }\n\n Cookies.set(\n `${LEGACY_PREFIX}${key}`,\n JSON.stringify(value),\n cookieAttributes\n );\n CookieStorage.save(key, value, options);\n },\n\n remove(key: string, options?: ClientStorageOptions) {\n let cookieAttributes: Cookies.CookieAttributes = {};\n\n if (options?.cookieDomain) {\n cookieAttributes.domain = options.cookieDomain;\n }\n\n Cookies.remove(key, cookieAttributes);\n CookieStorage.remove(key, options);\n CookieStorage.remove(`${LEGACY_PREFIX}${key}`, options);\n }\n} as ClientStorage;\n\n/**\n * A storage protocol for marshalling data to/from session storage\n */\nexport const SessionStorage = {\n get<T extends Object>(key: string) {\n /* c8 ignore next 3 */\n if (typeof sessionStorage === 'undefined') {\n return;\n }\n\n const value = sessionStorage.getItem(key);\n\n if (value == null) {\n return;\n }\n\n return <T>JSON.parse(value);\n },\n\n save(key: string, value: any): void {\n sessionStorage.setItem(key, JSON.stringify(value));\n },\n\n remove(key: string) {\n sessionStorage.removeItem(key);\n }\n} as ClientStorage;\n","import { ICache } from './cache';\nimport type { Dpop } from './dpop/dpop';\nimport { CompleteResponse } from './MyAccountApiClient';\n\n/**\n * Configuration option for automatic interactive error handling.\n *\n * - `'popup'`: SDK automatically opens Universal Login popup on MFA error\n */\nexport type InteractiveErrorHandler = 'popup';\n\nexport interface AuthorizationParams {\n /**\n * - `'page'`: displays the UI with a full page view\n * - `'popup'`: displays the UI with a popup window\n * - `'touch'`: displays the UI in a way that leverages a touch interface\n * - `'wap'`: displays the UI with a \"feature phone\" type interface\n */\n display?: 'page' | 'popup' | 'touch' | 'wap';\n\n /**\n * - `'none'`: do not prompt user for login or consent on reauthentication\n * - `'login'`: prompt user for reauthentication\n * - `'consent'`: prompt user for consent before processing request\n * - `'select_account'`: prompt user to select an account\n */\n prompt?: 'none' | 'login' | 'consent' | 'select_account';\n\n /**\n * Maximum allowable elapsed time (in seconds) since authentication.\n * If the last time the user authenticated is greater than this value,\n * the user must be reauthenticated.\n */\n max_age?: string | number;\n\n /**\n * The space-separated list of language tags, ordered by preference.\n * For example: `'fr-CA fr en'`.\n */\n ui_locales?: string;\n\n /**\n * Previously issued ID Token.\n */\n id_token_hint?: string;\n\n /**\n * Provides a hint to Auth0 as to what flow should be displayed.\n * The default behavior is to show a login page but you can override\n * this by passing 'signup' to show the signup page instead.\n *\n * This only affects the New Universal Login Experience.\n */\n screen_hint?: 'signup' | 'login' | string;\n\n /**\n * The user's email address or other identifier. When your app knows\n * which user is trying to authenticate, you can provide this parameter\n * to pre-fill the email box or select the right session for sign-in.\n *\n * This currently only affects the classic Lock experience.\n */\n login_hint?: string;\n\n acr_values?: string;\n\n /**\n * The default scope to be used on authentication requests.\n *\n * This defaults to `profile email` if not set. If you are setting extra scopes and require\n * `profile` and `email` to be included then you must include them in the provided scope.\n *\n * Note: The `openid` scope is **always applied** regardless of this setting.\n */\n scope?: string;\n\n /**\n * The default audience to be used for requesting API access.\n */\n audience?: string;\n\n /**\n * The name of the connection configured for your application.\n * If null, it will redirect to the Auth0 Login Page and show\n * the Login Widget.\n */\n connection?: string;\n\n /**\n * The organization to log in to.\n *\n * This will specify an `organization` parameter in your user's login request.\n *\n * - If you provide an Organization ID (a string with the prefix `org_`), it will be validated against the `org_id` claim of your user's ID Token. The validation is case-sensitive.\n * - If you provide an Organization Name (a string *without* the prefix `org_`), it will be validated against the `org_name` claim of your user's ID Token. The validation is case-insensitive.\n * To use an Organization Name you must have \"Allow Organization Names in Authentication API\" switched on in your Auth0 settings dashboard.\n * More information is available on the [Auth0 documentation portal](https://auth0.com/docs/manage-users/organizations/configure-organizations/use-org-name-authentication-api)\n *\n */\n organization?: string;\n\n /**\n * The Id of an invitation to accept. This is available from the user invitation URL that is given when participating in a user invitation flow.\n */\n invitation?: string;\n\n /**\n * The default URL where Auth0 will redirect your browser to with\n * the authentication result. It must be whitelisted in\n * the \"Allowed Callback URLs\" field in your Auth0 Application's\n * settings. If not provided here, it should be provided in the other\n * methods that provide authentication.\n */\n redirect_uri?: string;\n\n /**\n * If you need to send custom parameters to the Authorization Server,\n * make sure to use the original parameter name.\n */\n [key: string]: any;\n}\n\nexport interface ClientAuthorizationParams extends Omit<AuthorizationParams, 'scope'> {\n scope?: string | Record<string, string>\n};\n\ninterface BaseLoginOptions {\n /**\n * URL parameters that will be sent back to the Authorization Server. This can be known parameters\n * defined by Auth0 or custom parameters that you define.\n */\n authorizationParams?: AuthorizationParams;\n}\n\nexport interface Auth0ClientOptions {\n /**\n * Your Auth0 account domain such as `'example.auth0.com'`,\n * `'example.eu.auth0.com'` or , `'example.mycompany.com'`\n * (when using [custom domains](https://auth0.com/docs/custom-domains))\n */\n domain: string;\n /**\n * The issuer to be used for validation of JWTs, optionally defaults to the domain above\n */\n issuer?: string;\n /**\n * The Client ID found on your Application settings page\n */\n clientId: string;\n /**\n * The value in seconds used to account for clock skew in JWT expirations.\n * Typically, this value is no more than a minute or two at maximum.\n * Defaults to 60s.\n */\n leeway?: number;\n\n /**\n * The location to use when storing cache data. Valid values are `memory` or `localstorage`.\n * The default setting is `memory`.\n *\n * Read more about [changing storage options in the Auth0 docs](https://auth0.com/docs/libraries/auth0-single-page-app-sdk#change-storage-options)\n */\n cacheLocation?: CacheLocation;\n\n /**\n * Specify a custom cache implementation to use for token storage and retrieval. This setting takes precedence over `cacheLocation` if they are both specified.\n */\n cache?: ICache;\n\n /**\n * If true, refresh tokens are used to fetch new access tokens from the Auth0 server. If false, the standard technique of using a hidden iframe and the `authorization_code` grant with `prompt=none` is used.\n * The default setting is `false`.\n *\n * Standard technique relies on cookies. Because browsers increasingly block third-party cookies, it requires a Custom Domain to function reliably. Refresh tokens serve as a fallback for environments where third-party cookies are blocked.\n * Using a Custom Domain with this set to `false` is the most secure and recommended approach.\n *\n * **Note**: Use of refresh tokens must be enabled by an administrator on your Auth0 client application.\n */\n useRefreshTokens?: boolean;\n\n /**\n * If true, fallback to the technique of using a hidden iframe and the `authorization_code` grant with `prompt=none` when unable to use refresh tokens. If false, the iframe fallback is not used and\n * errors relating to a failed `refresh_token` grant should be handled appropriately. The default setting is `false`.\n *\n * **Note**: There might be situations where doing silent auth with a Web Message response from an iframe is not possible,\n * like when you're serving your application from the file system or a custom protocol (like in a Desktop or Native app).\n * In situations like this you can disable the iframe fallback and handle the failed `refresh_token` grant and prompt the user to login interactively with `loginWithRedirect` or `loginWithPopup`.\"\n *\n * E.g. Using the `file:` protocol in an Electron application does not support that legacy technique.\n *\n * @example\n * let token: string;\n * try {\n * token = await auth0.getTokenSilently();\n * } catch (e) {\n * if (e.error === 'missing_refresh_token' || e.error === 'invalid_grant') {\n * auth0.loginWithRedirect();\n * }\n * }\n */\n useRefreshTokensFallback?: boolean;\n\n /**\n * A maximum number of seconds to wait before declaring background calls to /authorize as failed for timeout\n * Defaults to 60s.\n */\n authorizeTimeoutInSeconds?: number;\n\n /**\n * Specify the timeout for HTTP calls using `fetch`. The default is 10 seconds.\n */\n httpTimeoutInSeconds?: number;\n\n /**\n * Internal property to send information about the client to the authorization server.\n * @internal\n */\n auth0Client?: {\n name: string;\n version: string;\n env?: { [key: string]: string };\n };\n\n /**\n * Sets an additional cookie with no SameSite attribute to support legacy browsers\n * that are not compatible with the latest SameSite changes.\n * This will log a warning on modern browsers, you can disable the warning by setting\n * this to false but be aware that some older useragents will not work,\n * See https://www.chromium.org/updates/same-site/incompatible-clients\n * Defaults to true\n */\n legacySameSiteCookie?: boolean;\n\n /**\n * If `true`, the SDK will use a cookie when storing information about the auth transaction while\n * the user is going through the authentication flow on the authorization server.\n *\n * The default is `false`, in which case the SDK will use session storage.\n *\n * @notes\n *\n * You might want to enable this if you rely on your users being able to authenticate using flows that\n * may end up spanning across multiple tabs (e.g. magic links) or you cannot otherwise rely on session storage being available.\n */\n useCookiesForTransactions?: boolean;\n\n /**\n * Number of days until the cookie `auth0.is.authenticated` will expire\n * Defaults to 1.\n */\n sessionCheckExpiryDays?: number;\n\n /**\n * The domain the cookie is accessible from. If not set, the cookie is scoped to\n * the current domain, including the subdomain.\n *\n * Note: setting this incorrectly may cause silent authentication to stop working\n * on page load.\n *\n *\n * To keep a user logged in across multiple subdomains set this to your\n * top-level domain and prefixed with a `.` (eg: `.example.com`).\n */\n cookieDomain?: string;\n\n /**\n * If true, data to the token endpoint is transmitted as x-www-form-urlencoded data, if false it will be transmitted as JSON. The default setting is `true`.\n *\n * **Note:** Setting this to `false` may affect you if you use Auth0 Rules and are sending custom, non-primitive data. If you disable this,\n * please verify that your Auth0 Rules continue to work as intended.\n */\n useFormData?: boolean;\n\n /**\n * Modify the value used as the current time during the token validation.\n *\n * **Note**: Using this improperly can potentially compromise the token validation.\n */\n nowProvider?: () => Promise<number> | number;\n\n /**\n * If provided, the SDK will load the token worker from this URL instead of the integrated `blob`. An example of when this is useful is if you have strict\n * Content-Security-Policy (CSP) and wish to avoid needing to set `worker-src: blob:`. We recommend either serving the worker, which you can find in the module\n * at `<module_path>/dist/auth0-spa-js.worker.production.js`, from the same host as your application or using the Auth0 CDN\n * `https://cdn.auth0.com/js/auth0-spa-js/<version>/auth0-spa-js.worker.production.js`.\n *\n * **Note**: The worker is only used when `useRefreshTokens: true`, `cacheLocation: 'memory'`, and the `cache` is not custom.\n */\n workerUrl?: string;\n\n\n /**\n * If `true`, the SDK will allow the refreshing of tokens using MRRT\n */\n useMrrt?: boolean;\n\n /**\n * If `true`, DPoP (OAuth 2.0 Demonstrating Proof of Possession, RFC9449)\n * will be used to cryptographically bind tokens to this specific browser\n * so they can't be used from a different device in case of a leak.\n *\n * The default setting is `false`.\n */\n useDpop?: boolean;\n\n /**\n * Configures automatic handling of interactive authentication errors.\n *\n * When set, the SDK intercepts `mfa_required` errors from `getTokenSilently()`\n * and handles them automatically instead of throwing to the caller.\n *\n * - `'popup'`: Opens Universal Login in a popup to complete MFA.\n * The original `authorizationParams` (audience, scope) are preserved.\n * On success, the token is returned. On failure, popup errors are thrown.\n *\n * This option only affects `getTokenSilently()`. Other methods are not affected.\n *\n * @default undefined (MFA errors are thrown to the caller)\n */\n interactiveErrorHandler?: InteractiveErrorHandler;\n\n /**\n * URL parameters that will be sent back to the Authorization Server. This can be known parameters\n * defined by Auth0 or custom parameters that you define.\n */\n authorizationParams?: ClientAuthorizationParams;\n}\n\n/**\n * Configuration details exposed by the Auth0Client after initialization.\n *\n * @category Main\n */\nexport interface ClientConfiguration {\n /**\n * The Auth0 domain that was configured\n */\n domain: string;\n\n /**\n * The Auth0 client ID that was configured\n */\n clientId: string;\n}\n\n/**\n * The possible locations where tokens can be stored\n */\nexport type CacheLocation = 'memory' | 'localstorage';\n\n/**\n * @ignore\n */\nexport interface AuthorizeOptions extends AuthorizationParams {\n response_type: string;\n response_mode: string;\n redirect_uri?: string;\n nonce: string;\n state: string;\n scope: string;\n code_challenge: string;\n code_challenge_method: string;\n}\n\nexport interface RedirectLoginOptions<TAppState = any>\n extends BaseLoginOptions {\n /**\n * Used to store state before doing the redirect\n */\n appState?: TAppState;\n /**\n * Used to add to the URL fragment before redirecting\n */\n fragment?: string;\n /**\n * Used to control the redirect and not rely on the SDK to do the actual redirect.\n *\n * @example\n * const client = new Auth0Client({\n * async onRedirect(url) {\n * window.location.replace(url);\n * }\n * });\n * @deprecated since v2.0.1, use `openUrl` instead.\n */\n onRedirect?: (url: string) => Promise<void>;\n\n /**\n * Used to control the redirect and not rely on the SDK to do the actual redirect.\n *\n * @example\n * const client = new Auth0Client({\n * openUrl(url) {\n * window.location.replace(url);\n * }\n * });\n *\n * @example\n * import { Browser } from '@capacitor/browser';\n *\n * const client = new Auth0Client({\n * async openUrl(url) {\n * await Browser.open({ url });\n * }\n * });\n */\n openUrl?: (url: string) => Promise<void> | void;\n}\n\n/**\n * The types of responses expected from the authorization server.\n * - `code`: used for the standard login flow.\n * - `connect_code`: used for the connect account flow.\n */\nexport enum ResponseType {\n Code = 'code',\n ConnectCode = 'connect_code'\n}\n\nexport interface RedirectLoginResult<TAppState = any> {\n /**\n * State stored when the redirect request was made\n */\n appState?: TAppState;\n\n /**\n * The type of response, for login it will be `code`\n */\n response_type: ResponseType.Code;\n}\n\nexport interface PopupLoginOptions extends BaseLoginOptions { }\n\nexport interface PopupConfigOptions {\n /**\n * The number of seconds to wait for a popup response before\n * throwing a timeout error. Defaults to 60s\n */\n timeoutInSeconds?: number;\n\n /**\n * Accepts an already-created popup window to use. If not specified, the SDK\n * will create its own. This may be useful for platforms like iOS that have\n * security restrictions around when popups can be invoked (e.g. from a user click event)\n */\n popup?: any;\n\n /**\n * Controls whether the SDK automatically closes the popup window.\n *\n * - `true` (default): SDK closes the popup automatically after receiving the authorization response\n * - `false`: SDK does not close the popup. The caller is responsible for closing it, including on errors.\n *\n * Setting this to `false` is useful when you need full control over the popup lifecycle,\n * such as in Chrome extensions where closing the popup too early can terminate the\n * extension's service worker before authentication completes.\n *\n * When `closePopup: false`, you should close the popup in a try/finally block:\n * ```\n * const popup = window.open('', '_blank');\n * try {\n * await auth0.loginWithPopup({}, { popup, closePopup: false });\n * } finally {\n * popup.close();\n * }\n * ```\n *\n * @default true\n */\n closePopup?: boolean;\n}\n\nexport interface GetTokenSilentlyOptions {\n /**\n * When `off`, ignores the cache and always sends a\n * request to Auth0.\n * When `cache-only`, only reads from the cache and never sends a request to Auth0.\n * Defaults to `on`, where it both reads from the cache and sends a request to Auth0 as needed.\n */\n cacheMode?: 'on' | 'off' | 'cache-only';\n\n /**\n * Parameters that will be sent back to Auth0 as part of a request.\n */\n authorizationParams?: {\n /**\n * There's no actual redirect when getting a token silently,\n * but, according to the spec, a `redirect_uri` param is required.\n * Auth0 uses this parameter to validate that the current `origin`\n * matches the `redirect_uri` `origin` when sending the response.\n * It must be whitelisted in the \"Allowed Web Origins\" in your\n * Auth0 Application's settings.\n */\n redirect_uri?: string;\n\n /**\n * The scope that was used in the authentication request\n */\n scope?: string;\n\n /**\n * The audience that was used in the authentication request\n */\n audience?: string;\n\n /**\n * If you need to send custom parameters to the Authorization Server,\n * make sure to use the original parameter name.\n */\n [key: string]: any;\n };\n\n /** A maximum number of seconds to wait before declaring the background /authorize call as failed for timeout\n * Defaults to 60s.\n */\n timeoutInSeconds?: number;\n\n /**\n * If true, the full response from the /oauth/token endpoint (or the cache, if the cache was used) is returned\n * (minus `refresh_token` if one was issued). Otherwise, just the access token is returned.\n *\n * The default is `false`.\n */\n detailedResponse?: boolean;\n}\n\nexport interface GetTokenWithPopupOptions extends PopupLoginOptions {\n /**\n * When `off`, ignores the cache and always sends a request to Auth0.\n * When `cache-only`, only reads from the cache and never sends a request to Auth0.\n * Defaults to `on`, where it both reads from the cache and sends a request to Auth0 as needed.\n */\n cacheMode?: 'on' | 'off' | 'cache-only';\n}\n\nexport interface LogoutUrlOptions {\n /**\n * The `clientId` of your application.\n *\n * If this property is not set, then the `clientId` that was used during initialization of the SDK is sent to the logout endpoint.\n *\n * If this property is set to `null`, then no client ID value is sent to the logout endpoint.\n *\n * [Read more about how redirecting after logout works](https://auth0.com/docs/logout/guides/redirect-users-after-logout)\n */\n clientId?: string | null;\n\n /**\n * Parameters to pass to the logout endpoint. This can be known parameters defined by Auth0 or custom parameters\n * you wish to provide.\n */\n logoutParams?: {\n /**\n * When supported by the upstream identity provider,\n * forces the user to logout of their identity provider\n * and from Auth0.\n * [Read more about how federated logout works at Auth0](https://auth0.com/docs/logout/guides/logout-idps)\n */\n federated?: boolean;\n /**\n * The URL where Auth0 will redirect your browser to after the logout.\n *\n * **Note**: If the `client_id` parameter is included, the\n * `returnTo` URL that is provided must be listed in the\n * Application's \"Allowed Logout URLs\" in the Auth0 dashboard.\n * However, if the `client_id` parameter is not included, the\n * `returnTo` URL must be listed in the \"Allowed Logout URLs\" at\n * the account level in the Auth0 dashboard.\n *\n * [Read more about how redirecting after logout works](https://auth0.com/docs/logout/guides/redirect-users-after-logout)\n */\n returnTo?: string;\n\n /**\n * If you need to send custom parameters to the logout endpoint, make sure to use the original parameter name.\n */\n [key: string]: any;\n };\n}\n\nexport interface LogoutOptions extends LogoutUrlOptions {\n /**\n * Used to control the redirect and not rely on the SDK to do the actual redirect.\n *\n * @example\n * await auth0.logout({\n * async onRedirect(url) {\n * window.location.replace(url);\n * }\n * });\n * @deprecated since v2.0.1, use `openUrl` instead.\n */\n onRedirect?: (url: string) => Promise<void>;\n\n /**\n * Used to control the redirect and not rely on the SDK to do the actual redirect.\n *\n * Set to `false` to disable the redirect, or provide a function to handle the actual redirect yourself.\n *\n * @example\n * await auth0.logout({\n * openUrl(url) {\n * window.location.replace(url);\n * }\n * });\n *\n * @example\n * import { Browser } from '@capacitor/browser';\n *\n * await auth0.logout({\n * async openUrl(url) {\n * await Browser.open({ url });\n * }\n * });\n */\n openUrl?: false | ((url: string) => Promise<void> | void);\n}\n\nexport interface RedirectConnectAccountOptions<TAppState = any> {\n /**\n * The name of the connection to link (e.g. 'google-oauth2').\n */\n connection: string;\n\n /**\n * Array of scopes to request from the Identity Provider during the connect account flow.\n * \n * @example\n * await auth0.connectAccountWithRedirect({\n * connection: 'google-oauth2',\n * scopes: ['https://www.googleapis.com/auth/calendar']\n * });\n */\n scopes?: string[];\n\n /**\n * Additional authorization parameters for the request.\n *\n * @example\n * await auth0.connectAccountWithRedirect({\n * connection: 'github',\n * authorization_params: {\n * audience: 'https://api.github.com'\n * }\n * });\n */\n authorization_params?: AuthorizationParams;\n\n /**\n * The URI to redirect back to after connecting the account.\n */\n redirectUri?: string;\n\n /**\n * Optional application state to persist through the transaction.\n *\n * @example\n * await auth0.connectAccountWithRedirect({\n * connection: 'google-oauth2',\n * appState: { returnTo: '/settings' }\n * });\n */\n appState?: TAppState;\n\n /**\n * Optional function to handle the redirect URL.\n *\n * @example\n * await auth0.connectAccountWithRedirect({\n * connection: 'google-oauth2',\n * openUrl: async (url) => { myBrowserApi.open(url); }\n * });\n */\n openUrl?: (url: string) => Promise<void>;\n}\n\n/**\n * The result returned after a successful account connection redirect.\n *\n * Combines the redirect login result (including any persisted app state)\n * with the complete response from the My Account API.\n *\n * @template TAppState - The type of application state persisted through the transaction.\n * @example\n * const result = await auth0.connectAccountWithRedirect(options);\n * console.log(result.appState); // Access persisted app state\n * console.log(result.connection); // The connection of the account you connected to.\n * console.log(result.response_type === 'connect_code'); // The response type will be 'connect_code'\n */\nexport type ConnectAccountRedirectResult<TAppState = any> = CompleteResponse & {\n /**\n * State stored when the redirect request was made\n */\n appState?: TAppState;\n\n /**\n * The type of response, for connect account it will be `connect_code`\n */\n response_type: ResponseType.ConnectCode;\n};\n\n/**\n * @ignore\n */\nexport interface AuthenticationResult {\n state: string;\n code?: string;\n /**\n * This is for the redirect from the connect account flow.\n */\n connect_code?: string;\n error?: string;\n error_description?: string;\n}\n\n/**\n * @ignore\n */\nexport interface TokenEndpointOptions {\n baseUrl: string;\n client_id: string;\n grant_type: string;\n timeout?: number;\n auth0Client: any;\n useFormData?: boolean;\n dpop?: Pick<Dpop, 'generateProof' | 'getNonce' | 'setNonce'>;\n [key: string]: any;\n}\n\nexport type TokenEndpointResponse = {\n id_token: string;\n token_type: string;\n access_token: string;\n refresh_token?: string;\n expires_in: number;\n scope?: string;\n};\n\n/**\n * @ignore\n */\nexport interface OAuthTokenOptions extends TokenEndpointOptions {\n code_verifier: string;\n code: string;\n redirect_uri: string;\n audience: string;\n scope: string;\n}\n\n/**\n * @ignore\n */\nexport interface RefreshTokenOptions extends TokenEndpointOptions {\n refresh_token: string;\n}\n\n/**\n * @ignore\n */\nexport interface JWTVerifyOptions {\n iss: string;\n aud: string;\n id_token: string;\n nonce?: string;\n leeway?: number;\n max_age?: number;\n organization?: string;\n now?: number;\n}\n\nexport interface IdToken {\n __raw: string;\n name?: string;\n given_name?: string;\n family_name?: string;\n middle_name?: string;\n nickname?: string;\n preferred_username?: string;\n profile?: string;\n picture?: string;\n website?: string;\n email?: string;\n email_verified?: boolean;\n gender?: string;\n birthdate?: string;\n zoneinfo?: string;\n locale?: string;\n phone_number?: string;\n phone_number_verified?: boolean;\n address?: string;\n updated_at?: string;\n iss?: string;\n aud?: string;\n exp?: number;\n nbf?: number;\n iat?: number;\n jti?: string;\n azp?: string;\n nonce?: string;\n auth_time?: string;\n at_hash?: string;\n c_hash?: string;\n acr?: string;\n amr?: string[];\n sub_jwk?: string;\n cnf?: string;\n sid?: string;\n org_id?: string;\n org_name?: string;\n [key: string]: any;\n}\n\nexport class User {\n name?: string;\n given_name?: string;\n family_name?: string;\n middle_name?: string;\n nickname?: string;\n preferred_username?: string;\n profile?: string;\n picture?: string;\n website?: string;\n email?: string;\n email_verified?: boolean;\n gender?: string;\n birthdate?: string;\n zoneinfo?: string;\n locale?: string;\n phone_number?: string;\n phone_number_verified?: boolean;\n address?: string;\n updated_at?: string;\n sub?: string;\n [key: string]: any;\n}\n\n/**\n * @ignore\n */\nexport type FetchOptions = {\n method?: string;\n headers?: Record<string, string>;\n credentials?: 'include' | 'omit';\n body?: string;\n signal?: AbortSignal;\n};\n\n/**\n * @ignore\n */\nexport type FetchResponse = {\n ok: boolean;\n headers: Record<string, string | undefined>;\n json: any;\n};\n\nexport type GetTokenSilentlyVerboseResponse = Omit<\n TokenEndpointResponse,\n 'refresh_token'\n>;\n\n// MFA API types\nexport type {\n Authenticator,\n AuthenticatorType,\n OobChannel,\n MfaFactorType,\n EnrollParams,\n EnrollOtpParams,\n EnrollSmsParams,\n EnrollVoiceParams,\n EnrollEmailParams,\n EnrollPushParams,\n EnrollmentResponse,\n OtpEnrollmentResponse,\n OobEnrollmentResponse,\n ChallengeAuthenticatorParams,\n ChallengeResponse,\n VerifyParams,\n MfaGrantType,\n EnrollmentFactor\n} from './mfa/types';\n","const singlePromiseMap: Record<string, Promise<any>> = {};\n\nexport const singlePromise = <T>(\n cb: () => Promise<T>,\n key: string\n): Promise<T> => {\n let promise: null | Promise<T> = singlePromiseMap[key];\n if (!promise) {\n promise = cb().finally(() => {\n delete singlePromiseMap[key];\n promise = null;\n });\n singlePromiseMap[key] = promise;\n }\n return promise;\n};\n\nexport const retryPromise = async (\n cb: () => Promise<boolean>,\n maxNumberOfRetries = 3\n) => {\n for (let i = 0; i < maxNumberOfRetries; i++) {\n if (await cb()) {\n return true;\n }\n }\n\n return false;\n};\n","import {\n CACHE_KEY_PREFIX,\n ICache,\n KeyManifestEntry,\n MaybePromise\n} from './shared';\n\nexport class CacheKeyManifest {\n private readonly manifestKey: string;\n\n constructor(private cache: ICache, private clientId: string) {\n this.manifestKey = this.createManifestKeyFrom(this.clientId);\n }\n\n async add(key: string): Promise<void> {\n const keys = new Set(\n (await this.cache.get<KeyManifestEntry>(this.manifestKey))?.keys || []\n );\n\n keys.add(key);\n\n await this.cache.set<KeyManifestEntry>(this.manifestKey, {\n keys: [...keys]\n });\n }\n\n async remove(key: string): Promise<void> {\n const entry = await this.cache.get<KeyManifestEntry>(this.manifestKey);\n\n if (entry) {\n const keys = new Set(entry.keys);\n keys.delete(key);\n\n if (keys.size > 0) {\n return await this.cache.set(this.manifestKey, { keys: [...keys] });\n }\n\n return await this.cache.remove(this.manifestKey);\n }\n }\n\n get(): MaybePromise<KeyManifestEntry | undefined> {\n return this.cache.get<KeyManifestEntry>(this.manifestKey);\n }\n\n clear(): MaybePromise<void> {\n return this.cache.remove(this.manifestKey);\n }\n\n private createManifestKeyFrom(clientId: string): string {\n return `${CACHE_KEY_PREFIX}::${clientId}`;\n }\n}\n","import { ICache, InMemoryCache, LocalStorageCache } from './cache';\nimport {\n Auth0ClientOptions,\n AuthorizationParams,\n AuthorizeOptions,\n ClientAuthorizationParams,\n LogoutOptions\n} from './global';\nimport { scopesToRequest } from './scope';\n\n/**\n * @ignore\n */\nexport const GET_TOKEN_SILENTLY_LOCK_KEY = 'auth0.lock.getTokenSilently';\n\n/**\n * @ignore\n */\nexport const GET_TOKEN_FROM_IFRAME_LOCK_KEY = 'auth0.lock.getTokenFromIFrame';\n\n/**\n * @ignore\n */\nexport const buildGetTokenSilentlyLockKey = (\n clientId: string,\n audience: string\n) => `${GET_TOKEN_SILENTLY_LOCK_KEY}.${clientId}.${audience}`;\n\n/**\n * @ignore\n * Builds a global lock key for iframe-based authentication flows.\n * This ensures only one iframe authorization request runs at a time per client,\n * preventing \"Invalid state\" errors from concurrent iframe requests overwriting\n * each other's state in the Auth0 session.\n */\nexport const buildIframeLockKey = (clientId: string) =>\n `${GET_TOKEN_FROM_IFRAME_LOCK_KEY}.${clientId}`;\n\n/**\n * @ignore\n */\nexport const buildOrganizationHintCookieName = (clientId: string) =>\n `auth0.${clientId}.organization_hint`;\n\n/**\n * @ignore\n */\nexport const OLD_IS_AUTHENTICATED_COOKIE_NAME = 'auth0.is.authenticated';\n\n/**\n * @ignore\n */\nexport const buildIsAuthenticatedCookieName = (clientId: string) =>\n `auth0.${clientId}.is.authenticated`;\n\n/**\n * @ignore\n */\nconst cacheLocationBuilders: Record<string, () => ICache> = {\n memory: () => new InMemoryCache().enclosedCache,\n localstorage: () => new LocalStorageCache()\n};\n\n/**\n * @ignore\n */\nexport const cacheFactory = (location: string) => {\n return cacheLocationBuilders[location];\n};\n\n/**\n * @ignore\n */\nexport const getAuthorizeParams = (\n clientOptions: Auth0ClientOptions & {\n authorizationParams: ClientAuthorizationParams;\n },\n scope: Record<string, string>,\n authorizationParams: AuthorizationParams & { scope?: string },\n state: string,\n nonce: string,\n code_challenge: string,\n redirect_uri: string | undefined,\n response_mode: string | undefined,\n thumbprint: string | undefined\n): AuthorizeOptions => {\n return {\n client_id: clientOptions.clientId,\n ...clientOptions.authorizationParams,\n ...authorizationParams,\n scope: scopesToRequest(scope, authorizationParams.scope, authorizationParams.audience),\n response_type: 'code',\n response_mode: response_mode || 'query',\n state,\n nonce,\n redirect_uri:\n redirect_uri || clientOptions.authorizationParams.redirect_uri,\n code_challenge,\n code_challenge_method: 'S256',\n dpop_jkt: thumbprint\n };\n};\n\n/**\n * @ignore\n *\n * Function used to provide support for the deprecated onRedirect through openUrl.\n */\nexport const patchOpenUrlWithOnRedirect = <\n T extends Pick<LogoutOptions, 'openUrl' | 'onRedirect'>\n>(\n options: T\n) => {\n const { openUrl, onRedirect, ...originalOptions } = options;\n\n const result = {\n ...originalOptions,\n openUrl: openUrl === false || openUrl ? openUrl : onRedirect\n };\n\n return result as T;\n};\n\n/**\n * @ignore\n * \n * Checks if all scopes are included inside other array of scopes\n */\nexport const allScopesAreIncluded = (scopeToInclude?: string, scopes?: string): boolean => {\n const scopeGroup = scopes?.split(\" \") || [];\n const scopesToInclude = scopeToInclude?.split(\" \") || [];\n return scopesToInclude.every((key) => scopeGroup.includes(key));\n}\n\n/**\n * @ignore\n * \n * Returns the scopes that are missing after a refresh\n */\nexport const getMissingScopes = (requestedScope?: string, respondedScope?: string): string => {\n const requestedScopes = requestedScope?.split(\" \") || [];\n const respondedScopes = respondedScope?.split(\" \") || [];\n\n const missingScopes = requestedScopes.filter((scope) => respondedScopes.indexOf(scope) == -1);\n\n return missingScopes.join(\",\");\n}\n\n/**\n * @ignore\n *\n * For backward compatibility we are going to check if we are going to downscope while doing a refresh request\n * while MRRT is allowed. If the audience is the same for the refresh_token we are going to use and it has\n * lower scopes than the ones originally in the token, we are going to return the scopes that were stored\n * with the refresh_token in the tokenset.\n * @param useMrrt Setting that the user can activate to use MRRT in their requests\n * @param authorizationParams Contains the audience and scope that the user requested to obtain a token\n * @param cachedAudience Audience stored with the refresh_token wich we are going to use in the request\n * @param cachedScope Scope stored with the refresh_token wich we are going to use in the request\n */\nexport const getScopeToRequest = (\n useMrrt: boolean | undefined,\n authorizationParams: { audience?: string, scope: string },\n cachedAudience?: string,\n cachedScope?: string\n): string => {\n if (useMrrt && cachedAudience && cachedScope) {\n if (authorizationParams.audience !== cachedAudience) {\n return authorizationParams.scope;\n }\n\n const cachedScopes = cachedScope.split(\" \");\n const newScopes = authorizationParams.scope?.split(\" \") || [];\n const newScopesAreIncluded = newScopes.every((scope) => cachedScopes.includes(scope));\n\n return cachedScopes.length >= newScopes.length && newScopesAreIncluded ? cachedScope : authorizationParams.scope;\n }\n\n return authorizationParams.scope;\n}\n\n/**\n * @ignore\n * \n * Checks if the refresh request has been done using MRRT\n * @param cachedAudience Audience from the refresh token used to refresh\n * @param cachedScope Scopes from the refresh token used to refresh\n * @param requestAudience Audience sent to the server\n * @param requestScope Scopes sent to the server\n */\nexport const isRefreshWithMrrt = (\n cachedAudience: string | undefined,\n cachedScope: string | undefined,\n requestAudience: string | undefined,\n requestScope: string,\n): boolean => {\n if (cachedAudience !== requestAudience) {\n return true;\n }\n\n return !allScopesAreIncluded(requestScope, cachedScope);\n}","import { type KeyPair } from './utils';\n\nconst VERSION = 1;\nconst NAME = 'auth0-spa-js';\nconst TABLES = {\n NONCE: 'nonce',\n KEYPAIR: 'keypair'\n} as const;\n\nconst AUTH0_NONCE_ID = 'auth0';\n\ntype Table = (typeof TABLES)[keyof typeof TABLES];\n\nexport class DpopStorage {\n protected readonly clientId: string;\n protected dbHandle: IDBDatabase | undefined;\n\n constructor(clientId: string) {\n this.clientId = clientId;\n }\n\n protected getVersion(): number {\n return VERSION;\n }\n\n protected createDbHandle(): Promise<IDBDatabase> {\n const req = window.indexedDB.open(NAME, this.getVersion());\n\n return new Promise((resolve, reject) => {\n req.onupgradeneeded = () =>\n Object.values(TABLES).forEach(t => req.result.createObjectStore(t));\n\n req.onerror = () => reject(req.error);\n req.onsuccess = () => resolve(req.result);\n });\n }\n\n protected async getDbHandle(): Promise<IDBDatabase> {\n if (!this.dbHandle) {\n this.dbHandle = await this.createDbHandle();\n }\n\n return this.dbHandle;\n }\n\n protected async executeDbRequest<T = unknown>(\n table: string,\n mode: IDBTransactionMode,\n requestFactory: (table: IDBObjectStore) => IDBRequest<T>\n ): Promise<T> {\n const db = await this.getDbHandle();\n\n const txn = db.transaction(table, mode);\n const store = txn.objectStore(table);\n\n const request = requestFactory(store);\n\n return new Promise((resolve, reject) => {\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n });\n }\n\n protected buildKey(id?: string): string {\n const finalId = id\n ? `_${id}` // prefix to avoid collisions\n : AUTH0_NONCE_ID;\n\n return `${this.clientId}::${finalId}`;\n }\n\n public setNonce(nonce: string, id?: string): Promise<void> {\n return this.save(TABLES.NONCE, this.buildKey(id), nonce);\n }\n\n public setKeyPair(keyPair: KeyPair): Promise<void> {\n return this.save(TABLES.KEYPAIR, this.buildKey(), keyPair);\n }\n\n protected async save(\n table: Table,\n key: IDBValidKey,\n obj: unknown\n ): Promise<void> {\n return void await this.executeDbRequest(table, 'readwrite', table =>\n table.put(obj, key)\n );\n }\n\n public findNonce(id?: string): Promise<string | undefined> {\n return this.find(TABLES.NONCE, this.buildKey(id));\n }\n\n public findKeyPair(): Promise<KeyPair | undefined> {\n return this.find(TABLES.KEYPAIR, this.buildKey());\n }\n\n protected find<T = unknown>(\n table: Table,\n key: IDBValidKey\n ): Promise<T | undefined> {\n return this.executeDbRequest(table, 'readonly', table => table.get(key));\n }\n\n protected async deleteBy(\n table: Table,\n predicate: (key: IDBValidKey) => boolean\n ): Promise<void> {\n const allKeys = await this.executeDbRequest(table, 'readonly', table =>\n table.getAllKeys()\n );\n\n allKeys\n ?.filter(predicate)\n .map(k =>\n this.executeDbRequest(table, 'readwrite', table => table.delete(k))\n );\n }\n\n protected deleteByClientId(table: Table, clientId: string): Promise<void> {\n return this.deleteBy(\n table,\n k => typeof k === 'string' && k.startsWith(`${clientId}::`)\n );\n }\n\n public clearNonces(): Promise<void> {\n return this.deleteByClientId(TABLES.NONCE, this.clientId);\n }\n\n public clearKeyPairs(): Promise<void> {\n return this.deleteByClientId(TABLES.KEYPAIR, this.clientId);\n }\n}\n","import { DpopStorage } from './storage';\nimport * as dpopUtils from './utils';\n\nexport class Dpop {\n protected readonly storage: DpopStorage;\n\n public constructor(clientId: string) {\n this.storage = new DpopStorage(clientId);\n }\n\n public getNonce(id?: string): Promise<string | undefined> {\n return this.storage.findNonce(id);\n }\n\n public setNonce(nonce: string, id?: string): Promise<void> {\n return this.storage.setNonce(nonce, id);\n }\n\n protected async getOrGenerateKeyPair(): Promise<dpopUtils.KeyPair> {\n let keyPair = await this.storage.findKeyPair();\n\n if (!keyPair) {\n keyPair = await dpopUtils.generateKeyPair();\n await this.storage.setKeyPair(keyPair);\n }\n\n return keyPair;\n }\n\n public async generateProof(params: {\n url: string;\n method: string;\n nonce?: string;\n accessToken?: string;\n }): Promise<string> {\n const keyPair = await this.getOrGenerateKeyPair();\n\n return dpopUtils.generateProof({\n keyPair,\n ...params\n });\n }\n\n public async calculateThumbprint(): Promise<string> {\n const keyPair = await this.getOrGenerateKeyPair();\n\n return dpopUtils.calculateThumbprint(keyPair);\n }\n\n public async clear(): Promise<void> {\n await Promise.all([\n this.storage.clearNonces(),\n this.storage.clearKeyPairs()\n ]);\n }\n}\n","import { DPOP_NONCE_HEADER } from './dpop/utils';\nimport { UseDpopNonceError } from './errors';\nimport { GetTokenSilentlyVerboseResponse } from './global';\n\nexport type ResponseHeaders =\n | Record<string, string | null | undefined>\n | [string, string][]\n | { get(name: string): string | null | undefined };\n\nexport type CustomFetchMinimalOutput = {\n status: number;\n headers: ResponseHeaders;\n};\n\nexport type CustomFetchImpl<TOutput extends CustomFetchMinimalOutput> = (\n req: Request\n) => Promise<TOutput>;\n\nexport type AuthParams = {\n scope?: string[];\n audience?: string;\n};\n\ntype AccessTokenFactory = (authParams?: AuthParams) => Promise<string | GetTokenSilentlyVerboseResponse>;\n\nenum TokenType {\n Bearer = 'Bearer',\n DPoP = 'DPoP'\n}\n\nexport type FetcherConfig<TOutput extends CustomFetchMinimalOutput> = {\n getAccessToken?: AccessTokenFactory;\n baseUrl?: string;\n fetch?: CustomFetchImpl<TOutput>;\n dpopNonceId?: string;\n};\n\nexport type FetcherHooks = {\n isDpopEnabled: () => boolean;\n getAccessToken: AccessTokenFactory;\n getDpopNonce: () => Promise<string | undefined>;\n setDpopNonce: (nonce: string) => Promise<void>;\n generateDpopProof: (params: {\n url: string;\n method: string;\n nonce?: string;\n accessToken: string;\n }) => Promise<string>;\n};\n\nexport type FetchWithAuthCallbacks<TOutput> = {\n onUseDpopNonceError?(): Promise<TOutput>;\n};\n\nexport class Fetcher<TOutput extends CustomFetchMinimalOutput> {\n protected readonly config: Omit<FetcherConfig<TOutput>, 'fetch'> &\n Required<Pick<FetcherConfig<TOutput>, 'fetch'>>;\n\n protected readonly hooks: FetcherHooks;\n\n constructor(config: FetcherConfig<TOutput>, hooks: FetcherHooks) {\n this.hooks = hooks;\n\n this.config = {\n ...config,\n fetch:\n config.fetch ||\n // For easier testing and constructor compatibility with SSR.\n ((typeof window === 'undefined'\n ? fetch\n : window.fetch.bind(window)) as () => Promise<any>)\n };\n }\n\n protected isAbsoluteUrl(url: string): boolean {\n // `http://example.com`, `https://example.com` or `//example.com`\n return /^(https?:)?\\/\\//i.test(url);\n }\n\n protected buildUrl(\n baseUrl: string | undefined,\n url: string | undefined\n ): string {\n if (url) {\n if (this.isAbsoluteUrl(url)) {\n return url;\n }\n\n if (baseUrl) {\n return `${baseUrl.replace(/\\/?\\/$/, '')}/${url.replace(/^\\/+/, '')}`;\n }\n }\n\n throw new TypeError('`url` must be absolute or `baseUrl` non-empty.');\n }\n\n protected getAccessToken(authParams?: AuthParams): Promise<string | GetTokenSilentlyVerboseResponse> {\n return this.config.getAccessToken\n ? this.config.getAccessToken(authParams)\n : this.hooks.getAccessToken(authParams);\n }\n\n protected extractUrl(info: RequestInfo | URL): string {\n if (typeof info === 'string') {\n return info;\n }\n\n if (info instanceof URL) {\n return info.href;\n }\n\n return info.url;\n }\n\n protected buildBaseRequest(\n info: RequestInfo | URL,\n init: RequestInit | undefined\n ): Request {\n // In the native `fetch()` behavior, `init` can override `info` and the result\n // is the merge of both. So let's replicate that behavior by passing those into\n // a fresh `Request` object.\n\n // No `baseUrl`? We can use `info` and `init` as is.\n if (!this.config.baseUrl) {\n return new Request(info, init);\n }\n\n // But if `baseUrl` is present, first we have to build the final URL...\n const finalUrl = this.buildUrl(this.config.baseUrl, this.extractUrl(info));\n\n // ... and then overwrite `info`'s URL with it, making sure we keep any other\n // properties that might be there already (headers, etc).\n const finalInfo = info instanceof Request\n ? new Request(finalUrl, info)\n : finalUrl;\n\n return new Request(finalInfo, init);\n }\n\n protected setAuthorizationHeader(\n request: Request,\n accessToken: string,\n tokenType: string = TokenType.Bearer\n ): void {\n request.headers.set(\n 'authorization',\n `${tokenType} ${accessToken}`\n );\n }\n\n protected async setDpopProofHeader(\n request: Request,\n accessToken: string\n ): Promise<void> {\n if (!this.config.dpopNonceId) {\n return;\n }\n\n const dpopNonce = await this.hooks.getDpopNonce();\n\n const dpopProof = await this.hooks.generateDpopProof({\n accessToken,\n method: request.method,\n nonce: dpopNonce,\n url: request.url\n });\n\n request.headers.set('dpop', dpopProof);\n }\n\n protected async prepareRequest(request: Request, authParams?: AuthParams) {\n const accessTokenResponse = await this.getAccessToken(authParams);\n\n let tokenType: string;\n let accessToken: string;\n if (typeof accessTokenResponse === 'string') {\n tokenType = this.config.dpopNonceId ? TokenType.DPoP : TokenType.Bearer;\n accessToken = accessTokenResponse;\n } else {\n tokenType = accessTokenResponse.token_type;\n accessToken = accessTokenResponse.access_token;\n }\n\n this.setAuthorizationHeader(request, accessToken, tokenType);\n if (tokenType === TokenType.DPoP) {\n await this.setDpopProofHeader(request, accessToken);\n }\n }\n\n protected getHeader(headers: ResponseHeaders, name: string): string {\n if (Array.isArray(headers)) {\n return new Headers(headers).get(name) || '';\n }\n\n if (typeof headers.get === 'function') {\n return headers.get(name) || '';\n }\n\n return (headers as Record<string, string | null | undefined>)[name] || '';\n }\n\n protected hasUseDpopNonceError(response: TOutput): boolean {\n if (response.status !== 401) {\n return false;\n }\n\n const wwwAuthHeader = this.getHeader(response.headers, 'www-authenticate');\n\n return wwwAuthHeader.includes('invalid_dpop_nonce') || wwwAuthHeader.includes('use_dpop_nonce');\n }\n\n protected async handleResponse(\n response: TOutput,\n callbacks: FetchWithAuthCallbacks<TOutput>\n ): Promise<TOutput> {\n const newDpopNonce = this.getHeader(response.headers, DPOP_NONCE_HEADER);\n\n if (newDpopNonce) {\n await this.hooks.setDpopNonce(newDpopNonce);\n }\n\n if (!this.hasUseDpopNonceError(response)) {\n return response;\n }\n\n // After a `use_dpop_nonce` error, if we didn't get a new DPoP nonce or we\n // did but it still got rejected for the same reason, we have to give up.\n if (!newDpopNonce || !callbacks.onUseDpopNonceError) {\n throw new UseDpopNonceError(newDpopNonce);\n }\n\n return callbacks.onUseDpopNonceError();\n }\n\n protected async internalFetchWithAuth(\n info: RequestInfo | URL,\n init: RequestInit | undefined,\n callbacks: FetchWithAuthCallbacks<TOutput>,\n authParams?: AuthParams\n ): Promise<TOutput> {\n const request = this.buildBaseRequest(info, init);\n\n await this.prepareRequest(request, authParams);\n\n const response = await this.config.fetch(request);\n\n return this.handleResponse(response, callbacks);\n }\n\n public fetchWithAuth(\n info: RequestInfo | URL,\n init?: RequestInit,\n authParams?: AuthParams\n ): Promise<TOutput> {\n const callbacks: FetchWithAuthCallbacks<TOutput> = {\n onUseDpopNonceError: () =>\n this.internalFetchWithAuth(\n info,\n init,\n {\n ...callbacks,\n // Retry on a `use_dpop_nonce` error, but just once.\n onUseDpopNonceError: undefined\n },\n authParams\n )\n };\n\n return this.internalFetchWithAuth(info, init, callbacks, authParams);\n }\n}\n","import { AuthorizationParams } from './global';\nimport { Fetcher } from './fetcher';\n\ninterface ConnectRequest {\n /** The name of the connection to link the account with (e.g., 'google-oauth2', 'facebook'). */\n connection: string;\n /** Array of scopes to request from the Identity Provider during the connect account flow. */\n scopes?: string[];\n /** The URI to redirect to after the connection process completes. */\n redirect_uri: string;\n /** An opaque value used to maintain state between the request and callback. */\n state?: string;\n /** The PKCE code challenge derived from the code verifier. */\n code_challenge?: string;\n /** The method used to derive the code challenge. Required when code_challenge is provided. */\n code_challenge_method?: 'S256';\n authorization_params?: AuthorizationParams;\n}\n\ninterface ConnectResponse {\n /** The base URI to initiate the account connection flow. */\n connect_uri: string;\n /** The authentication session identifier. */\n auth_session: string;\n /** Parameters to be used with the connect URI. */\n connect_params: {\n /** The ticket identifier to be used with the connection URI. */\n ticket: string;\n };\n /** The number of seconds until the ticket expires. */\n expires_in: number;\n}\n\ninterface CompleteRequest {\n /** The authentication session identifier */\n auth_session: string;\n /** The authorization code returned from the connect flow */\n connect_code: string;\n /** The redirect URI used in the original request */\n redirect_uri: string;\n /** The PKCE code verifier */\n code_verifier?: string;\n}\n\nexport interface CompleteResponse {\n /** The unique identifier of the connected account */\n id: string;\n /** The connection name */\n connection: string;\n /** The access type, always 'offline' */\n access_type: 'offline';\n /** Array of scopes granted */\n scopes?: string[];\n /** ISO date string of when the connected account was created */\n created_at: string;\n /** ISO date string of when the refresh token expires (optional) */\n expires_at?: string;\n}\n\n// Validation error returned from MyAccount API\nexport interface ErrorResponse {\n type: string;\n status: number;\n title: string;\n detail: string;\n validation_errors?: {\n detail: string;\n field?: string;\n pointer?: string;\n source?: string;\n }[];\n}\n\n/**\n * Subset of the MyAccount API that handles the connect accounts flow.\n */\nexport class MyAccountApiClient {\n constructor(\n private myAccountFetcher: Fetcher<Response>,\n private apiBase: string\n ) {}\n\n /**\n * Get a ticket for the connect account flow.\n */\n async connectAccount(params: ConnectRequest): Promise<ConnectResponse> {\n const res = await this.myAccountFetcher.fetchWithAuth(\n `${this.apiBase}v1/connected-accounts/connect`,\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(params)\n }\n );\n return this._handleResponse(res);\n }\n\n /**\n * Verify the redirect from the connect account flow and complete the connecting of the account.\n */\n async completeAccount(params: CompleteRequest): Promise<CompleteResponse> {\n const res = await this.myAccountFetcher.fetchWithAuth(\n `${this.apiBase}v1/connected-accounts/complete`,\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(params)\n }\n );\n return this._handleResponse(res);\n }\n\n private async _handleResponse(res: Response) {\n let body: any;\n try {\n body = await res.text();\n body = JSON.parse(body);\n } catch (err) {\n throw new MyAccountApiError({\n type: 'invalid_json',\n status: res.status,\n title: 'Invalid JSON response',\n detail: body || String(err)\n });\n }\n\n if (res.ok) {\n return body;\n } else {\n throw new MyAccountApiError(body);\n }\n }\n}\n\nexport class MyAccountApiError extends Error {\n public readonly type: string;\n public readonly status: number;\n public readonly title: string;\n public readonly detail: string;\n public readonly validation_errors?: ErrorResponse['validation_errors'];\n\n constructor({\n type,\n status,\n title,\n detail,\n validation_errors\n }: ErrorResponse) {\n super(detail);\n this.name = 'MyAccountApiError';\n this.type = type;\n this.status = status;\n this.title = title;\n this.detail = detail;\n this.validation_errors = validation_errors;\n Object.setPrototypeOf(this, MyAccountApiError.prototype);\n }\n}\n","import type { MfaFactorType, OobChannel } from './types';\n\n/**\n * Mapping configuration for a factor type\n */\nexport interface FactorMapping {\n authenticatorTypes: ['otp'] | ['oob'];\n oobChannels?: OobChannel[];\n}\n\n/**\n * Maps MFA factor types to auth-js enrollment parameters\n */\nexport const FACTOR_MAPPING: Record<MfaFactorType, FactorMapping> = {\n otp: {\n authenticatorTypes: ['otp']\n },\n sms: {\n authenticatorTypes: ['oob'],\n oobChannels: ['sms']\n },\n email: {\n authenticatorTypes: ['oob'],\n oobChannels: ['email']\n },\n push: {\n authenticatorTypes: ['oob'],\n oobChannels: ['auth0']\n },\n voice: {\n authenticatorTypes: ['oob'],\n oobChannels: ['voice']\n }\n};\n\n/**\n * MFA grant type constants for verification\n */\nexport const MfaGrantTypes = {\n /** Grant type for OTP (TOTP) verification */\n OTP: 'http://auth0.com/oauth/grant-type/mfa-otp',\n\n /** Grant type for OOB (SMS, Email, Push) verification */\n OOB: 'http://auth0.com/oauth/grant-type/mfa-oob',\n\n /** Grant type for recovery code verification */\n RECOVERY_CODE: 'http://auth0.com/oauth/grant-type/mfa-recovery-code'\n} as const;\n","import { FACTOR_MAPPING, MfaGrantTypes } from './constants';\nimport type { EnrollParams, VerifyParams, MfaGrantType } from './types';\n\n/**\n * Converts factor-based enrollment params to auth-js format\n *\n * @param params - The enrollment parameters with factorType\n * @returns Parameters in auth-js format with authenticatorTypes/oobChannels\n */\nexport function getAuthJsEnrollParams(params: EnrollParams) {\n const mapping = FACTOR_MAPPING[params.factorType];\n\n return {\n mfaToken: params.mfaToken,\n authenticatorTypes: mapping.authenticatorTypes,\n ...(mapping.oobChannels && { oobChannels: mapping.oobChannels }),\n ...('phoneNumber' in params && { phoneNumber: params.phoneNumber }),\n ...('email' in params && { email: params.email })\n };\n}\n\n/**\n * Gets the grant type from verification parameters based on which field is provided.\n *\n * Priority order: otp > oobCode > recoveryCode\n *\n * @param params - The verification parameters\n * @returns The grant type or undefined if no verification field is present\n */\nexport function getGrantType(params: VerifyParams): MfaGrantType | undefined {\n if ('otp' in params && params.otp) {\n return MfaGrantTypes.OTP;\n }\n if ('oobCode' in params && params.oobCode) {\n return MfaGrantTypes.OOB;\n }\n if ('recoveryCode' in params && params.recoveryCode) {\n return MfaGrantTypes.RECOVERY_CODE;\n }\n return undefined;\n}\n",null,"export const encoder = new TextEncoder();\nexport const decoder = new TextDecoder();\nconst MAX_INT32 = 2 ** 32;\nexport function concat(...buffers) {\n const size = buffers.reduce((acc, { length }) => acc + length, 0);\n const buf = new Uint8Array(size);\n let i = 0;\n for (const buffer of buffers) {\n buf.set(buffer, i);\n i += buffer.length;\n }\n return buf;\n}\nfunction writeUInt32BE(buf, value, offset) {\n if (value < 0 || value >= MAX_INT32) {\n throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`);\n }\n buf.set([value >>> 24, value >>> 16, value >>> 8, value & 0xff], offset);\n}\nexport function uint64be(value) {\n const high = Math.floor(value / MAX_INT32);\n const low = value % MAX_INT32;\n const buf = new Uint8Array(8);\n writeUInt32BE(buf, high, 0);\n writeUInt32BE(buf, low, 4);\n return buf;\n}\nexport function uint32be(value) {\n const buf = new Uint8Array(4);\n writeUInt32BE(buf, value);\n return buf;\n}\nexport function encode(string) {\n const bytes = new Uint8Array(string.length);\n for (let i = 0; i < string.length; i++) {\n const code = string.charCodeAt(i);\n if (code > 127) {\n throw new TypeError('non-ASCII string encountered in encode()');\n }\n bytes[i] = code;\n }\n return bytes;\n}\n","export function encodeBase64(input) {\n if (Uint8Array.prototype.toBase64) {\n return input.toBase64();\n }\n const CHUNK_SIZE = 0x8000;\n const arr = [];\n for (let i = 0; i < input.length; i += CHUNK_SIZE) {\n arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));\n }\n return btoa(arr.join(''));\n}\nexport function decodeBase64(encoded) {\n if (Uint8Array.fromBase64) {\n return Uint8Array.fromBase64(encoded);\n }\n const binary = atob(encoded);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n","import { encoder, decoder } from '../lib/buffer_utils.js';\nimport { encodeBase64, decodeBase64 } from '../lib/base64.js';\nexport function decode(input) {\n if (Uint8Array.fromBase64) {\n return Uint8Array.fromBase64(typeof input === 'string' ? input : decoder.decode(input), {\n alphabet: 'base64url',\n });\n }\n let encoded = input;\n if (encoded instanceof Uint8Array) {\n encoded = decoder.decode(encoded);\n }\n encoded = encoded.replace(/-/g, '+').replace(/_/g, '/');\n try {\n return decodeBase64(encoded);\n }\n catch {\n throw new TypeError('The input to be decoded is not correctly encoded.');\n }\n}\nexport function encode(input) {\n let unencoded = input;\n if (typeof unencoded === 'string') {\n unencoded = encoder.encode(unencoded);\n }\n if (Uint8Array.prototype.toBase64) {\n return unencoded.toBase64({ alphabet: 'base64url', omitPadding: true });\n }\n return encodeBase64(unencoded).replace(/=/g, '').replace(/\\+/g, '-').replace(/\\//g, '_');\n}\n","export class JOSEError extends Error {\n static code = 'ERR_JOSE_GENERIC';\n code = 'ERR_JOSE_GENERIC';\n constructor(message, options) {\n super(message, options);\n this.name = this.constructor.name;\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nexport class JWTClaimValidationFailed extends JOSEError {\n static code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';\n code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';\n claim;\n reason;\n payload;\n constructor(message, payload, claim = 'unspecified', reason = 'unspecified') {\n super(message, { cause: { claim, reason, payload } });\n this.claim = claim;\n this.reason = reason;\n this.payload = payload;\n }\n}\nexport class JWTExpired extends JOSEError {\n static code = 'ERR_JWT_EXPIRED';\n code = 'ERR_JWT_EXPIRED';\n claim;\n reason;\n payload;\n constructor(message, payload, claim = 'unspecified', reason = 'unspecified') {\n super(message, { cause: { claim, reason, payload } });\n this.claim = claim;\n this.reason = reason;\n this.payload = payload;\n }\n}\nexport class JOSEAlgNotAllowed extends JOSEError {\n static code = 'ERR_JOSE_ALG_NOT_ALLOWED';\n code = 'ERR_JOSE_ALG_NOT_ALLOWED';\n}\nexport class JOSENotSupported extends JOSEError {\n static code = 'ERR_JOSE_NOT_SUPPORTED';\n code = 'ERR_JOSE_NOT_SUPPORTED';\n}\nexport class JWEDecryptionFailed extends JOSEError {\n static code = 'ERR_JWE_DECRYPTION_FAILED';\n code = 'ERR_JWE_DECRYPTION_FAILED';\n constructor(message = 'decryption operation failed', options) {\n super(message, options);\n }\n}\nexport class JWEInvalid extends JOSEError {\n static code = 'ERR_JWE_INVALID';\n code = 'ERR_JWE_INVALID';\n}\nexport class JWSInvalid extends JOSEError {\n static code = 'ERR_JWS_INVALID';\n code = 'ERR_JWS_INVALID';\n}\nexport class JWTInvalid extends JOSEError {\n static code = 'ERR_JWT_INVALID';\n code = 'ERR_JWT_INVALID';\n}\nexport class JWKInvalid extends JOSEError {\n static code = 'ERR_JWK_INVALID';\n code = 'ERR_JWK_INVALID';\n}\nexport class JWKSInvalid extends JOSEError {\n static code = 'ERR_JWKS_INVALID';\n code = 'ERR_JWKS_INVALID';\n}\nexport class JWKSNoMatchingKey extends JOSEError {\n static code = 'ERR_JWKS_NO_MATCHING_KEY';\n code = 'ERR_JWKS_NO_MATCHING_KEY';\n constructor(message = 'no applicable key found in the JSON Web Key Set', options) {\n super(message, options);\n }\n}\nexport class JWKSMultipleMatchingKeys extends JOSEError {\n [Symbol.asyncIterator];\n static code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';\n code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';\n constructor(message = 'multiple matching keys found in the JSON Web Key Set', options) {\n super(message, options);\n }\n}\nexport class JWKSTimeout extends JOSEError {\n static code = 'ERR_JWKS_TIMEOUT';\n code = 'ERR_JWKS_TIMEOUT';\n constructor(message = 'request timed out', options) {\n super(message, options);\n }\n}\nexport class JWSSignatureVerificationFailed extends JOSEError {\n static code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';\n code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';\n constructor(message = 'signature verification failed', options) {\n super(message, options);\n }\n}\n","const unusable = (name, prop = 'algorithm.name') => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);\nconst isAlgorithm = (algorithm, name) => algorithm.name === name;\nfunction getHashLength(hash) {\n return parseInt(hash.name.slice(4), 10);\n}\nfunction getNamedCurve(alg) {\n switch (alg) {\n case 'ES256':\n return 'P-256';\n case 'ES384':\n return 'P-384';\n case 'ES512':\n return 'P-521';\n default:\n throw new Error('unreachable');\n }\n}\nfunction checkUsage(key, usage) {\n if (usage && !key.usages.includes(usage)) {\n throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);\n }\n}\nexport function checkSigCryptoKey(key, alg, usage) {\n switch (alg) {\n case 'HS256':\n case 'HS384':\n case 'HS512': {\n if (!isAlgorithm(key.algorithm, 'HMAC'))\n throw unusable('HMAC');\n const expected = parseInt(alg.slice(2), 10);\n const actual = getHashLength(key.algorithm.hash);\n if (actual !== expected)\n throw unusable(`SHA-${expected}`, 'algorithm.hash');\n break;\n }\n case 'RS256':\n case 'RS384':\n case 'RS512': {\n if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5'))\n throw unusable('RSASSA-PKCS1-v1_5');\n const expected = parseInt(alg.slice(2), 10);\n const actual = getHashLength(key.algorithm.hash);\n if (actual !== expected)\n throw unusable(`SHA-${expected}`, 'algorithm.hash');\n break;\n }\n case 'PS256':\n case 'PS384':\n case 'PS512': {\n if (!isAlgorithm(key.algorithm, 'RSA-PSS'))\n throw unusable('RSA-PSS');\n const expected = parseInt(alg.slice(2), 10);\n const actual = getHashLength(key.algorithm.hash);\n if (actual !== expected)\n throw unusable(`SHA-${expected}`, 'algorithm.hash');\n break;\n }\n case 'Ed25519':\n case 'EdDSA': {\n if (!isAlgorithm(key.algorithm, 'Ed25519'))\n throw unusable('Ed25519');\n break;\n }\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87': {\n if (!isAlgorithm(key.algorithm, alg))\n throw unusable(alg);\n break;\n }\n case 'ES256':\n case 'ES384':\n case 'ES512': {\n if (!isAlgorithm(key.algorithm, 'ECDSA'))\n throw unusable('ECDSA');\n const expected = getNamedCurve(alg);\n const actual = key.algorithm.namedCurve;\n if (actual !== expected)\n throw unusable(expected, 'algorithm.namedCurve');\n break;\n }\n default:\n throw new TypeError('CryptoKey does not support this operation');\n }\n checkUsage(key, usage);\n}\nexport function checkEncCryptoKey(key, alg, usage) {\n switch (alg) {\n case 'A128GCM':\n case 'A192GCM':\n case 'A256GCM': {\n if (!isAlgorithm(key.algorithm, 'AES-GCM'))\n throw unusable('AES-GCM');\n const expected = parseInt(alg.slice(1, 4), 10);\n const actual = key.algorithm.length;\n if (actual !== expected)\n throw unusable(expected, 'algorithm.length');\n break;\n }\n case 'A128KW':\n case 'A192KW':\n case 'A256KW': {\n if (!isAlgorithm(key.algorithm, 'AES-KW'))\n throw unusable('AES-KW');\n const expected = parseInt(alg.slice(1, 4), 10);\n const actual = key.algorithm.length;\n if (actual !== expected)\n throw unusable(expected, 'algorithm.length');\n break;\n }\n case 'ECDH': {\n switch (key.algorithm.name) {\n case 'ECDH':\n case 'X25519':\n break;\n default:\n throw unusable('ECDH or X25519');\n }\n break;\n }\n case 'PBES2-HS256+A128KW':\n case 'PBES2-HS384+A192KW':\n case 'PBES2-HS512+A256KW':\n if (!isAlgorithm(key.algorithm, 'PBKDF2'))\n throw unusable('PBKDF2');\n break;\n case 'RSA-OAEP':\n case 'RSA-OAEP-256':\n case 'RSA-OAEP-384':\n case 'RSA-OAEP-512': {\n if (!isAlgorithm(key.algorithm, 'RSA-OAEP'))\n throw unusable('RSA-OAEP');\n const expected = parseInt(alg.slice(9), 10) || 1;\n const actual = getHashLength(key.algorithm.hash);\n if (actual !== expected)\n throw unusable(`SHA-${expected}`, 'algorithm.hash');\n break;\n }\n default:\n throw new TypeError('CryptoKey does not support this operation');\n }\n checkUsage(key, usage);\n}\n","function message(msg, actual, ...types) {\n types = types.filter(Boolean);\n if (types.length > 2) {\n const last = types.pop();\n msg += `one of type ${types.join(', ')}, or ${last}.`;\n }\n else if (types.length === 2) {\n msg += `one of type ${types[0]} or ${types[1]}.`;\n }\n else {\n msg += `of type ${types[0]}.`;\n }\n if (actual == null) {\n msg += ` Received ${actual}`;\n }\n else if (typeof actual === 'function' && actual.name) {\n msg += ` Received function ${actual.name}`;\n }\n else if (typeof actual === 'object' && actual != null) {\n if (actual.constructor?.name) {\n msg += ` Received an instance of ${actual.constructor.name}`;\n }\n }\n return msg;\n}\nexport const invalidKeyInput = (actual, ...types) => message('Key must be ', actual, ...types);\nexport const withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);\n","export function assertCryptoKey(key) {\n if (!isCryptoKey(key)) {\n throw new Error('CryptoKey instance expected');\n }\n}\nexport const isCryptoKey = (key) => {\n if (key?.[Symbol.toStringTag] === 'CryptoKey')\n return true;\n try {\n return key instanceof CryptoKey;\n }\n catch {\n return false;\n }\n};\nexport const isKeyObject = (key) => key?.[Symbol.toStringTag] === 'KeyObject';\nexport const isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);\n","export function isDisjoint(...headers) {\n const sources = headers.filter(Boolean);\n if (sources.length === 0 || sources.length === 1) {\n return true;\n }\n let acc;\n for (const header of sources) {\n const parameters = Object.keys(header);\n if (!acc || acc.size === 0) {\n acc = new Set(parameters);\n continue;\n }\n for (const parameter of parameters) {\n if (acc.has(parameter)) {\n return false;\n }\n acc.add(parameter);\n }\n }\n return true;\n}\n","const isObjectLike = (value) => typeof value === 'object' && value !== null;\nexport function isObject(input) {\n if (!isObjectLike(input) || Object.prototype.toString.call(input) !== '[object Object]') {\n return false;\n }\n if (Object.getPrototypeOf(input) === null) {\n return true;\n }\n let proto = input;\n while (Object.getPrototypeOf(proto) !== null) {\n proto = Object.getPrototypeOf(proto);\n }\n return Object.getPrototypeOf(input) === proto;\n}\n","export function checkKeyLength(alg, key) {\n if (alg.startsWith('RS') || alg.startsWith('PS')) {\n const { modulusLength } = key.algorithm;\n if (typeof modulusLength !== 'number' || modulusLength < 2048) {\n throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);\n }\n }\n}\n","import { invalidKeyInput } from './invalid_key_input.js';\nimport { encodeBase64, decodeBase64 } from '../lib/base64.js';\nimport { JOSENotSupported } from '../util/errors.js';\nimport { isCryptoKey, isKeyObject } from './is_key_like.js';\nconst formatPEM = (b64, descriptor) => {\n const newlined = (b64.match(/.{1,64}/g) || []).join('\\n');\n return `-----BEGIN ${descriptor}-----\\n${newlined}\\n-----END ${descriptor}-----`;\n};\nconst genericExport = async (keyType, keyFormat, key) => {\n if (isKeyObject(key)) {\n if (key.type !== keyType) {\n throw new TypeError(`key is not a ${keyType} key`);\n }\n return key.export({ format: 'pem', type: keyFormat });\n }\n if (!isCryptoKey(key)) {\n throw new TypeError(invalidKeyInput(key, 'CryptoKey', 'KeyObject'));\n }\n if (!key.extractable) {\n throw new TypeError('CryptoKey is not extractable');\n }\n if (key.type !== keyType) {\n throw new TypeError(`key is not a ${keyType} key`);\n }\n return formatPEM(encodeBase64(new Uint8Array(await crypto.subtle.exportKey(keyFormat, key))), `${keyType.toUpperCase()} KEY`);\n};\nexport const toSPKI = (key) => genericExport('public', 'spki', key);\nexport const toPKCS8 = (key) => genericExport('private', 'pkcs8', key);\nconst bytesEqual = (a, b) => {\n if (a.byteLength !== b.length)\n return false;\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i])\n return false;\n }\n return true;\n};\nconst createASN1State = (data) => ({ data, pos: 0 });\nconst parseLength = (state) => {\n const first = state.data[state.pos++];\n if (first & 0x80) {\n const lengthOfLen = first & 0x7f;\n let length = 0;\n for (let i = 0; i < lengthOfLen; i++) {\n length = (length << 8) | state.data[state.pos++];\n }\n return length;\n }\n return first;\n};\nconst skipElement = (state, count = 1) => {\n if (count <= 0)\n return;\n state.pos++;\n const length = parseLength(state);\n state.pos += length;\n if (count > 1) {\n skipElement(state, count - 1);\n }\n};\nconst expectTag = (state, expectedTag, errorMessage) => {\n if (state.data[state.pos++] !== expectedTag) {\n throw new Error(errorMessage);\n }\n};\nconst getSubarray = (state, length) => {\n const result = state.data.subarray(state.pos, state.pos + length);\n state.pos += length;\n return result;\n};\nconst parseAlgorithmOID = (state) => {\n expectTag(state, 0x06, 'Expected algorithm OID');\n const oidLen = parseLength(state);\n return getSubarray(state, oidLen);\n};\nfunction parsePKCS8Header(state) {\n expectTag(state, 0x30, 'Invalid PKCS#8 structure');\n parseLength(state);\n expectTag(state, 0x02, 'Expected version field');\n const verLen = parseLength(state);\n state.pos += verLen;\n expectTag(state, 0x30, 'Expected algorithm identifier');\n const algIdLen = parseLength(state);\n const algIdStart = state.pos;\n return { algIdStart, algIdLength: algIdLen };\n}\nfunction parseSPKIHeader(state) {\n expectTag(state, 0x30, 'Invalid SPKI structure');\n parseLength(state);\n expectTag(state, 0x30, 'Expected algorithm identifier');\n const algIdLen = parseLength(state);\n const algIdStart = state.pos;\n return { algIdStart, algIdLength: algIdLen };\n}\nconst parseECAlgorithmIdentifier = (state) => {\n const algOid = parseAlgorithmOID(state);\n if (bytesEqual(algOid, [0x2b, 0x65, 0x6e])) {\n return 'X25519';\n }\n if (!bytesEqual(algOid, [0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01])) {\n throw new Error('Unsupported key algorithm');\n }\n expectTag(state, 0x06, 'Expected curve OID');\n const curveOidLen = parseLength(state);\n const curveOid = getSubarray(state, curveOidLen);\n for (const { name, oid } of [\n { name: 'P-256', oid: [0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07] },\n { name: 'P-384', oid: [0x2b, 0x81, 0x04, 0x00, 0x22] },\n { name: 'P-521', oid: [0x2b, 0x81, 0x04, 0x00, 0x23] },\n ]) {\n if (bytesEqual(curveOid, oid)) {\n return name;\n }\n }\n throw new Error('Unsupported named curve');\n};\nconst genericImport = async (keyFormat, keyData, alg, options) => {\n let algorithm;\n let keyUsages;\n const isPublic = keyFormat === 'spki';\n const getSigUsages = () => (isPublic ? ['verify'] : ['sign']);\n const getEncUsages = () => isPublic ? ['encrypt', 'wrapKey'] : ['decrypt', 'unwrapKey'];\n switch (alg) {\n case 'PS256':\n case 'PS384':\n case 'PS512':\n algorithm = { name: 'RSA-PSS', hash: `SHA-${alg.slice(-3)}` };\n keyUsages = getSigUsages();\n break;\n case 'RS256':\n case 'RS384':\n case 'RS512':\n algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${alg.slice(-3)}` };\n keyUsages = getSigUsages();\n break;\n case 'RSA-OAEP':\n case 'RSA-OAEP-256':\n case 'RSA-OAEP-384':\n case 'RSA-OAEP-512':\n algorithm = {\n name: 'RSA-OAEP',\n hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`,\n };\n keyUsages = getEncUsages();\n break;\n case 'ES256':\n case 'ES384':\n case 'ES512': {\n const curveMap = { ES256: 'P-256', ES384: 'P-384', ES512: 'P-521' };\n algorithm = { name: 'ECDSA', namedCurve: curveMap[alg] };\n keyUsages = getSigUsages();\n break;\n }\n case 'ECDH-ES':\n case 'ECDH-ES+A128KW':\n case 'ECDH-ES+A192KW':\n case 'ECDH-ES+A256KW': {\n try {\n const namedCurve = options.getNamedCurve(keyData);\n algorithm = namedCurve === 'X25519' ? { name: 'X25519' } : { name: 'ECDH', namedCurve };\n }\n catch (cause) {\n throw new JOSENotSupported('Invalid or unsupported key format');\n }\n keyUsages = isPublic ? [] : ['deriveBits'];\n break;\n }\n case 'Ed25519':\n case 'EdDSA':\n algorithm = { name: 'Ed25519' };\n keyUsages = getSigUsages();\n break;\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n algorithm = { name: alg };\n keyUsages = getSigUsages();\n break;\n default:\n throw new JOSENotSupported('Invalid or unsupported \"alg\" (Algorithm) value');\n }\n return crypto.subtle.importKey(keyFormat, keyData, algorithm, options?.extractable ?? (isPublic ? true : false), keyUsages);\n};\nconst processPEMData = (pem, pattern) => {\n return decodeBase64(pem.replace(pattern, ''));\n};\nexport const fromPKCS8 = (pem, alg, options) => {\n const keyData = processPEMData(pem, /(?:-----(?:BEGIN|END) PRIVATE KEY-----|\\s)/g);\n let opts = options;\n if (alg?.startsWith?.('ECDH-ES')) {\n opts ||= {};\n opts.getNamedCurve = (keyData) => {\n const state = createASN1State(keyData);\n parsePKCS8Header(state);\n return parseECAlgorithmIdentifier(state);\n };\n }\n return genericImport('pkcs8', keyData, alg, opts);\n};\nexport const fromSPKI = (pem, alg, options) => {\n const keyData = processPEMData(pem, /(?:-----(?:BEGIN|END) PUBLIC KEY-----|\\s)/g);\n let opts = options;\n if (alg?.startsWith?.('ECDH-ES')) {\n opts ||= {};\n opts.getNamedCurve = (keyData) => {\n const state = createASN1State(keyData);\n parseSPKIHeader(state);\n return parseECAlgorithmIdentifier(state);\n };\n }\n return genericImport('spki', keyData, alg, opts);\n};\nfunction spkiFromX509(buf) {\n const state = createASN1State(buf);\n expectTag(state, 0x30, 'Invalid certificate structure');\n parseLength(state);\n expectTag(state, 0x30, 'Invalid tbsCertificate structure');\n parseLength(state);\n if (buf[state.pos] === 0xa0) {\n skipElement(state, 6);\n }\n else {\n skipElement(state, 5);\n }\n const spkiStart = state.pos;\n expectTag(state, 0x30, 'Invalid SPKI structure');\n const spkiContentLen = parseLength(state);\n return buf.subarray(spkiStart, spkiStart + spkiContentLen + (state.pos - spkiStart));\n}\nfunction extractX509SPKI(x509) {\n const derBytes = processPEMData(x509, /(?:-----(?:BEGIN|END) CERTIFICATE-----|\\s)/g);\n return spkiFromX509(derBytes);\n}\nexport const fromX509 = (pem, alg, options) => {\n let spki;\n try {\n spki = extractX509SPKI(pem);\n }\n catch (cause) {\n throw new TypeError('Failed to parse the X.509 certificate', { cause });\n }\n return fromSPKI(formatPEM(encodeBase64(spki), 'PUBLIC KEY'), alg, options);\n};\n","import { JOSENotSupported } from '../util/errors.js';\nfunction subtleMapping(jwk) {\n let algorithm;\n let keyUsages;\n switch (jwk.kty) {\n case 'AKP': {\n switch (jwk.alg) {\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n algorithm = { name: jwk.alg };\n keyUsages = jwk.priv ? ['sign'] : ['verify'];\n break;\n default:\n throw new JOSENotSupported('Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value');\n }\n break;\n }\n case 'RSA': {\n switch (jwk.alg) {\n case 'PS256':\n case 'PS384':\n case 'PS512':\n algorithm = { name: 'RSA-PSS', hash: `SHA-${jwk.alg.slice(-3)}` };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'RS256':\n case 'RS384':\n case 'RS512':\n algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${jwk.alg.slice(-3)}` };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'RSA-OAEP':\n case 'RSA-OAEP-256':\n case 'RSA-OAEP-384':\n case 'RSA-OAEP-512':\n algorithm = {\n name: 'RSA-OAEP',\n hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`,\n };\n keyUsages = jwk.d ? ['decrypt', 'unwrapKey'] : ['encrypt', 'wrapKey'];\n break;\n default:\n throw new JOSENotSupported('Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value');\n }\n break;\n }\n case 'EC': {\n switch (jwk.alg) {\n case 'ES256':\n algorithm = { name: 'ECDSA', namedCurve: 'P-256' };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'ES384':\n algorithm = { name: 'ECDSA', namedCurve: 'P-384' };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'ES512':\n algorithm = { name: 'ECDSA', namedCurve: 'P-521' };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'ECDH-ES':\n case 'ECDH-ES+A128KW':\n case 'ECDH-ES+A192KW':\n case 'ECDH-ES+A256KW':\n algorithm = { name: 'ECDH', namedCurve: jwk.crv };\n keyUsages = jwk.d ? ['deriveBits'] : [];\n break;\n default:\n throw new JOSENotSupported('Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value');\n }\n break;\n }\n case 'OKP': {\n switch (jwk.alg) {\n case 'Ed25519':\n case 'EdDSA':\n algorithm = { name: 'Ed25519' };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'ECDH-ES':\n case 'ECDH-ES+A128KW':\n case 'ECDH-ES+A192KW':\n case 'ECDH-ES+A256KW':\n algorithm = { name: jwk.crv };\n keyUsages = jwk.d ? ['deriveBits'] : [];\n break;\n default:\n throw new JOSENotSupported('Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value');\n }\n break;\n }\n default:\n throw new JOSENotSupported('Invalid or unsupported JWK \"kty\" (Key Type) Parameter value');\n }\n return { algorithm, keyUsages };\n}\nexport async function jwkToKey(jwk) {\n if (!jwk.alg) {\n throw new TypeError('\"alg\" argument is required when \"jwk.alg\" is not present');\n }\n const { algorithm, keyUsages } = subtleMapping(jwk);\n const keyData = { ...jwk };\n if (keyData.kty !== 'AKP') {\n delete keyData.alg;\n }\n delete keyData.use;\n return crypto.subtle.importKey('jwk', keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages);\n}\n","import { decode as decodeBase64URL } from '../util/base64url.js';\nimport { fromSPKI, fromPKCS8, fromX509 } from '../lib/asn1.js';\nimport { jwkToKey } from '../lib/jwk_to_key.js';\nimport { JOSENotSupported } from '../util/errors.js';\nimport { isObject } from '../lib/is_object.js';\nexport async function importSPKI(spki, alg, options) {\n if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) {\n throw new TypeError('\"spki\" must be SPKI formatted string');\n }\n return fromSPKI(spki, alg, options);\n}\nexport async function importX509(x509, alg, options) {\n if (typeof x509 !== 'string' || x509.indexOf('-----BEGIN CERTIFICATE-----') !== 0) {\n throw new TypeError('\"x509\" must be X.509 formatted string');\n }\n return fromX509(x509, alg, options);\n}\nexport async function importPKCS8(pkcs8, alg, options) {\n if (typeof pkcs8 !== 'string' || pkcs8.indexOf('-----BEGIN PRIVATE KEY-----') !== 0) {\n throw new TypeError('\"pkcs8\" must be PKCS#8 formatted string');\n }\n return fromPKCS8(pkcs8, alg, options);\n}\nexport async function importJWK(jwk, alg, options) {\n if (!isObject(jwk)) {\n throw new TypeError('JWK must be an object');\n }\n let ext;\n alg ??= jwk.alg;\n ext ??= options?.extractable ?? jwk.ext;\n switch (jwk.kty) {\n case 'oct':\n if (typeof jwk.k !== 'string' || !jwk.k) {\n throw new TypeError('missing \"k\" (Key Value) Parameter value');\n }\n return decodeBase64URL(jwk.k);\n case 'RSA':\n if ('oth' in jwk && jwk.oth !== undefined) {\n throw new JOSENotSupported('RSA JWK \"oth\" (Other Primes Info) Parameter value is not supported');\n }\n return jwkToKey({ ...jwk, alg, ext });\n case 'AKP': {\n if (typeof jwk.alg !== 'string' || !jwk.alg) {\n throw new TypeError('missing \"alg\" (Algorithm) Parameter value');\n }\n if (alg !== undefined && alg !== jwk.alg) {\n throw new TypeError('JWK alg and alg option value mismatch');\n }\n return jwkToKey({ ...jwk, ext });\n }\n case 'EC':\n case 'OKP':\n return jwkToKey({ ...jwk, alg, ext });\n default:\n throw new JOSENotSupported('Unsupported \"kty\" (Key Type) Parameter value');\n }\n}\n","import { JOSENotSupported, JWEInvalid, JWSInvalid } from '../util/errors.js';\nexport function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {\n if (joseHeader.crit !== undefined && protectedHeader?.crit === undefined) {\n throw new Err('\"crit\" (Critical) Header Parameter MUST be integrity protected');\n }\n if (!protectedHeader || protectedHeader.crit === undefined) {\n return new Set();\n }\n if (!Array.isArray(protectedHeader.crit) ||\n protectedHeader.crit.length === 0 ||\n protectedHeader.crit.some((input) => typeof input !== 'string' || input.length === 0)) {\n throw new Err('\"crit\" (Critical) Header Parameter MUST be an array of non-empty strings when present');\n }\n let recognized;\n if (recognizedOption !== undefined) {\n recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);\n }\n else {\n recognized = recognizedDefault;\n }\n for (const parameter of protectedHeader.crit) {\n if (!recognized.has(parameter)) {\n throw new JOSENotSupported(`Extension Header Parameter \"${parameter}\" is not recognized`);\n }\n if (joseHeader[parameter] === undefined) {\n throw new Err(`Extension Header Parameter \"${parameter}\" is missing`);\n }\n if (recognized.get(parameter) && protectedHeader[parameter] === undefined) {\n throw new Err(`Extension Header Parameter \"${parameter}\" MUST be integrity protected`);\n }\n }\n return new Set(protectedHeader.crit);\n}\n","export function validateAlgorithms(option, algorithms) {\n if (algorithms !== undefined &&\n (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== 'string'))) {\n throw new TypeError(`\"${option}\" option must be an array of strings`);\n }\n if (!algorithms) {\n return undefined;\n }\n return new Set(algorithms);\n}\n","import { isObject } from './is_object.js';\nexport const isJWK = (key) => isObject(key) && typeof key.kty === 'string';\nexport const isPrivateJWK = (key) => key.kty !== 'oct' &&\n ((key.kty === 'AKP' && typeof key.priv === 'string') || typeof key.d === 'string');\nexport const isPublicJWK = (key) => key.kty !== 'oct' && key.d === undefined && key.priv === undefined;\nexport const isSecretJWK = (key) => key.kty === 'oct' && typeof key.k === 'string';\n","import { isJWK } from './is_jwk.js';\nimport { decode } from '../util/base64url.js';\nimport { jwkToKey } from './jwk_to_key.js';\nimport { isCryptoKey, isKeyObject } from './is_key_like.js';\nlet cache;\nconst handleJWK = async (key, jwk, alg, freeze = false) => {\n cache ||= new WeakMap();\n let cached = cache.get(key);\n if (cached?.[alg]) {\n return cached[alg];\n }\n const cryptoKey = await jwkToKey({ ...jwk, alg });\n if (freeze)\n Object.freeze(key);\n if (!cached) {\n cache.set(key, { [alg]: cryptoKey });\n }\n else {\n cached[alg] = cryptoKey;\n }\n return cryptoKey;\n};\nconst handleKeyObject = (keyObject, alg) => {\n cache ||= new WeakMap();\n let cached = cache.get(keyObject);\n if (cached?.[alg]) {\n return cached[alg];\n }\n const isPublic = keyObject.type === 'public';\n const extractable = isPublic ? true : false;\n let cryptoKey;\n if (keyObject.asymmetricKeyType === 'x25519') {\n switch (alg) {\n case 'ECDH-ES':\n case 'ECDH-ES+A128KW':\n case 'ECDH-ES+A192KW':\n case 'ECDH-ES+A256KW':\n break;\n default:\n throw new TypeError('given KeyObject instance cannot be used for this algorithm');\n }\n cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ['deriveBits']);\n }\n if (keyObject.asymmetricKeyType === 'ed25519') {\n if (alg !== 'EdDSA' && alg !== 'Ed25519') {\n throw new TypeError('given KeyObject instance cannot be used for this algorithm');\n }\n cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [\n isPublic ? 'verify' : 'sign',\n ]);\n }\n switch (keyObject.asymmetricKeyType) {\n case 'ml-dsa-44':\n case 'ml-dsa-65':\n case 'ml-dsa-87': {\n if (alg !== keyObject.asymmetricKeyType.toUpperCase()) {\n throw new TypeError('given KeyObject instance cannot be used for this algorithm');\n }\n cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [\n isPublic ? 'verify' : 'sign',\n ]);\n }\n }\n if (keyObject.asymmetricKeyType === 'rsa') {\n let hash;\n switch (alg) {\n case 'RSA-OAEP':\n hash = 'SHA-1';\n break;\n case 'RS256':\n case 'PS256':\n case 'RSA-OAEP-256':\n hash = 'SHA-256';\n break;\n case 'RS384':\n case 'PS384':\n case 'RSA-OAEP-384':\n hash = 'SHA-384';\n break;\n case 'RS512':\n case 'PS512':\n case 'RSA-OAEP-512':\n hash = 'SHA-512';\n break;\n default:\n throw new TypeError('given KeyObject instance cannot be used for this algorithm');\n }\n if (alg.startsWith('RSA-OAEP')) {\n return keyObject.toCryptoKey({\n name: 'RSA-OAEP',\n hash,\n }, extractable, isPublic ? ['encrypt'] : ['decrypt']);\n }\n cryptoKey = keyObject.toCryptoKey({\n name: alg.startsWith('PS') ? 'RSA-PSS' : 'RSASSA-PKCS1-v1_5',\n hash,\n }, extractable, [isPublic ? 'verify' : 'sign']);\n }\n if (keyObject.asymmetricKeyType === 'ec') {\n const nist = new Map([\n ['prime256v1', 'P-256'],\n ['secp384r1', 'P-384'],\n ['secp521r1', 'P-521'],\n ]);\n const namedCurve = nist.get(keyObject.asymmetricKeyDetails?.namedCurve);\n if (!namedCurve) {\n throw new TypeError('given KeyObject instance cannot be used for this algorithm');\n }\n if (alg === 'ES256' && namedCurve === 'P-256') {\n cryptoKey = keyObject.toCryptoKey({\n name: 'ECDSA',\n namedCurve,\n }, extractable, [isPublic ? 'verify' : 'sign']);\n }\n if (alg === 'ES384' && namedCurve === 'P-384') {\n cryptoKey = keyObject.toCryptoKey({\n name: 'ECDSA',\n namedCurve,\n }, extractable, [isPublic ? 'verify' : 'sign']);\n }\n if (alg === 'ES512' && namedCurve === 'P-521') {\n cryptoKey = keyObject.toCryptoKey({\n name: 'ECDSA',\n namedCurve,\n }, extractable, [isPublic ? 'verify' : 'sign']);\n }\n if (alg.startsWith('ECDH-ES')) {\n cryptoKey = keyObject.toCryptoKey({\n name: 'ECDH',\n namedCurve,\n }, extractable, isPublic ? [] : ['deriveBits']);\n }\n }\n if (!cryptoKey) {\n throw new TypeError('given KeyObject instance cannot be used for this algorithm');\n }\n if (!cached) {\n cache.set(keyObject, { [alg]: cryptoKey });\n }\n else {\n cached[alg] = cryptoKey;\n }\n return cryptoKey;\n};\nexport async function normalizeKey(key, alg) {\n if (key instanceof Uint8Array) {\n return key;\n }\n if (isCryptoKey(key)) {\n return key;\n }\n if (isKeyObject(key)) {\n if (key.type === 'secret') {\n return key.export();\n }\n if ('toCryptoKey' in key && typeof key.toCryptoKey === 'function') {\n try {\n return handleKeyObject(key, alg);\n }\n catch (err) {\n if (err instanceof TypeError) {\n throw err;\n }\n }\n }\n let jwk = key.export({ format: 'jwk' });\n return handleJWK(key, jwk, alg);\n }\n if (isJWK(key)) {\n if (key.k) {\n return decode(key.k);\n }\n return handleJWK(key, key, alg, true);\n }\n throw new Error('unreachable');\n}\n","import { withAlg as invalidKeyInput } from './invalid_key_input.js';\nimport { isKeyLike } from './is_key_like.js';\nimport * as jwk from './is_jwk.js';\nconst tag = (key) => key?.[Symbol.toStringTag];\nconst jwkMatchesOp = (alg, key, usage) => {\n if (key.use !== undefined) {\n let expected;\n switch (usage) {\n case 'sign':\n case 'verify':\n expected = 'sig';\n break;\n case 'encrypt':\n case 'decrypt':\n expected = 'enc';\n break;\n }\n if (key.use !== expected) {\n throw new TypeError(`Invalid key for this operation, its \"use\" must be \"${expected}\" when present`);\n }\n }\n if (key.alg !== undefined && key.alg !== alg) {\n throw new TypeError(`Invalid key for this operation, its \"alg\" must be \"${alg}\" when present`);\n }\n if (Array.isArray(key.key_ops)) {\n let expectedKeyOp;\n switch (true) {\n case usage === 'sign' || usage === 'verify':\n case alg === 'dir':\n case alg.includes('CBC-HS'):\n expectedKeyOp = usage;\n break;\n case alg.startsWith('PBES2'):\n expectedKeyOp = 'deriveBits';\n break;\n case /^A\\d{3}(?:GCM)?(?:KW)?$/.test(alg):\n if (!alg.includes('GCM') && alg.endsWith('KW')) {\n expectedKeyOp = usage === 'encrypt' ? 'wrapKey' : 'unwrapKey';\n }\n else {\n expectedKeyOp = usage;\n }\n break;\n case usage === 'encrypt' && alg.startsWith('RSA'):\n expectedKeyOp = 'wrapKey';\n break;\n case usage === 'decrypt':\n expectedKeyOp = alg.startsWith('RSA') ? 'unwrapKey' : 'deriveBits';\n break;\n }\n if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) {\n throw new TypeError(`Invalid key for this operation, its \"key_ops\" must include \"${expectedKeyOp}\" when present`);\n }\n }\n return true;\n};\nconst symmetricTypeCheck = (alg, key, usage) => {\n if (key instanceof Uint8Array)\n return;\n if (jwk.isJWK(key)) {\n if (jwk.isSecretJWK(key) && jwkMatchesOp(alg, key, usage))\n return;\n throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK \"kty\" (Key Type) equal to \"oct\" and the JWK \"k\" (Key Value) present`);\n }\n if (!isKeyLike(key)) {\n throw new TypeError(invalidKeyInput(alg, key, 'CryptoKey', 'KeyObject', 'JSON Web Key', 'Uint8Array'));\n }\n if (key.type !== 'secret') {\n throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type \"secret\"`);\n }\n};\nconst asymmetricTypeCheck = (alg, key, usage) => {\n if (jwk.isJWK(key)) {\n switch (usage) {\n case 'decrypt':\n case 'sign':\n if (jwk.isPrivateJWK(key) && jwkMatchesOp(alg, key, usage))\n return;\n throw new TypeError(`JSON Web Key for this operation must be a private JWK`);\n case 'encrypt':\n case 'verify':\n if (jwk.isPublicJWK(key) && jwkMatchesOp(alg, key, usage))\n return;\n throw new TypeError(`JSON Web Key for this operation must be a public JWK`);\n }\n }\n if (!isKeyLike(key)) {\n throw new TypeError(invalidKeyInput(alg, key, 'CryptoKey', 'KeyObject', 'JSON Web Key'));\n }\n if (key.type === 'secret') {\n throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type \"secret\"`);\n }\n if (key.type === 'public') {\n switch (usage) {\n case 'sign':\n throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type \"private\"`);\n case 'decrypt':\n throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type \"private\"`);\n }\n }\n if (key.type === 'private') {\n switch (usage) {\n case 'verify':\n throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type \"public\"`);\n case 'encrypt':\n throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type \"public\"`);\n }\n }\n};\nexport function checkKeyType(alg, key, usage) {\n switch (alg.substring(0, 2)) {\n case 'A1':\n case 'A2':\n case 'di':\n case 'HS':\n case 'PB':\n symmetricTypeCheck(alg, key, usage);\n break;\n default:\n asymmetricTypeCheck(alg, key, usage);\n }\n}\n",null,"import { JOSENotSupported } from '../util/errors.js';\nexport function subtleAlgorithm(alg, algorithm) {\n const hash = `SHA-${alg.slice(-3)}`;\n switch (alg) {\n case 'HS256':\n case 'HS384':\n case 'HS512':\n return { hash, name: 'HMAC' };\n case 'PS256':\n case 'PS384':\n case 'PS512':\n return { hash, name: 'RSA-PSS', saltLength: parseInt(alg.slice(-3), 10) >> 3 };\n case 'RS256':\n case 'RS384':\n case 'RS512':\n return { hash, name: 'RSASSA-PKCS1-v1_5' };\n case 'ES256':\n case 'ES384':\n case 'ES512':\n return { hash, name: 'ECDSA', namedCurve: algorithm.namedCurve };\n case 'Ed25519':\n case 'EdDSA':\n return { name: 'Ed25519' };\n case 'ML-DSA-44':\n case 'ML-DSA-65':\n case 'ML-DSA-87':\n return { name: alg };\n default:\n throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);\n }\n}\n","import { checkSigCryptoKey } from './crypto_key.js';\nimport { invalidKeyInput } from './invalid_key_input.js';\nexport async function getSigKey(alg, key, usage) {\n if (key instanceof Uint8Array) {\n if (!alg.startsWith('HS')) {\n throw new TypeError(invalidKeyInput(key, 'CryptoKey', 'KeyObject', 'JSON Web Key'));\n }\n return crypto.subtle.importKey('raw', key, { hash: `SHA-${alg.slice(-3)}`, name: 'HMAC' }, false, [usage]);\n }\n checkSigCryptoKey(key, alg, usage);\n return key;\n}\n","import { subtleAlgorithm } from './subtle_dsa.js';\nimport { checkKeyLength } from './check_key_length.js';\nimport { getSigKey } from './get_sign_verify_key.js';\nexport async function verify(alg, key, signature, data) {\n const cryptoKey = await getSigKey(alg, key, 'verify');\n checkKeyLength(alg, cryptoKey);\n const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm);\n try {\n return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);\n }\n catch {\n return false;\n }\n}\n","import { decode as b64u } from '../../util/base64url.js';\nimport { verify } from '../../lib/verify.js';\nimport { JOSEAlgNotAllowed, JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js';\nimport { concat, encoder, decoder, encode } from '../../lib/buffer_utils.js';\nimport { isDisjoint } from '../../lib/is_disjoint.js';\nimport { isObject } from '../../lib/is_object.js';\nimport { checkKeyType } from '../../lib/check_key_type.js';\nimport { validateCrit } from '../../lib/validate_crit.js';\nimport { validateAlgorithms } from '../../lib/validate_algorithms.js';\nimport { normalizeKey } from '../../lib/normalize_key.js';\nexport async function flattenedVerify(jws, key, options) {\n if (!isObject(jws)) {\n throw new JWSInvalid('Flattened JWS must be an object');\n }\n if (jws.protected === undefined && jws.header === undefined) {\n throw new JWSInvalid('Flattened JWS must have either of the \"protected\" or \"header\" members');\n }\n if (jws.protected !== undefined && typeof jws.protected !== 'string') {\n throw new JWSInvalid('JWS Protected Header incorrect type');\n }\n if (jws.payload === undefined) {\n throw new JWSInvalid('JWS Payload missing');\n }\n if (typeof jws.signature !== 'string') {\n throw new JWSInvalid('JWS Signature missing or incorrect type');\n }\n if (jws.header !== undefined && !isObject(jws.header)) {\n throw new JWSInvalid('JWS Unprotected Header incorrect type');\n }\n let parsedProt = {};\n if (jws.protected) {\n try {\n const protectedHeader = b64u(jws.protected);\n parsedProt = JSON.parse(decoder.decode(protectedHeader));\n }\n catch {\n throw new JWSInvalid('JWS Protected Header is invalid');\n }\n }\n if (!isDisjoint(parsedProt, jws.header)) {\n throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint');\n }\n const joseHeader = {\n ...parsedProt,\n ...jws.header,\n };\n const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options?.crit, parsedProt, joseHeader);\n let b64 = true;\n if (extensions.has('b64')) {\n b64 = parsedProt.b64;\n if (typeof b64 !== 'boolean') {\n throw new JWSInvalid('The \"b64\" (base64url-encode payload) Header Parameter must be a boolean');\n }\n }\n const { alg } = joseHeader;\n if (typeof alg !== 'string' || !alg) {\n throw new JWSInvalid('JWS \"alg\" (Algorithm) Header Parameter missing or invalid');\n }\n const algorithms = options && validateAlgorithms('algorithms', options.algorithms);\n if (algorithms && !algorithms.has(alg)) {\n throw new JOSEAlgNotAllowed('\"alg\" (Algorithm) Header Parameter value not allowed');\n }\n if (b64) {\n if (typeof jws.payload !== 'string') {\n throw new JWSInvalid('JWS Payload must be a string');\n }\n }\n else if (typeof jws.payload !== 'string' && !(jws.payload instanceof Uint8Array)) {\n throw new JWSInvalid('JWS Payload must be a string or an Uint8Array instance');\n }\n let resolvedKey = false;\n if (typeof key === 'function') {\n key = await key(parsedProt, jws);\n resolvedKey = true;\n }\n checkKeyType(alg, key, 'verify');\n const data = concat(jws.protected !== undefined ? encode(jws.protected) : new Uint8Array(), encode('.'), typeof jws.payload === 'string'\n ? b64\n ? encode(jws.payload)\n : encoder.encode(jws.payload)\n : jws.payload);\n let signature;\n try {\n signature = b64u(jws.signature);\n }\n catch {\n throw new JWSInvalid('Failed to base64url decode the signature');\n }\n const k = await normalizeKey(key, alg);\n const verified = await verify(alg, k, signature, data);\n if (!verified) {\n throw new JWSSignatureVerificationFailed();\n }\n let payload;\n if (b64) {\n try {\n payload = b64u(jws.payload);\n }\n catch {\n throw new JWSInvalid('Failed to base64url decode the payload');\n }\n }\n else if (typeof jws.payload === 'string') {\n payload = encoder.encode(jws.payload);\n }\n else {\n payload = jws.payload;\n }\n const result = { payload };\n if (jws.protected !== undefined) {\n result.protectedHeader = parsedProt;\n }\n if (jws.header !== undefined) {\n result.unprotectedHeader = jws.header;\n }\n if (resolvedKey) {\n return { ...result, key: k };\n }\n return result;\n}\n","import { flattenedVerify } from '../flattened/verify.js';\nimport { JWSInvalid } from '../../util/errors.js';\nimport { decoder } from '../../lib/buffer_utils.js';\nexport async function compactVerify(jws, key, options) {\n if (jws instanceof Uint8Array) {\n jws = decoder.decode(jws);\n }\n if (typeof jws !== 'string') {\n throw new JWSInvalid('Compact JWS must be a string or Uint8Array');\n }\n const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.');\n if (length !== 3) {\n throw new JWSInvalid('Invalid Compact JWS');\n }\n const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options);\n const result = { payload: verified.payload, protectedHeader: verified.protectedHeader };\n if (typeof key === 'function') {\n return { ...result, key: verified.key };\n }\n return result;\n}\n","import { JWTClaimValidationFailed, JWTExpired, JWTInvalid } from '../util/errors.js';\nimport { encoder, decoder } from './buffer_utils.js';\nimport { isObject } from './is_object.js';\nconst epoch = (date) => Math.floor(date.getTime() / 1000);\nconst minute = 60;\nconst hour = minute * 60;\nconst day = hour * 24;\nconst week = day * 7;\nconst year = day * 365.25;\nconst REGEX = /^(\\+|\\-)? ?(\\d+|\\d+\\.\\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;\nexport function secs(str) {\n const matched = REGEX.exec(str);\n if (!matched || (matched[4] && matched[1])) {\n throw new TypeError('Invalid time period format');\n }\n const value = parseFloat(matched[2]);\n const unit = matched[3].toLowerCase();\n let numericDate;\n switch (unit) {\n case 'sec':\n case 'secs':\n case 'second':\n case 'seconds':\n case 's':\n numericDate = Math.round(value);\n break;\n case 'minute':\n case 'minutes':\n case 'min':\n case 'mins':\n case 'm':\n numericDate = Math.round(value * minute);\n break;\n case 'hour':\n case 'hours':\n case 'hr':\n case 'hrs':\n case 'h':\n numericDate = Math.round(value * hour);\n break;\n case 'day':\n case 'days':\n case 'd':\n numericDate = Math.round(value * day);\n break;\n case 'week':\n case 'weeks':\n case 'w':\n numericDate = Math.round(value * week);\n break;\n default:\n numericDate = Math.round(value * year);\n break;\n }\n if (matched[1] === '-' || matched[4] === 'ago') {\n return -numericDate;\n }\n return numericDate;\n}\nfunction validateInput(label, input) {\n if (!Number.isFinite(input)) {\n throw new TypeError(`Invalid ${label} input`);\n }\n return input;\n}\nconst normalizeTyp = (value) => {\n if (value.includes('/')) {\n return value.toLowerCase();\n }\n return `application/${value.toLowerCase()}`;\n};\nconst checkAudiencePresence = (audPayload, audOption) => {\n if (typeof audPayload === 'string') {\n return audOption.includes(audPayload);\n }\n if (Array.isArray(audPayload)) {\n return audOption.some(Set.prototype.has.bind(new Set(audPayload)));\n }\n return false;\n};\nexport function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {\n let payload;\n try {\n payload = JSON.parse(decoder.decode(encodedPayload));\n }\n catch {\n }\n if (!isObject(payload)) {\n throw new JWTInvalid('JWT Claims Set must be a top-level JSON object');\n }\n const { typ } = options;\n if (typ &&\n (typeof protectedHeader.typ !== 'string' ||\n normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) {\n throw new JWTClaimValidationFailed('unexpected \"typ\" JWT header value', payload, 'typ', 'check_failed');\n }\n const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;\n const presenceCheck = [...requiredClaims];\n if (maxTokenAge !== undefined)\n presenceCheck.push('iat');\n if (audience !== undefined)\n presenceCheck.push('aud');\n if (subject !== undefined)\n presenceCheck.push('sub');\n if (issuer !== undefined)\n presenceCheck.push('iss');\n for (const claim of new Set(presenceCheck.reverse())) {\n if (!(claim in payload)) {\n throw new JWTClaimValidationFailed(`missing required \"${claim}\" claim`, payload, claim, 'missing');\n }\n }\n if (issuer &&\n !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) {\n throw new JWTClaimValidationFailed('unexpected \"iss\" claim value', payload, 'iss', 'check_failed');\n }\n if (subject && payload.sub !== subject) {\n throw new JWTClaimValidationFailed('unexpected \"sub\" claim value', payload, 'sub', 'check_failed');\n }\n if (audience &&\n !checkAudiencePresence(payload.aud, typeof audience === 'string' ? [audience] : audience)) {\n throw new JWTClaimValidationFailed('unexpected \"aud\" claim value', payload, 'aud', 'check_failed');\n }\n let tolerance;\n switch (typeof options.clockTolerance) {\n case 'string':\n tolerance = secs(options.clockTolerance);\n break;\n case 'number':\n tolerance = options.clockTolerance;\n break;\n case 'undefined':\n tolerance = 0;\n break;\n default:\n throw new TypeError('Invalid clockTolerance option type');\n }\n const { currentDate } = options;\n const now = epoch(currentDate || new Date());\n if ((payload.iat !== undefined || maxTokenAge) && typeof payload.iat !== 'number') {\n throw new JWTClaimValidationFailed('\"iat\" claim must be a number', payload, 'iat', 'invalid');\n }\n if (payload.nbf !== undefined) {\n if (typeof payload.nbf !== 'number') {\n throw new JWTClaimValidationFailed('\"nbf\" claim must be a number', payload, 'nbf', 'invalid');\n }\n if (payload.nbf > now + tolerance) {\n throw new JWTClaimValidationFailed('\"nbf\" claim timestamp check failed', payload, 'nbf', 'check_failed');\n }\n }\n if (payload.exp !== undefined) {\n if (typeof payload.exp !== 'number') {\n throw new JWTClaimValidationFailed('\"exp\" claim must be a number', payload, 'exp', 'invalid');\n }\n if (payload.exp <= now - tolerance) {\n throw new JWTExpired('\"exp\" claim timestamp check failed', payload, 'exp', 'check_failed');\n }\n }\n if (maxTokenAge) {\n const age = now - payload.iat;\n const max = typeof maxTokenAge === 'number' ? maxTokenAge : secs(maxTokenAge);\n if (age - tolerance > max) {\n throw new JWTExpired('\"iat\" claim timestamp check failed (too far in the past)', payload, 'iat', 'check_failed');\n }\n if (age < 0 - tolerance) {\n throw new JWTClaimValidationFailed('\"iat\" claim timestamp check failed (it should be in the past)', payload, 'iat', 'check_failed');\n }\n }\n return payload;\n}\nexport class JWTClaimsBuilder {\n #payload;\n constructor(payload) {\n if (!isObject(payload)) {\n throw new TypeError('JWT Claims Set MUST be an object');\n }\n this.#payload = structuredClone(payload);\n }\n data() {\n return encoder.encode(JSON.stringify(this.#payload));\n }\n get iss() {\n return this.#payload.iss;\n }\n set iss(value) {\n this.#payload.iss = value;\n }\n get sub() {\n return this.#payload.sub;\n }\n set sub(value) {\n this.#payload.sub = value;\n }\n get aud() {\n return this.#payload.aud;\n }\n set aud(value) {\n this.#payload.aud = value;\n }\n set jti(value) {\n this.#payload.jti = value;\n }\n set nbf(value) {\n if (typeof value === 'number') {\n this.#payload.nbf = validateInput('setNotBefore', value);\n }\n else if (value instanceof Date) {\n this.#payload.nbf = validateInput('setNotBefore', epoch(value));\n }\n else {\n this.#payload.nbf = epoch(new Date()) + secs(value);\n }\n }\n set exp(value) {\n if (typeof value === 'number') {\n this.#payload.exp = validateInput('setExpirationTime', value);\n }\n else if (value instanceof Date) {\n this.#payload.exp = validateInput('setExpirationTime', epoch(value));\n }\n else {\n this.#payload.exp = epoch(new Date()) + secs(value);\n }\n }\n set iat(value) {\n if (value === undefined) {\n this.#payload.iat = epoch(new Date());\n }\n else if (value instanceof Date) {\n this.#payload.iat = validateInput('setIssuedAt', epoch(value));\n }\n else if (typeof value === 'string') {\n this.#payload.iat = validateInput('setIssuedAt', epoch(new Date()) + secs(value));\n }\n else {\n this.#payload.iat = validateInput('setIssuedAt', value);\n }\n }\n}\n","import { compactVerify } from '../jws/compact/verify.js';\nimport { validateClaimsSet } from '../lib/jwt_claims_set.js';\nimport { JWTInvalid } from '../util/errors.js';\nexport async function jwtVerify(jwt, key, options) {\n const verified = await compactVerify(jwt, key, options);\n if (verified.protectedHeader.crit?.includes('b64') && verified.protectedHeader.b64 === false) {\n throw new JWTInvalid('JWTs MUST NOT use unencoded payload');\n }\n const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options);\n const result = { payload, protectedHeader: verified.protectedHeader };\n if (typeof key === 'function') {\n return { ...result, key: verified.key };\n }\n return result;\n}\n","import { importJWK } from '../key/import.js';\nimport { JWKSInvalid, JOSENotSupported, JWKSNoMatchingKey, JWKSMultipleMatchingKeys, } from '../util/errors.js';\nimport { isObject } from '../lib/is_object.js';\nfunction getKtyFromAlg(alg) {\n switch (typeof alg === 'string' && alg.slice(0, 2)) {\n case 'RS':\n case 'PS':\n return 'RSA';\n case 'ES':\n return 'EC';\n case 'Ed':\n return 'OKP';\n case 'ML':\n return 'AKP';\n default:\n throw new JOSENotSupported('Unsupported \"alg\" value for a JSON Web Key Set');\n }\n}\nfunction isJWKSLike(jwks) {\n return (jwks &&\n typeof jwks === 'object' &&\n Array.isArray(jwks.keys) &&\n jwks.keys.every(isJWKLike));\n}\nfunction isJWKLike(key) {\n return isObject(key);\n}\nclass LocalJWKSet {\n #jwks;\n #cached = new WeakMap();\n constructor(jwks) {\n if (!isJWKSLike(jwks)) {\n throw new JWKSInvalid('JSON Web Key Set malformed');\n }\n this.#jwks = structuredClone(jwks);\n }\n jwks() {\n return this.#jwks;\n }\n async getKey(protectedHeader, token) {\n const { alg, kid } = { ...protectedHeader, ...token?.header };\n const kty = getKtyFromAlg(alg);\n const candidates = this.#jwks.keys.filter((jwk) => {\n let candidate = kty === jwk.kty;\n if (candidate && typeof kid === 'string') {\n candidate = kid === jwk.kid;\n }\n if (candidate && (typeof jwk.alg === 'string' || kty === 'AKP')) {\n candidate = alg === jwk.alg;\n }\n if (candidate && typeof jwk.use === 'string') {\n candidate = jwk.use === 'sig';\n }\n if (candidate && Array.isArray(jwk.key_ops)) {\n candidate = jwk.key_ops.includes('verify');\n }\n if (candidate) {\n switch (alg) {\n case 'ES256':\n candidate = jwk.crv === 'P-256';\n break;\n case 'ES384':\n candidate = jwk.crv === 'P-384';\n break;\n case 'ES512':\n candidate = jwk.crv === 'P-521';\n break;\n case 'Ed25519':\n case 'EdDSA':\n candidate = jwk.crv === 'Ed25519';\n break;\n }\n }\n return candidate;\n });\n const { 0: jwk, length } = candidates;\n if (length === 0) {\n throw new JWKSNoMatchingKey();\n }\n if (length !== 1) {\n const error = new JWKSMultipleMatchingKeys();\n const _cached = this.#cached;\n error[Symbol.asyncIterator] = async function* () {\n for (const jwk of candidates) {\n try {\n yield await importWithAlgCache(_cached, jwk, alg);\n }\n catch { }\n }\n };\n throw error;\n }\n return importWithAlgCache(this.#cached, jwk, alg);\n }\n}\nasync function importWithAlgCache(cache, jwk, alg) {\n const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk);\n if (cached[alg] === undefined) {\n const key = await importJWK({ ...jwk, ext: true }, alg);\n if (key instanceof Uint8Array || key.type !== 'public') {\n throw new JWKSInvalid('JSON Web Key Set members must be public keys');\n }\n cached[alg] = key;\n }\n return cached[alg];\n}\nexport function createLocalJWKSet(jwks) {\n const set = new LocalJWKSet(jwks);\n const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);\n Object.defineProperties(localJWKSet, {\n jwks: {\n value: () => structuredClone(set.jwks()),\n enumerable: false,\n configurable: false,\n writable: false,\n },\n });\n return localJWKSet;\n}\n","import { JOSEError, JWKSNoMatchingKey, JWKSTimeout } from '../util/errors.js';\nimport { createLocalJWKSet } from './local.js';\nimport { isObject } from '../lib/is_object.js';\nfunction isCloudflareWorkers() {\n return (typeof WebSocketPair !== 'undefined' ||\n (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') ||\n (typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel'));\n}\nlet USER_AGENT;\nif (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) {\n const NAME = 'jose';\n const VERSION = 'v6.1.3';\n USER_AGENT = `${NAME}/${VERSION}`;\n}\nexport const customFetch = Symbol();\nasync function fetchJwks(url, headers, signal, fetchImpl = fetch) {\n const response = await fetchImpl(url, {\n method: 'GET',\n signal,\n redirect: 'manual',\n headers,\n }).catch((err) => {\n if (err.name === 'TimeoutError') {\n throw new JWKSTimeout();\n }\n throw err;\n });\n if (response.status !== 200) {\n throw new JOSEError('Expected 200 OK from the JSON Web Key Set HTTP response');\n }\n try {\n return await response.json();\n }\n catch {\n throw new JOSEError('Failed to parse the JSON Web Key Set HTTP response as JSON');\n }\n}\nexport const jwksCache = Symbol();\nfunction isFreshJwksCache(input, cacheMaxAge) {\n if (typeof input !== 'object' || input === null) {\n return false;\n }\n if (!('uat' in input) || typeof input.uat !== 'number' || Date.now() - input.uat >= cacheMaxAge) {\n return false;\n }\n if (!('jwks' in input) ||\n !isObject(input.jwks) ||\n !Array.isArray(input.jwks.keys) ||\n !Array.prototype.every.call(input.jwks.keys, isObject)) {\n return false;\n }\n return true;\n}\nclass RemoteJWKSet {\n #url;\n #timeoutDuration;\n #cooldownDuration;\n #cacheMaxAge;\n #jwksTimestamp;\n #pendingFetch;\n #headers;\n #customFetch;\n #local;\n #cache;\n constructor(url, options) {\n if (!(url instanceof URL)) {\n throw new TypeError('url must be an instance of URL');\n }\n this.#url = new URL(url.href);\n this.#timeoutDuration =\n typeof options?.timeoutDuration === 'number' ? options?.timeoutDuration : 5000;\n this.#cooldownDuration =\n typeof options?.cooldownDuration === 'number' ? options?.cooldownDuration : 30000;\n this.#cacheMaxAge = typeof options?.cacheMaxAge === 'number' ? options?.cacheMaxAge : 600000;\n this.#headers = new Headers(options?.headers);\n if (USER_AGENT && !this.#headers.has('User-Agent')) {\n this.#headers.set('User-Agent', USER_AGENT);\n }\n if (!this.#headers.has('accept')) {\n this.#headers.set('accept', 'application/json');\n this.#headers.append('accept', 'application/jwk-set+json');\n }\n this.#customFetch = options?.[customFetch];\n if (options?.[jwksCache] !== undefined) {\n this.#cache = options?.[jwksCache];\n if (isFreshJwksCache(options?.[jwksCache], this.#cacheMaxAge)) {\n this.#jwksTimestamp = this.#cache.uat;\n this.#local = createLocalJWKSet(this.#cache.jwks);\n }\n }\n }\n pendingFetch() {\n return !!this.#pendingFetch;\n }\n coolingDown() {\n return typeof this.#jwksTimestamp === 'number'\n ? Date.now() < this.#jwksTimestamp + this.#cooldownDuration\n : false;\n }\n fresh() {\n return typeof this.#jwksTimestamp === 'number'\n ? Date.now() < this.#jwksTimestamp + this.#cacheMaxAge\n : false;\n }\n jwks() {\n return this.#local?.jwks();\n }\n async getKey(protectedHeader, token) {\n if (!this.#local || !this.fresh()) {\n await this.reload();\n }\n try {\n return await this.#local(protectedHeader, token);\n }\n catch (err) {\n if (err instanceof JWKSNoMatchingKey) {\n if (this.coolingDown() === false) {\n await this.reload();\n return this.#local(protectedHeader, token);\n }\n }\n throw err;\n }\n }\n async reload() {\n if (this.#pendingFetch && isCloudflareWorkers()) {\n this.#pendingFetch = undefined;\n }\n this.#pendingFetch ||= fetchJwks(this.#url.href, this.#headers, AbortSignal.timeout(this.#timeoutDuration), this.#customFetch)\n .then((json) => {\n this.#local = createLocalJWKSet(json);\n if (this.#cache) {\n this.#cache.uat = Date.now();\n this.#cache.jwks = json;\n }\n this.#jwksTimestamp = Date.now();\n this.#pendingFetch = undefined;\n })\n .catch((err) => {\n this.#pendingFetch = undefined;\n throw err;\n });\n await this.#pendingFetch;\n }\n}\nexport function createRemoteJWKSet(url, options) {\n const set = new RemoteJWKSet(url, options);\n const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);\n Object.defineProperties(remoteJWKSet, {\n coolingDown: {\n get: () => set.coolingDown(),\n enumerable: true,\n configurable: false,\n },\n fresh: {\n get: () => set.fresh(),\n enumerable: true,\n configurable: false,\n },\n reload: {\n value: () => set.reload(),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n reloading: {\n get: () => set.pendingFetch(),\n enumerable: true,\n configurable: false,\n },\n jwks: {\n value: () => set.jwks(),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n });\n return remoteJWKSet;\n}\n","/**\n * Interface to represent an OAuth2 error.\n */\nexport interface OAuth2Error {\n error: string;\n error_description: string;\n message?: string;\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 };\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 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(\n 'build_authorization_url_error',\n 'There was an error when trying to build the authorization URL.',\n cause\n );\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(\n 'build_link_user_url_error',\n 'There was an error when trying to build the Link User URL.',\n cause\n );\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(\n 'build_unlink_user_url_error',\n 'There was an error when trying to build the Unlink User URL.',\n cause\n );\n this.name = 'BuildUnlinkUserUrlError';\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(\n 'The client secret or client assertion signing key must be provided.'\n );\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>(\n value: T\n): Partial<T> {\n return Object.entries(value)\n .filter(([, value]) => typeof value !== 'undefined')\n .reduce((acc, curr) => ({ ...acc, [curr[0]]: curr[1] }), {});\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","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 };\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 type {\n MfaClientOptions,\n AuthenticatorResponse,\n AuthenticatorApiResponse,\n ListAuthenticatorsOptions,\n DeleteAuthenticatorOptions,\n EnrollAuthenticatorOptions,\n EnrollmentResponse,\n EnrollmentApiResponse,\n ChallengeOptions,\n ChallengeResponse,\n ChallengeApiResponse,\n} from './types.js';\nimport {\n MfaListAuthenticatorsError,\n MfaEnrollmentError,\n MfaDeleteAuthenticatorError,\n MfaChallengeError,\n type MfaApiErrorResponse,\n} from './errors.js';\nimport {\n transformAuthenticatorResponse,\n transformEnrollmentResponse,\n transformChallengeResponse,\n} from './utils.js';\n\n\nexport class MfaClient {\n #baseUrl: string;\n #clientId: string;\n #customFetch: typeof fetch;\n\n /**\n * @internal\n */\n constructor(options: MfaClientOptions) {\n this.#baseUrl = `https://${options.domain}`;\n this.#clientId = options.clientId;\n this.#customFetch = options.customFetch ?? ((...args) => fetch(...args));\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 const error = (await response.json()) as MfaApiErrorResponse;\n throw new MfaListAuthenticatorsError(\n error.error_description || 'Failed to list authenticators',\n error\n );\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 const error = (await response.json()) as MfaApiErrorResponse;\n throw new MfaEnrollmentError(\n error.error_description || 'Failed to enroll authenticator',\n error\n );\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 const error = (await response.json()) as MfaApiErrorResponse;\n throw new MfaDeleteAuthenticatorError(\n error.error_description || 'Failed to delete authenticator',\n error\n );\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 (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 const error = (await response.json()) as MfaApiErrorResponse;\n throw new MfaChallengeError(\n error.error_description || 'Failed to challenge authenticator',\n error\n );\n }\n\n const apiResponse = (await response.json()) as ChallengeApiResponse;\n return transformChallengeResponse(apiResponse);\n }\n}\n","import {\n IDToken,\n TokenEndpointResponse,\n TokenEndpointResponseHelpers,\n} from 'openid-client';\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 * 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\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\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 * 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?:\n | 'urn:ietf:params:oauth:token-type:access_token'\n | '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 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 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(\n response: TokenEndpointResponse & TokenEndpointResponseHelpers\n ): 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 = (\n response as typeof response & { issued_token_type?: string }\n ).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 * as client from 'openid-client';\nimport { createRemoteJWKSet, importPKCS8, jwtVerify, customFetch } from 'jose';\nimport {\n BackchannelAuthenticationError,\n BuildAuthorizationUrlError,\n BuildLinkUserUrlError,\n BuildUnlinkUserUrlError,\n TokenExchangeError,\n MissingClientAuthError,\n NotSupportedError,\n NotSupportedErrorCode,\n OAuth2Error,\n TokenByClientCredentialsError,\n TokenByCodeError,\n TokenByRefreshTokenError,\n TokenForConnectionError,\n VerifyLogoutTokenError,\n} from './errors.js';\nimport { stripUndefinedProperties } from './utils.js';\nimport { MfaClient } from './mfa/mfa-client.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 TokenByRefreshTokenOptions,\n TokenForConnectionOptions,\n TokenResponse,\n VerifyLogoutTokenOptions,\n VerifyLogoutTokenResult,\n} from './types.js';\n\nconst DEFAULT_SCOPES = 'openid profile email offline_access';\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 * - requested_token_type: Determines the type of token returned, must be explicit\n * - actor_token, actor_token_type: Delegation parameters that affect authorization context\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(\n 'subject_token must not include leading or trailing whitespace'\n );\n }\n // Very common copy paste mistake (case-insensitive check)\n if (/^bearer\\s+/i.test(token)) {\n throw new TokenExchangeError(\n \"subject_token must not include the 'Bearer ' prefix\"\n );\n }\n}\n\n/**\n * Appends extra parameters to URLSearchParams while enforcing security constraints.\n */\nfunction appendExtraParams(\n params: URLSearchParams,\n extra?: Record<string, string | string[]>\n): 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 =\n '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 =\n '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 * 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 readonly #options: AuthClientOptions;\n #jwks?: ReturnType<typeof createRemoteJWKSet>;\n public mfa: MfaClient;\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 this.mfa = new MfaClient({\n domain: this.#options.domain,\n clientId: this.#options.clientId,\n customFetch: this.#options.customFetch,\n });\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 clientAuth = await this.#getClientAuth();\n\n this.#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.#options.customFetch, \n }\n );\n\n this.#serverMetadata = this.#configuration.serverMetadata();\n this.#configuration[client.customFetch] =\n this.#options.customFetch || fetch;\n\n return {\n configuration: this.#configuration,\n serverMetadata: this.#serverMetadata,\n };\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(\n options?: BuildAuthorizationUrlOptions\n ): Promise<BuildAuthorizationUrlResult> {\n const { serverMetadata } = await this.#discover();\n\n if (\n options?.pushedAuthorizationRequests &&\n !serverMetadata.pushed_authorization_request_endpoint\n ) {\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(\n options: BuildLinkUserUrlOptions\n ): 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(\n options: BuildUnlinkUserUrlOptions\n ): 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(\n options: BackchannelAuthenticationOptions\n ): 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(\n 'authorization_details',\n JSON.stringify(options.authorizationDetails)\n );\n }\n\n try {\n const backchannelAuthenticationResponse =\n await client.initiateBackchannelAuthentication(configuration, params);\n\n const tokenEndpointResponse =\n 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(\n 'authorization_details',\n JSON.stringify(options.authorizationDetails)\n );\n }\n\n try {\n const backchannelAuthenticationResponse =\n 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(\n options: TokenForConnectionOptions\n ): Promise<TokenResponse> {\n if (options.refreshToken && options.accessToken) {\n throw new TokenForConnectionError(\n 'Either a refresh or access token should be specified, but not both.'\n );\n }\n\n const subjectTokenValue = options.accessToken ?? options.refreshToken;\n if (!subjectTokenValue) {\n throw new TokenForConnectionError(\n 'Either a refresh or access token must be specified.'\n );\n }\n\n try {\n return await this.exchangeToken({\n connection: options.connection,\n subjectToken: subjectTokenValue,\n subjectTokenType: options.accessToken\n ? SUBJECT_TYPE_ACCESS_TOKEN\n : 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(\n options: TokenVaultExchangeOptions\n ): Promise<TokenResponse> {\n const { configuration } = await this.#discover();\n\n if ('audience' in options || 'resource' in options) {\n throw new TokenExchangeError(\n 'audience and resource parameters are not supported for Token Vault exchanges'\n );\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:\n options.subjectTokenType ?? SUBJECT_TYPE_ACCESS_TOKEN,\n requested_token_type:\n options.requestedTokenType ??\n 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 e as OAuth2Error\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(\n options: ExchangeProfileOptions\n ): Promise<TokenResponse> {\n const { configuration } = await this.#discover();\n\n validateSubjectToken(options.subjectToken);\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\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 return TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);\n } catch (e) {\n throw new TokenExchangeError(\n `Failed to exchange token of type '${options.subjectTokenType}'${options.audience ? ` for audience '${options.audience}'` : ''}.`,\n e as OAuth2Error\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(\n options: ExchangeProfileOptions | TokenVaultExchangeOptions\n ): Promise<TokenResponse> {\n return 'connection' in options\n ? this.#exchangeTokenVaultToken(options)\n : 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(\n url: URL,\n options: TokenByCodeOptions\n ): Promise<TokenResponse> {\n const { configuration } = await this.#discover();\n try {\n const tokenEndpointResponse = await client.authorizationCodeGrant(\n configuration,\n url,\n {\n pkceCodeVerifier: options.codeVerifier,\n }\n );\n\n return TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);\n } catch (e) {\n throw new TokenByCodeError(\n 'There was an error while trying to request a token.',\n e as OAuth2Error\n );\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 try {\n const tokenEndpointResponse = await client.refreshTokenGrant(\n configuration,\n options.refreshToken\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 e as OAuth2Error\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(\n options: TokenByClientCredentialsOptions\n ): 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(\n configuration,\n params\n );\n\n return TokenResponse.fromTokenEndpointResponse(tokenEndpointResponse);\n } catch (e) {\n throw new TokenByClientCredentialsError(\n 'There was an error while trying to request a token.',\n e as OAuth2Error\n );\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(\n options: VerifyLogoutTokenOptions\n ): Promise<VerifyLogoutTokenResult> {\n const { serverMetadata } = await this.#discover();\n this.#jwks ||= createRemoteJWKSet(new URL(serverMetadata!.jwks_uri!), {\n [customFetch]: this.#options.customFetch,\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(\n 'either \"sid\" or \"sub\" (or both) claims must be present'\n );\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 (\n !('http://schemas.openid.net/event/backchannel-logout' in payload.events)\n ) {\n throw new VerifyLogoutTokenError(\n '\"http://schemas.openid.net/event/backchannel-logout\" member is missing in the \"events\" claim'\n );\n }\n\n if (\n typeof payload.events[\n 'http://schemas.openid.net/event/backchannel-logout'\n ] !== 'object'\n ) {\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 (\n !this.#options.clientSecret &&\n !this.#options.clientAssertionSigningKey &&\n !this.#options.useMtls\n ) {\n throw new MissingClientAuthError();\n }\n\n if (this.#options.useMtls) {\n return client.TlsClientAuth();\n }\n\n let clientPrivateKey = this.#options.clientAssertionSigningKey as\n | CryptoKey\n | 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 }\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(\n options?: BuildAuthorizationUrlOptions\n ): 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","import { MfaApiErrorResponse } from '@auth0/auth0-auth-js';\nimport { GenericError } from '../errors';\n\n/**\n * Base class for MFA-related errors in auth0-spa-js.\n * Extends GenericError for unified error hierarchy across the SDK.\n */\nexport class MfaError extends GenericError {\n constructor(error: string, error_description: string) {\n super(error, error_description);\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, MfaError.prototype);\n }\n\n static fromPayload({\n error,\n error_description\n }: {\n error: string;\n error_description: string;\n }) {\n return new MfaError(error, error_description);\n }\n}\n\n/**\n * Error thrown when listing MFA authenticators fails.\n *\n * @example\n * ```typescript\n * try {\n * const authenticators = await mfa.getAuthenticators();\n * } catch (error) {\n * if (error instanceof MfaListAuthenticatorsError) {\n * console.log(error.error); // 'access_denied'\n * console.log(error.error_description); // 'Unauthorized'\n * }\n * }\n * ```\n */\nexport class MfaListAuthenticatorsError extends MfaError {\n constructor(error: string, error_description: string) {\n super(error, error_description);\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, MfaListAuthenticatorsError.prototype);\n }\n}\n\n/**\n * Error thrown when enrolling an MFA authenticator fails.\n *\n * @example\n * ```typescript\n * try {\n * const enrollment = await mfa.enroll({\n * authenticator_types: ['otp']\n * });\n * } catch (error) {\n * if (error instanceof MfaEnrollmentError) {\n * console.log(error.error); // 'invalid_phone_number'\n * console.log(error.error_description); // 'Invalid phone number format'\n * }\n * }\n * ```\n */\nexport class MfaEnrollmentError extends MfaError {\n constructor(error: string, error_description: string) {\n super(error, error_description);\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, MfaEnrollmentError.prototype);\n }\n}\n\n/**\n * Error thrown when initiating an MFA challenge fails.\n *\n * @example\n * ```typescript\n * try {\n * const challenge = await mfa.challenge({\n * mfaToken: mfaToken,\n * challengeType: 'otp',\n * authenticatorId: 'otp|dev_123'\n * });\n * } catch (error) {\n * if (error instanceof MfaChallengeError) {\n * console.log(error.error); // 'too_many_attempts'\n * console.log(error.error_description); // 'Rate limit exceeded'\n * }\n * }\n * ```\n */\nexport class MfaChallengeError extends MfaError {\n constructor(error: string, error_description: string) {\n super(error, error_description);\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, MfaChallengeError.prototype);\n }\n}\n\n/**\n * Error thrown when verifying an MFA challenge fails.\n *\n * @example\n * ```typescript\n * try {\n * const tokens = await mfa.verify({\n * mfaToken: mfaToken,\n * grant_type: 'http://auth0.com/oauth/grant-type/mfa-otp',\n * otp: '123456'\n * });\n * } catch (error) {\n * if (error instanceof MfaVerifyError) {\n * console.log(error.error); // 'invalid_otp' or 'context_not_found'\n * console.log(error.error_description); // Error details\n * }\n * }\n * ```\n */\nexport class MfaVerifyError extends MfaError {\n constructor(error: string, error_description: string) {\n super(error, error_description);\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, MfaVerifyError.prototype);\n }\n}\n\n/**\n * Error thrown when getting enrollment factors fails.\n *\n * @example\n * ```typescript\n * try {\n * const factors = await mfa.getEnrollmentFactors(mfaToken);\n * } catch (error) {\n * if (error instanceof MfaEnrollmentFactorsError) {\n * console.log(error.error); // 'mfa_context_not_found'\n * console.log(error.error_description); // 'MFA context not found...'\n * }\n * }\n * ```\n */\nexport class MfaEnrollmentFactorsError extends MfaError {\n constructor(error: string, error_description: string) {\n super(error, error_description);\n //https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, MfaEnrollmentFactorsError.prototype);\n }\n}\n\n/**\n * Re-export MfaApiErrorResponse type for convenience\n */\nexport type { MfaApiErrorResponse };\n","import { MfaRequirements } from '../errors';\n\n/**\n * Represents the stored context for an MFA flow\n */\nexport interface MfaContext {\n /** The OAuth scope for the original token request */\n scope?: string;\n /** The API audience for the original token request */\n audience?: string;\n /** MFA requirements from the mfa_required error (camelCase for TypeScript conventions) */\n mfaRequirements?: MfaRequirements;\n /** Timestamp when the context was created */\n createdAt: number;\n}\n\n/**\n * Default TTL for MFA contexts in milliseconds (10 minutes)\n * This aligns with typical MFA token expiration times\n */\nconst DEFAULT_TTL_MS = 10 * 60 * 1000;\n\n/**\n * Manages MFA authentication contexts keyed by MFA token.\n *\n * When an mfa_required error occurs, the SDK stores the original request's\n * scope and audience. When the user later provides an MFA token for verification,\n * the SDK retrieves the matching context to complete the token exchange.\n *\n * This enables concurrent MFA flows without state conflicts.\n *\n * @example\n * ```typescript\n * const manager = new MfaContextManager();\n *\n * // Store context when mfa_required error occurs\n * manager.set('mfaTokenAbc', { scope: 'openid profile', audience: 'https://api.example.com' });\n *\n * // Retrieve context when user completes MFA\n * const context = manager.get('mfaTokenAbc');\n * // { scope: 'openid profile', audience: 'https://api.example.com', createdAt: ... }\n *\n * // Remove after successful verification\n * manager.remove('mfaTokenAbc');\n * ```\n */\nexport class MfaContextManager {\n private contexts: Map<string, MfaContext> = new Map();\n private readonly ttlMs: number;\n\n /**\n * Creates a new MfaContextManager\n * @param ttlMs - Time-to-live for contexts in milliseconds (default: 10 minutes)\n */\n constructor(ttlMs: number = DEFAULT_TTL_MS) {\n this.ttlMs = ttlMs;\n }\n\n /**\n * Stores an MFA context keyed by the MFA token.\n * Runs cleanup to remove expired entries before storing.\n *\n * @param mfaToken - The MFA token from the mfa_required error\n * @param context - The scope and audience from the original request\n */\n public set(\n mfaToken: string,\n context: Omit<MfaContext, 'createdAt'>\n ): void {\n this.cleanup();\n this.contexts.set(mfaToken, {\n ...context,\n createdAt: Date.now()\n });\n }\n\n /**\n * Retrieves the MFA context for a given token.\n * Returns undefined if the token is not found or has expired.\n *\n * @param mfaToken - The MFA token to look up\n * @returns The stored context, or undefined if not found/expired\n */\n public get(mfaToken: string): MfaContext | undefined {\n const context = this.contexts.get(mfaToken);\n if (!context) {\n return undefined;\n }\n\n // Check if expired\n if (Date.now() - context.createdAt > this.ttlMs) {\n this.contexts.delete(mfaToken);\n return undefined;\n }\n\n return context;\n }\n\n /**\n * Removes an MFA context.\n * Should be called after successful MFA verification.\n *\n * @param mfaToken - The MFA token to remove\n */\n public remove(mfaToken: string): void {\n this.contexts.delete(mfaToken);\n }\n\n /**\n * Removes all expired contexts from the Map.\n * Called automatically on every `set` operation.\n */\n private cleanup(): void {\n const now = Date.now();\n for (const [key, value] of this.contexts) {\n if (now - value.createdAt > this.ttlMs) {\n this.contexts.delete(key);\n }\n }\n }\n\n /**\n * Returns the number of stored contexts\n */\n public get size(): number {\n return this.contexts.size;\n }\n}\n","import { Auth0Client } from '../Auth0Client';\nimport type { TokenEndpointResponse } from '../global';\nimport type {\n Authenticator,\n EnrollParams,\n EnrollmentResponse,\n ChallengeAuthenticatorParams,\n ChallengeResponse,\n VerifyParams,\n OobChannel,\n ChallengeType,\n EnrollmentFactor\n} from './types';\nimport { getAuthJsEnrollParams, getGrantType } from './utils';\nimport {\n MfaClient as Auth0AuthJsMfaClient,\n MfaListAuthenticatorsError as Auth0JsMfaListAuthenticatorsError,\n MfaEnrollmentError as Auth0JsMfaEnrollmentError,\n MfaChallengeError as Auth0JsMfaChallengeError\n} from '@auth0/auth0-auth-js';\nimport {\n MfaListAuthenticatorsError,\n MfaEnrollmentError,\n MfaChallengeError,\n MfaVerifyError,\n MfaEnrollmentFactorsError\n} from './errors';\nimport { MfaRequirements, MfaRequiredError } from '../errors';\nimport { MfaContextManager } from './MfaContextManager';\n\n/**\n * Client for Auth0 MFA API operations\n *\n * Manages multi-factor authentication including:\n * - Listing enrolled authenticators\n * - Enrolling new authenticators (OTP, SMS, Voice, Push, Email)\n * - Initiating MFA challenges\n * - Verifying MFA challenges\n *\n * This is a wrapper around auth0-auth-js MfaClient that maintains\n * backward compatibility with the existing spa-js API.\n *\n * MFA context (scope, audience) is stored internally keyed by mfaToken,\n * enabling concurrent MFA flows without state conflicts.\n *\n * @example\n * ```typescript\n * try {\n * await auth0.getTokenSilently({ authorizationParams: { audience: 'https://api.example.com' } });\n * } catch (e) {\n * if (e instanceof MfaRequiredError) {\n * // SDK automatically stores context for this mfaToken\n * const authenticators = await auth0.mfa.getAuthenticators({ mfaToken: e.mfa_token });\n * // ... complete MFA flow\n * }\n * }\n * ```\n */\nexport class MfaApiClient {\n private authJsMfaClient: Auth0AuthJsMfaClient;\n private auth0Client: Auth0Client;\n private contextManager: MfaContextManager;\n\n /**\n * @internal\n * Do not instantiate directly. Use Auth0Client.mfa instead.\n */\n constructor(authJsMfaClient: Auth0AuthJsMfaClient, auth0Client: Auth0Client) {\n this.authJsMfaClient = authJsMfaClient;\n this.auth0Client = auth0Client;\n this.contextManager = new MfaContextManager();\n }\n\n /**\n * @internal\n * Stores authentication details (scope, audience, and MFA requirements) for MFA token verification.\n * This is automatically called by Auth0Client when an mfa_required error occurs.\n *\n * The context is stored keyed by the MFA token, enabling concurrent MFA flows.\n *\n * @param mfaToken - The MFA token from the mfa_required error response\n * @param scope - The OAuth scope from the original request (optional)\n * @param audience - The API audience from the original request (optional)\n * @param mfaRequirements - The MFA requirements from the mfa_required error (optional)\n */\n public setMFAAuthDetails(\n mfaToken: string,\n scope?: string,\n audience?: string,\n mfaRequirements?: MfaRequirements\n ) {\n this.contextManager.set(mfaToken, { scope, audience, mfaRequirements });\n }\n\n /**\n * Gets enrolled MFA authenticators filtered by challenge types from context.\n *\n * Challenge types are automatically resolved from the stored MFA context\n * (set when mfa_required error occurred).\n *\n * @param mfaToken - MFA token from mfa_required error\n * @returns Array of enrolled authenticators matching the challenge types\n * @throws {MfaListAuthenticatorsError} If the request fails or context not found\n *\n * @example Basic usage\n * ```typescript\n * try {\n * await auth0.getTokenSilently();\n * } catch (e) {\n * if (e instanceof MfaRequiredError) {\n * // SDK automatically uses challenge types from error context\n * const authenticators = await auth0.mfa.getAuthenticators(e.mfa_token);\n * }\n * }\n * ```\n */\n public async getAuthenticators(mfaToken: string): Promise<Authenticator[]> {\n // Auto-resolve challenge types from stored context\n const context = this.contextManager.get(mfaToken);\n\n // Single validation check for context and challenge types\n if (!context?.mfaRequirements?.challenge || context.mfaRequirements.challenge.length === 0) {\n throw new MfaListAuthenticatorsError(\n 'invalid_request',\n 'challengeType is required and must contain at least one challenge type, please check mfa_required error payload'\n );\n }\n\n const challengeTypes = context.mfaRequirements.challenge.map(\n c => c.type\n ) as ChallengeType[];\n\n try {\n const allAuthenticators = await this.authJsMfaClient.listAuthenticators({\n mfaToken\n });\n\n // Filter authenticators by challenge types from context\n return allAuthenticators.filter(auth => {\n if (!auth.type) return false;\n return challengeTypes.includes(auth.type as ChallengeType);\n });\n } catch (error: unknown) {\n if (error instanceof Auth0JsMfaListAuthenticatorsError) {\n throw new MfaListAuthenticatorsError(\n error.cause?.error!,\n error.message\n );\n }\n throw error;\n }\n }\n\n /**\n * Enrolls a new MFA authenticator\n *\n * Requires MFA access token with 'enroll' scope\n *\n * @param params - Enrollment parameters including mfaToken and factorType\n * @returns Enrollment response with authenticator details\n * @throws {MfaEnrollmentError} If enrollment fails\n *\n * @example OTP enrollment\n * ```typescript\n * const enrollment = await mfa.enroll({\n * mfaToken: mfaToken,\n * factorType: 'otp'\n * });\n * console.log(enrollment.secret); // Base32 secret\n * console.log(enrollment.barcodeUri); // QR code URI\n * ```\n *\n * @example SMS enrollment\n * ```typescript\n * const enrollment = await mfa.enroll({\n * mfaToken: mfaToken,\n * factorType: 'sms',\n * phoneNumber: '+12025551234'\n * });\n * ```\n */\n public async enroll(\n params: EnrollParams\n ): Promise<EnrollmentResponse> {\n const authJsParams = getAuthJsEnrollParams(params);\n\n try {\n // Type assertion is safe here because getAuthJsEnrollParams ensures correct mapping\n return await this.authJsMfaClient.enrollAuthenticator(authJsParams as any);\n } catch (error: unknown) {\n if (error instanceof Auth0JsMfaEnrollmentError) {\n throw new MfaEnrollmentError(\n error.cause?.error!,\n error.message\n );\n }\n throw error;\n }\n }\n\n /**\n * Initiates an MFA challenge\n *\n * Sends OTP via SMS, initiates push notification, or prepares for OTP entry\n *\n * @param params - Challenge parameters including mfaToken\n * @returns Challenge response with oobCode if applicable\n * @throws {MfaChallengeError} If challenge initiation fails\n *\n * @example OTP challenge\n * ```typescript\n * const challenge = await mfa.challenge({\n * mfaToken: mfaTokenFromLogin,\n * challengeType: 'otp',\n * authenticatorId: 'otp|dev_xxx'\n * });\n * // User enters OTP from their authenticator app\n * ```\n *\n * @example SMS challenge\n * ```typescript\n * const challenge = await mfa.challenge({\n * mfaToken: mfaTokenFromLogin,\n * challengeType: 'oob',\n * authenticatorId: 'sms|dev_xxx'\n * });\n * console.log(challenge.oobCode); // Use for verification\n * ```\n */\n public async challenge(\n params: ChallengeAuthenticatorParams\n ): Promise<ChallengeResponse> {\n try {\n const authJsParams: {\n challengeType: 'otp' | 'oob';\n authenticatorId?: string;\n oobChannel?: OobChannel;\n mfaToken: string;\n } = {\n challengeType: params.challengeType,\n mfaToken: params.mfaToken\n };\n\n if (params.authenticatorId) {\n authJsParams.authenticatorId = params.authenticatorId;\n }\n\n return await this.authJsMfaClient.challengeAuthenticator(authJsParams);\n } catch (error: unknown) {\n if (error instanceof Auth0JsMfaChallengeError) {\n throw new MfaChallengeError(\n error.cause?.error!,\n error.message\n );\n }\n throw error;\n }\n }\n\n /**\n * Gets available MFA enrollment factors from the stored context.\n *\n * This method exposes the enrollment options from the mfa_required error's\n * mfaRequirements.enroll array, eliminating the need for manual parsing.\n *\n * @param mfaToken - MFA token from mfa_required error\n * @returns Array of enrollment factors available for the user (empty array if no enrollment required)\n * @throws {MfaEnrollmentFactorsError} If MFA context not found\n *\n * @example Basic usage\n * ```typescript\n * try {\n * await auth0.getTokenSilently();\n * } catch (error) {\n * if (error.error === 'mfa_required') {\n * // Get enrollment options from SDK\n * const enrollOptions = await auth0.mfa.getEnrollmentFactors(error.mfa_token);\n * // [{ type: 'otp' }, { type: 'phone' }, { type: 'push-notification' }]\n *\n * showEnrollmentOptions(enrollOptions);\n * }\n * }\n * ```\n *\n * @example Check if enrollment is required\n * ```typescript\n * try {\n * const factors = await auth0.mfa.getEnrollmentFactors(mfaToken);\n * if (factors.length > 0) {\n * // User needs to enroll in MFA\n * renderEnrollmentUI(factors);\n * } else {\n * // No enrollment required, proceed with challenge\n * }\n * } catch (error) {\n * if (error instanceof MfaEnrollmentFactorsError) {\n * console.error('Context not found:', error.error_description);\n * }\n * }\n * ```\n */\n public async getEnrollmentFactors(\n mfaToken: string\n ): Promise<EnrollmentFactor[]> {\n const context = this.contextManager.get(mfaToken);\n\n if (!context || !context.mfaRequirements) {\n throw new MfaEnrollmentFactorsError(\n 'mfa_context_not_found',\n 'MFA context not found for this MFA token. Please retry the original request to get a new MFA token.'\n );\n }\n\n // Return empty array if no enrollment required (not an error case)\n if (!context.mfaRequirements.enroll || context.mfaRequirements.enroll.length === 0) {\n return [];\n }\n\n return context.mfaRequirements.enroll;\n }\n\n /**\n * Verifies an MFA challenge and completes authentication\n *\n * The scope and audience are retrieved from the stored context (set when the\n * mfa_required error occurred). The grant_type is automatically inferred from\n * which verification field is provided (otp, oobCode, or recoveryCode).\n *\n * @param params - Verification parameters with OTP, OOB code, or recovery code\n * @returns Token response with access_token, id_token, refresh_token\n * @throws {MfaVerifyError} If verification fails (invalid code, expired, rate limited)\n * @throws {MfaVerifyError} If MFA context not found\n * @throws {MfaVerifyError} If grant_type cannot be inferred\n *\n * Rate limits:\n * - 10 verification attempts allowed\n * - Refreshes at 1 attempt per 6 minutes\n *\n * @example OTP verification (grant_type inferred from otp field)\n * ```typescript\n * const tokens = await mfa.verify({\n * mfaToken: mfaTokenFromLogin,\n * otp: '123456'\n * });\n * console.log(tokens.access_token);\n * ```\n *\n * @example OOB verification (grant_type inferred from oobCode field)\n * ```typescript\n * const tokens = await mfa.verify({\n * mfaToken: mfaTokenFromLogin,\n * oobCode: challenge.oobCode,\n * bindingCode: '123456' // Code user received via SMS\n * });\n * ```\n *\n * @example Recovery code verification (grant_type inferred from recoveryCode field)\n * ```typescript\n * const tokens = await mfa.verify({\n * mfaToken: mfaTokenFromLogin,\n * recoveryCode: 'XXXX-XXXX-XXXX'\n * });\n * ```\n */\n public async verify(\n params: VerifyParams\n ): Promise<TokenEndpointResponse> {\n // Look up stored context for this MFA token\n const context = this.contextManager.get(params.mfaToken);\n\n // Use context values only (set when mfa_required error occurred)\n if (!context) {\n throw new MfaVerifyError(\n 'mfa_context_not_found',\n 'MFA context not found for this MFA token. Please retry the original request to get a new MFA token.'\n );\n }\n\n // Get grant type from verification fields\n const grantType = getGrantType(params);\n\n if (!grantType) {\n throw new MfaVerifyError(\n 'invalid_request',\n 'Unable to determine grant type. Provide one of: otp, oobCode, or recoveryCode.'\n );\n }\n\n const scope = context.scope;\n const audience = context.audience;\n\n try {\n const result = await this.auth0Client._requestTokenForMfa({\n grant_type: grantType,\n mfaToken: params.mfaToken,\n scope,\n audience,\n otp: params.otp,\n oob_code: params.oobCode,\n binding_code: params.bindingCode,\n recovery_code: params.recoveryCode\n });\n\n // Clean up context after successful verification\n this.contextManager.remove(params.mfaToken);\n\n return result;\n } catch (error: unknown) {\n if (error instanceof MfaRequiredError) {\n this.setMFAAuthDetails(\n error.mfa_token,\n scope,\n audience,\n error.mfa_requirements\n );\n } else if (error instanceof MfaVerifyError) {\n throw new MfaVerifyError(\n error.error,\n error.error_description\n );\n }\n throw error;\n }\n }\n}\n","import {\n createQueryParams,\n runPopup,\n parseAuthenticationResult,\n encode,\n createRandomString,\n runIframe,\n sha256,\n bufferToBase64UrlEncoded,\n validateCrypto,\n openPopup,\n getDomain,\n getTokenIssuer,\n parseNumber,\n stripAuth0Client\n} from './utils';\n\nimport { getLockManager, type ILockManager } from './lock';\n\nimport { oauthToken } from './api';\n\nimport { injectDefaultScopes, scopesToRequest } from './scope';\n\nimport {\n InMemoryCache,\n ICache,\n CacheKey,\n CacheManager,\n CacheEntry,\n IdTokenEntry,\n CACHE_KEY_ID_TOKEN_SUFFIX,\n DecodedToken\n} from './cache';\n\nimport { ConnectAccountTransaction, LoginTransaction, TransactionManager } from './transaction-manager';\nimport { verify as verifyIdToken } from './jwt';\nimport {\n AuthenticationError,\n ConnectError,\n GenericError,\n MfaRequiredError,\n MissingRefreshTokenError,\n MissingScopesError,\n PopupOpenError,\n TimeoutError\n} from './errors';\n\nimport {\n ClientStorage,\n CookieStorage,\n CookieStorageWithLegacySameSite,\n SessionStorage\n} from './storage';\n\nimport {\n CACHE_LOCATION_MEMORY,\n DEFAULT_POPUP_CONFIG_OPTIONS,\n DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS,\n MISSING_REFRESH_TOKEN_ERROR_MESSAGE,\n DEFAULT_SCOPE,\n DEFAULT_SESSION_CHECK_EXPIRY_DAYS,\n DEFAULT_AUTH0_CLIENT,\n INVALID_REFRESH_TOKEN_ERROR_MESSAGE,\n USER_BLOCKED_ERROR_MESSAGE,\n DEFAULT_NOW_PROVIDER,\n DEFAULT_FETCH_TIMEOUT_MS,\n DEFAULT_AUDIENCE\n} from './constants';\n\nimport {\n Auth0ClientOptions,\n AuthorizationParams,\n AuthorizeOptions,\n RedirectLoginOptions,\n PopupLoginOptions,\n PopupConfigOptions,\n RedirectLoginResult,\n GetTokenSilentlyOptions,\n GetTokenWithPopupOptions,\n LogoutOptions,\n CacheLocation,\n LogoutUrlOptions,\n User,\n IdToken,\n GetTokenSilentlyVerboseResponse,\n TokenEndpointResponse,\n AuthenticationResult,\n ConnectAccountRedirectResult,\n RedirectConnectAccountOptions,\n ResponseType,\n ClientAuthorizationParams,\n ClientConfiguration\n} from './global';\n\n// @ts-ignore\nimport TokenWorker from './worker/token.worker.ts';\nimport { singlePromise, retryPromise } from './promise-utils';\nimport { CacheKeyManifest } from './cache/key-manifest';\nimport {\n buildIsAuthenticatedCookieName,\n buildOrganizationHintCookieName,\n cacheFactory,\n getAuthorizeParams,\n buildGetTokenSilentlyLockKey,\n buildIframeLockKey,\n OLD_IS_AUTHENTICATED_COOKIE_NAME,\n patchOpenUrlWithOnRedirect,\n getScopeToRequest,\n allScopesAreIncluded,\n isRefreshWithMrrt,\n getMissingScopes\n} from './Auth0Client.utils';\nimport { CustomTokenExchangeOptions } from './TokenExchange';\nimport { Dpop } from './dpop/dpop';\nimport {\n Fetcher,\n type FetcherConfig,\n type CustomFetchMinimalOutput\n} from './fetcher';\nimport { MyAccountApiClient } from './MyAccountApiClient';\nimport { MfaApiClient } from './mfa';\nimport { AuthClient as Auth0AuthJsClient } from '@auth0/auth0-auth-js';\n\n/**\n * @ignore\n */\ntype GetTokenSilentlyResult = TokenEndpointResponse & {\n decodedToken: ReturnType<typeof verifyIdToken>;\n scope: string;\n oauthTokenScope?: string;\n audience: string;\n};\n\n/**\n * Auth0 SDK for Single Page Applications using [Authorization Code Grant Flow with PKCE](https://auth0.com/docs/api-auth/tutorials/authorization-code-grant-pkce).\n */\nexport class Auth0Client {\n private readonly transactionManager: TransactionManager;\n private readonly cacheManager: CacheManager;\n private readonly lockManager: ILockManager;\n private readonly domainUrl: string;\n private readonly tokenIssuer: string;\n private readonly scope: Record<string, string>;\n private readonly cookieStorage: ClientStorage;\n private readonly dpop: Dpop | undefined;\n private readonly sessionCheckExpiryDays: number;\n private readonly orgHintCookieName: string;\n private readonly isAuthenticatedCookieName: string;\n private readonly nowProvider: () => number | Promise<number>;\n private readonly httpTimeoutMs: number;\n private readonly options: Auth0ClientOptions & {\n authorizationParams: ClientAuthorizationParams,\n };\n private readonly userCache: ICache = new InMemoryCache().enclosedCache;\n private readonly myAccountApi: MyAccountApiClient;\n\n /**\n * MFA API client for multi-factor authentication operations.\n *\n * Provides methods for:\n * - Listing enrolled authenticators\n * - Enrolling new authenticators (OTP, SMS, Voice, Push, Email)\n * - Initiating MFA challenges\n * - Verifying MFA challenges\n */\n public readonly mfa: MfaApiClient;\n\n private worker?: Worker;\n private readonly authJsClient: Auth0AuthJsClient;\n\n private readonly defaultOptions: Partial<Auth0ClientOptions> = {\n authorizationParams: {\n scope: DEFAULT_SCOPE\n },\n useRefreshTokensFallback: false,\n useFormData: true\n };\n\n constructor(options: Auth0ClientOptions) {\n this.options = {\n ...this.defaultOptions,\n ...options,\n authorizationParams: {\n ...this.defaultOptions.authorizationParams,\n ...options.authorizationParams\n }\n };\n\n typeof window !== 'undefined' && validateCrypto();\n\n this.lockManager = getLockManager();\n\n if (options.cache && options.cacheLocation) {\n console.warn(\n 'Both `cache` and `cacheLocation` options have been specified in the Auth0Client configuration; ignoring `cacheLocation` and using `cache`.'\n );\n }\n\n let cacheLocation: CacheLocation | undefined;\n let cache: ICache;\n\n if (options.cache) {\n cache = options.cache;\n } else {\n cacheLocation = options.cacheLocation || CACHE_LOCATION_MEMORY;\n\n if (!cacheFactory(cacheLocation)) {\n throw new Error(`Invalid cache location \"${cacheLocation}\"`);\n }\n\n cache = cacheFactory(cacheLocation)();\n }\n\n this.httpTimeoutMs = options.httpTimeoutInSeconds\n ? options.httpTimeoutInSeconds * 1000\n : DEFAULT_FETCH_TIMEOUT_MS;\n\n this.cookieStorage =\n options.legacySameSiteCookie === false\n ? CookieStorage\n : CookieStorageWithLegacySameSite;\n\n this.orgHintCookieName = buildOrganizationHintCookieName(\n this.options.clientId\n );\n\n this.isAuthenticatedCookieName = buildIsAuthenticatedCookieName(\n this.options.clientId\n );\n\n this.sessionCheckExpiryDays =\n options.sessionCheckExpiryDays || DEFAULT_SESSION_CHECK_EXPIRY_DAYS;\n\n const transactionStorage = options.useCookiesForTransactions\n ? this.cookieStorage\n : SessionStorage;\n\n // Construct the scopes based on the following:\n // 1. Always include `openid`\n // 2. Include the scopes provided in `authorizationParams. This defaults to `profile email`\n // 3. Add `offline_access` if `useRefreshTokens` is enabled\n this.scope = injectDefaultScopes(\n this.options.authorizationParams.scope,\n 'openid',\n this.options.useRefreshTokens ? 'offline_access' : ''\n );\n\n this.transactionManager = new TransactionManager(\n transactionStorage,\n this.options.clientId,\n this.options.cookieDomain\n );\n\n this.nowProvider = this.options.nowProvider || DEFAULT_NOW_PROVIDER;\n\n this.cacheManager = new CacheManager(\n cache,\n !cache.allKeys\n ? new CacheKeyManifest(cache, this.options.clientId)\n : undefined,\n this.nowProvider\n );\n\n this.dpop = this.options.useDpop\n ? new Dpop(this.options.clientId)\n : undefined;\n\n this.domainUrl = getDomain(this.options.domain);\n this.tokenIssuer = getTokenIssuer(this.options.issuer, this.domainUrl);\n\n const myAccountApiIdentifier = `${this.domainUrl}/me/`;\n const myAccountFetcher = this.createFetcher({\n ...(this.options.useDpop && { dpopNonceId: '__auth0_my_account_api__' }),\n getAccessToken: () =>\n this.getTokenSilently({\n authorizationParams: {\n scope: 'create:me:connected_accounts',\n audience: myAccountApiIdentifier\n },\n detailedResponse: true\n })\n });\n this.myAccountApi = new MyAccountApiClient(\n myAccountFetcher,\n myAccountApiIdentifier\n );\n\n // Initialize auth-js client foundational Oauth feature support\n this.authJsClient = new Auth0AuthJsClient({\n domain: this.options.domain,\n clientId: this.options.clientId,\n });\n this.mfa = new MfaApiClient(this.authJsClient.mfa, this);\n\n\n // Don't use web workers unless using refresh tokens in memory\n if (\n typeof window !== 'undefined' &&\n window.Worker &&\n this.options.useRefreshTokens &&\n cacheLocation === CACHE_LOCATION_MEMORY\n ) {\n if (this.options.workerUrl) {\n this.worker = new Worker(this.options.workerUrl);\n } else {\n this.worker = new TokenWorker();\n }\n }\n }\n\n /**\n * Returns a readonly copy of the initialization configuration.\n *\n * @returns An object containing domain and clientId\n *\n * @example\n * ```typescript\n * const auth0 = new Auth0Client({\n * domain: 'tenant.auth0.com',\n * clientId: 'abc123'\n * });\n *\n * const config = auth0.getConfiguration();\n * // { domain: 'tenant.auth0.com', clientId: 'abc123' }\n * ```\n */\n public getConfiguration(): Readonly<ClientConfiguration> {\n return Object.freeze({\n domain: this.options.domain,\n clientId: this.options.clientId\n });\n }\n\n private _url(path: string) {\n const auth0ClientObj = this.options.auth0Client || DEFAULT_AUTH0_CLIENT;\n // Strip env from auth0Client for /authorize to prevent query param truncation\n const strippedAuth0Client = stripAuth0Client(auth0ClientObj, true);\n const auth0Client = encodeURIComponent(\n btoa(JSON.stringify(strippedAuth0Client))\n );\n return `${this.domainUrl}${path}&auth0Client=${auth0Client}`;\n }\n\n private _authorizeUrl(authorizeOptions: AuthorizeOptions) {\n return this._url(`/authorize?${createQueryParams(authorizeOptions)}`);\n }\n\n private async _verifyIdToken(\n id_token: string,\n nonce?: string,\n organization?: string\n ) {\n const now = await this.nowProvider();\n\n return verifyIdToken({\n iss: this.tokenIssuer,\n aud: this.options.clientId,\n id_token,\n nonce,\n organization,\n leeway: this.options.leeway,\n max_age: parseNumber(this.options.authorizationParams.max_age),\n now\n });\n }\n\n private _processOrgHint(organization?: string) {\n if (organization) {\n this.cookieStorage.save(this.orgHintCookieName, organization, {\n daysUntilExpire: this.sessionCheckExpiryDays,\n cookieDomain: this.options.cookieDomain\n });\n } else {\n this.cookieStorage.remove(this.orgHintCookieName, {\n cookieDomain: this.options.cookieDomain\n });\n }\n }\n\n private async _prepareAuthorizeUrl(\n authorizationParams: AuthorizationParams,\n authorizeOptions?: Partial<AuthorizeOptions>,\n fallbackRedirectUri?: string\n ): Promise<{\n scope: string;\n audience: string;\n redirect_uri?: string;\n nonce: string;\n code_verifier: string;\n state: string;\n url: string;\n }> {\n const state = encode(createRandomString());\n const nonce = encode(createRandomString());\n const code_verifier = createRandomString();\n const code_challengeBuffer = await sha256(code_verifier);\n const code_challenge = bufferToBase64UrlEncoded(code_challengeBuffer);\n const thumbprint = await this.dpop?.calculateThumbprint();\n\n const params = getAuthorizeParams(\n this.options,\n this.scope,\n authorizationParams,\n state,\n nonce,\n code_challenge,\n authorizationParams.redirect_uri ||\n this.options.authorizationParams.redirect_uri ||\n fallbackRedirectUri,\n authorizeOptions?.response_mode,\n thumbprint\n );\n\n const url = this._authorizeUrl(params);\n\n return {\n nonce,\n code_verifier,\n scope: params.scope,\n audience: params.audience || DEFAULT_AUDIENCE,\n redirect_uri: params.redirect_uri,\n state,\n url\n };\n }\n\n /**\n * ```js\n * try {\n * await auth0.loginWithPopup(options);\n * } catch(e) {\n * if (e instanceof PopupCancelledError) {\n * // Popup was closed before login completed\n * }\n * }\n * ```\n *\n * Opens a popup with the `/authorize` URL using the parameters\n * provided as arguments. Random and secure `state` and `nonce`\n * parameters will be auto-generated. If the response is successful,\n * results will be valid according to their expiration times.\n *\n * IMPORTANT: This method has to be called from an event handler\n * that was started by the user like a button click, for example,\n * otherwise the popup will be blocked in most browsers.\n *\n * @param options\n * @param config\n */\n public async loginWithPopup(\n options?: PopupLoginOptions,\n config?: PopupConfigOptions\n ) {\n options = options || {};\n config = config || {};\n\n if (!config.popup) {\n config.popup = openPopup('');\n\n if (!config.popup) {\n throw new PopupOpenError();\n }\n }\n\n const params = await this._prepareAuthorizeUrl(\n options.authorizationParams || {},\n { response_mode: 'web_message' },\n window.location.origin\n );\n\n config.popup.location.href = params.url;\n\n const codeResult = await runPopup({\n ...config,\n timeoutInSeconds:\n config.timeoutInSeconds ||\n this.options.authorizeTimeoutInSeconds ||\n DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS\n });\n\n if (params.state !== codeResult.state) {\n throw new GenericError('state_mismatch', 'Invalid state');\n }\n\n const organization =\n options.authorizationParams?.organization ||\n this.options.authorizationParams.organization;\n\n await this._requestToken(\n {\n audience: params.audience,\n scope: params.scope,\n code_verifier: params.code_verifier,\n grant_type: 'authorization_code',\n code: codeResult.code as string,\n redirect_uri: params.redirect_uri\n },\n {\n nonceIn: params.nonce,\n organization\n }\n );\n }\n\n /**\n * ```js\n * const user = await auth0.getUser();\n * ```\n *\n * Returns the user information if available (decoded\n * from the `id_token`).\n *\n * @typeparam TUser The type to return, has to extend {@link User}.\n */\n public async getUser<TUser extends User>(): Promise<TUser | undefined> {\n const cache = await this._getIdTokenFromCache();\n\n return cache?.decodedToken?.user as TUser;\n }\n\n /**\n * ```js\n * const claims = await auth0.getIdTokenClaims();\n * ```\n *\n * Returns all claims from the id_token if available.\n */\n public async getIdTokenClaims(): Promise<IdToken | undefined> {\n const cache = await this._getIdTokenFromCache();\n\n return cache?.decodedToken?.claims;\n }\n\n /**\n * ```js\n * await auth0.loginWithRedirect(options);\n * ```\n *\n * Performs a redirect to `/authorize` using the parameters\n * provided as arguments. Random and secure `state` and `nonce`\n * parameters will be auto-generated.\n *\n * @param options\n */\n public async loginWithRedirect<TAppState = any>(\n options: RedirectLoginOptions<TAppState> = {}\n ) {\n const { openUrl, fragment, appState, ...urlOptions } =\n patchOpenUrlWithOnRedirect(options);\n\n const organization =\n urlOptions.authorizationParams?.organization ||\n this.options.authorizationParams.organization;\n\n const { url, ...transaction } = await this._prepareAuthorizeUrl(\n urlOptions.authorizationParams || {}\n );\n\n this.transactionManager.create<LoginTransaction>({\n ...transaction,\n appState,\n response_type: ResponseType.Code,\n ...(organization && { organization })\n });\n\n const urlWithFragment = fragment ? `${url}#${fragment}` : url;\n\n if (openUrl) {\n await openUrl(urlWithFragment);\n } else {\n window.location.assign(urlWithFragment);\n }\n }\n\n /**\n * After the browser redirects back to the callback page,\n * call `handleRedirectCallback` to handle success and error\n * responses from Auth0. If the response is successful, results\n * will be valid according to their expiration times.\n */\n public async handleRedirectCallback<TAppState = any>(\n url: string = window.location.href\n ): Promise<\n RedirectLoginResult<TAppState> | ConnectAccountRedirectResult<TAppState>\n > {\n const queryStringFragments = url.split('?').slice(1);\n\n if (queryStringFragments.length === 0) {\n throw new Error('There are no query params available for parsing.');\n }\n\n const transaction = this.transactionManager.get<\n LoginTransaction | ConnectAccountTransaction\n >();\n\n if (!transaction) {\n throw new GenericError('missing_transaction', 'Invalid state');\n }\n\n this.transactionManager.remove();\n\n const authenticationResult = parseAuthenticationResult(\n queryStringFragments.join('')\n );\n\n if (transaction.response_type === ResponseType.ConnectCode) {\n return this._handleConnectAccountRedirectCallback<TAppState>(\n authenticationResult,\n transaction\n );\n }\n return this._handleLoginRedirectCallback<TAppState>(\n authenticationResult,\n transaction\n );\n }\n\n /**\n * Handles the redirect callback from the login flow.\n *\n * @template AppState - The application state persisted from the /authorize redirect.\n * @param {string} authenticationResult - The parsed authentication result from the URL.\n * @param {string} transaction - The login transaction.\n *\n * @returns {RedirectLoginResult} Resolves with the persisted app state.\n * @throws {GenericError | Error} If the transaction is missing, invalid, or the code exchange fails.\n */\n private async _handleLoginRedirectCallback<TAppState>(\n authenticationResult: AuthenticationResult,\n transaction: LoginTransaction\n ): Promise<RedirectLoginResult<TAppState>> {\n const { code, state, error, error_description } = authenticationResult;\n\n if (error) {\n throw new AuthenticationError(\n error,\n error_description || error,\n state,\n transaction.appState\n );\n }\n\n // Transaction should have a `code_verifier` to do PKCE for CSRF protection\n if (\n !transaction.code_verifier ||\n (transaction.state && transaction.state !== state)\n ) {\n throw new GenericError('state_mismatch', 'Invalid state');\n }\n\n const organization = transaction.organization;\n const nonceIn = transaction.nonce;\n const redirect_uri = transaction.redirect_uri;\n\n await this._requestToken(\n {\n audience: transaction.audience,\n scope: transaction.scope,\n code_verifier: transaction.code_verifier,\n grant_type: 'authorization_code',\n code: code as string,\n ...(redirect_uri ? { redirect_uri } : {})\n },\n { nonceIn, organization }\n );\n\n return {\n appState: transaction.appState,\n response_type: ResponseType.Code\n };\n }\n\n /**\n * Handles the redirect callback from the connect account flow.\n * This works the same as the redirect from the login flow expect it verifies the `connect_code`\n * with the My Account API rather than the `code` with the Authorization Server.\n *\n * @template AppState - The application state persisted from the connect redirect.\n * @param {string} connectResult - The parsed connect accounts result from the URL.\n * @param {string} transaction - The login transaction.\n * @returns {Promise<ConnectAccountRedirectResult>} The result of the My Account API, including any persisted app state.\n * @throws {GenericError | MyAccountApiError} If the transaction is missing, invalid, or an error is returned from the My Account API.\n */\n private async _handleConnectAccountRedirectCallback<TAppState>(\n connectResult: AuthenticationResult,\n transaction: ConnectAccountTransaction\n ): Promise<ConnectAccountRedirectResult<TAppState>> {\n const { connect_code, state, error, error_description } = connectResult;\n\n if (error) {\n throw new ConnectError(\n error,\n error_description || error,\n transaction.connection,\n state,\n transaction.appState\n );\n }\n\n if (!connect_code) {\n throw new GenericError('missing_connect_code', 'Missing connect code');\n }\n\n if (\n !transaction.code_verifier ||\n !transaction.state ||\n !transaction.auth_session ||\n !transaction.redirect_uri ||\n transaction.state !== state\n ) {\n throw new GenericError('state_mismatch', 'Invalid state');\n }\n\n const data = await this.myAccountApi.completeAccount({\n auth_session: transaction.auth_session,\n connect_code,\n redirect_uri: transaction.redirect_uri,\n code_verifier: transaction.code_verifier\n });\n\n return {\n ...data,\n appState: transaction.appState,\n response_type: ResponseType.ConnectCode,\n };\n }\n\n /**\n * ```js\n * await auth0.checkSession();\n * ```\n *\n * Check if the user is logged in using `getTokenSilently`. The difference\n * with `getTokenSilently` is that this doesn't return a token, but it will\n * pre-fill the token cache.\n *\n * This method also heeds the `auth0.{clientId}.is.authenticated` cookie, as an optimization\n * to prevent calling Auth0 unnecessarily. If the cookie is not present because\n * there was no previous login (or it has expired) then tokens will not be refreshed.\n *\n * It should be used for silently logging in the user when you instantiate the\n * `Auth0Client` constructor. You should not need this if you are using the\n * `createAuth0Client` factory.\n *\n * **Note:** the cookie **may not** be present if running an app using a private tab, as some\n * browsers clear JS cookie data and local storage when the tab or page is closed, or on page reload. This effectively\n * means that `checkSession` could silently return without authenticating the user on page refresh when\n * using a private tab, despite having previously logged in. As a workaround, use `getTokenSilently` instead\n * and handle the possible `login_required` error [as shown in the readme](https://github.com/auth0/auth0-spa-js#creating-the-client).\n *\n * @param options\n */\n public async checkSession(options?: GetTokenSilentlyOptions) {\n if (!this.cookieStorage.get(this.isAuthenticatedCookieName)) {\n if (!this.cookieStorage.get(OLD_IS_AUTHENTICATED_COOKIE_NAME)) {\n return;\n } else {\n // Migrate the existing cookie to the new name scoped by client ID\n this.cookieStorage.save(this.isAuthenticatedCookieName, true, {\n daysUntilExpire: this.sessionCheckExpiryDays,\n cookieDomain: this.options.cookieDomain\n });\n\n this.cookieStorage.remove(OLD_IS_AUTHENTICATED_COOKIE_NAME);\n }\n }\n\n try {\n await this.getTokenSilently(options);\n } catch (_) { }\n }\n\n /**\n * Fetches a new access token and returns the response from the /oauth/token endpoint, omitting the refresh token.\n *\n * @param options\n */\n public async getTokenSilently(\n options: GetTokenSilentlyOptions & { detailedResponse: true }\n ): Promise<GetTokenSilentlyVerboseResponse>;\n\n /**\n * Fetches a new access token and returns it.\n *\n * @param options\n */\n public async getTokenSilently(\n options?: GetTokenSilentlyOptions\n ): Promise<string>;\n\n /**\n * Fetches a new access token, and either returns just the access token (the default) or the response from the /oauth/token endpoint, depending on the `detailedResponse` option.\n *\n * ```js\n * const token = await auth0.getTokenSilently(options);\n * ```\n *\n * If there's a valid token stored and it has more than 60 seconds\n * remaining before expiration, return the token. Otherwise, attempt\n * to obtain a new token.\n *\n * A new token will be obtained either by opening an iframe or a\n * refresh token (if `useRefreshTokens` is `true`).\n\n * If iframes are used, opens an iframe with the `/authorize` URL\n * using the parameters provided as arguments. Random and secure `state`\n * and `nonce` parameters will be auto-generated. If the response is successful,\n * results will be validated according to their expiration times.\n *\n * If refresh tokens are used, the token endpoint is called directly with the\n * 'refresh_token' grant. If no refresh token is available to make this call,\n * the SDK will only fall back to using an iframe to the '/authorize' URL if\n * the `useRefreshTokensFallback` setting has been set to `true`. By default this\n * setting is `false`.\n *\n * This method may use a web worker to perform the token call if the in-memory\n * cache is used.\n *\n * If an `audience` value is given to this function, the SDK always falls\n * back to using an iframe to make the token exchange.\n *\n * Note that in all cases, falling back to an iframe requires access to\n * the `auth0` cookie.\n *\n * @param options\n */\n public async getTokenSilently(\n options: GetTokenSilentlyOptions = {}\n ): Promise<undefined | string | GetTokenSilentlyVerboseResponse> {\n const localOptions: GetTokenSilentlyOptions & {\n authorizationParams: AuthorizationParams & { scope: string };\n } = {\n cacheMode: 'on',\n ...options,\n authorizationParams: {\n ...this.options.authorizationParams,\n ...options.authorizationParams,\n scope: scopesToRequest(\n this.scope,\n options.authorizationParams?.scope,\n options.authorizationParams?.audience || this.options.authorizationParams.audience,\n )\n }\n };\n\n const result = await singlePromise(\n () => this._getTokenSilently(localOptions),\n `${this.options.clientId}::${localOptions.authorizationParams.audience}::${localOptions.authorizationParams.scope}`\n );\n\n return options.detailedResponse ? result : result?.access_token;\n }\n\n private async _getTokenSilently(\n options: GetTokenSilentlyOptions & {\n authorizationParams: AuthorizationParams & { scope: string };\n }\n ): Promise<undefined | GetTokenSilentlyVerboseResponse> {\n const { cacheMode, ...getTokenOptions } = options;\n\n // Check the cache before acquiring the lock to avoid the latency of\n // `lock.acquireLock` when the cache is populated.\n if (cacheMode !== 'off') {\n const entry = await this._getEntryFromCache({\n scope: getTokenOptions.authorizationParams.scope,\n audience: getTokenOptions.authorizationParams.audience || DEFAULT_AUDIENCE,\n clientId: this.options.clientId,\n cacheMode,\n });\n\n if (entry) {\n return entry;\n }\n }\n\n if (cacheMode === 'cache-only') {\n return;\n }\n\n // Generate lock key based on client ID and audience for better isolation\n const lockKey = buildGetTokenSilentlyLockKey(\n this.options.clientId,\n getTokenOptions.authorizationParams.audience || 'default'\n );\n\n try {\n return await this.lockManager.runWithLock(lockKey, 5000, async () => {\n // Check the cache a second time, because it may have been populated\n // by a previous call while this call was waiting to acquire the lock.\n if (cacheMode !== 'off') {\n const entry = await this._getEntryFromCache({\n scope: getTokenOptions.authorizationParams.scope,\n audience:\n getTokenOptions.authorizationParams.audience || DEFAULT_AUDIENCE,\n clientId: this.options.clientId\n });\n\n if (entry) {\n return entry;\n }\n }\n\n const authResult = this.options.useRefreshTokens\n ? await this._getTokenUsingRefreshToken(getTokenOptions)\n : await this._getTokenFromIFrame(getTokenOptions);\n\n const { id_token, token_type, access_token, oauthTokenScope, expires_in } =\n authResult;\n\n return {\n id_token,\n token_type,\n access_token,\n ...(oauthTokenScope ? { scope: oauthTokenScope } : null),\n expires_in\n };\n });\n } catch (error) {\n // Lock is already released - safe to open popup\n if (this._isInteractiveError(error) && this.options.interactiveErrorHandler === 'popup') {\n return await this._handleInteractiveErrorWithPopup(getTokenOptions);\n }\n throw error;\n }\n }\n\n /**\n * Checks if an error should be handled by the interactive error handler.\n * Currently only handles mfa_required; extensible for future error types.\n */\n private _isInteractiveError(error: unknown): error is MfaRequiredError {\n return error instanceof MfaRequiredError;\n }\n\n /**\n * Handles MFA errors by opening a popup to complete authentication,\n * then reads the resulting token from cache.\n */\n private async _handleInteractiveErrorWithPopup(\n options: GetTokenSilentlyOptions & {\n authorizationParams: AuthorizationParams & { scope: string };\n }\n ): Promise<GetTokenSilentlyVerboseResponse> {\n try {\n await this.loginWithPopup({\n authorizationParams: options.authorizationParams\n });\n\n const entry = await this._getEntryFromCache({\n scope: options.authorizationParams.scope,\n audience:\n options.authorizationParams.audience || DEFAULT_AUDIENCE,\n clientId: this.options.clientId\n });\n\n if (!entry) {\n throw new GenericError(\n 'interactive_handler_cache_miss',\n 'Token not found in cache after interactive authentication'\n );\n }\n\n return entry;\n } catch (error) {\n // Expected errors (all GenericError subclasses):\n // - PopupCancelledError: user closed the popup before completing login\n // - PopupTimeoutError: popup did not complete within the allowed time\n // - PopupOpenError: popup could not be opened (e.g. blocked by browser)\n // - GenericError: authentication or cache miss errors\n throw error;\n }\n }\n\n /**\n * ```js\n * const token = await auth0.getTokenWithPopup(options);\n * ```\n * Opens a popup with the `/authorize` URL using the parameters\n * provided as arguments. Random and secure `state` and `nonce`\n * parameters will be auto-generated. If the response is successful,\n * results will be valid according to their expiration times.\n *\n * @param options\n * @param config\n */\n public async getTokenWithPopup(\n options: GetTokenWithPopupOptions = {},\n config: PopupConfigOptions = {}\n ) {\n const localOptions = {\n ...options,\n authorizationParams: {\n ...this.options.authorizationParams,\n ...options.authorizationParams,\n scope: scopesToRequest(\n this.scope,\n options.authorizationParams?.scope,\n options.authorizationParams?.audience || this.options.authorizationParams.audience\n )\n }\n };\n\n config = {\n ...DEFAULT_POPUP_CONFIG_OPTIONS,\n ...config\n };\n\n await this.loginWithPopup(localOptions, config);\n\n const cache = await this.cacheManager.get(\n new CacheKey({\n scope: localOptions.authorizationParams.scope,\n audience: localOptions.authorizationParams.audience || DEFAULT_AUDIENCE,\n clientId: this.options.clientId\n }),\n undefined,\n this.options.useMrrt\n );\n\n return cache!.access_token;\n }\n\n /**\n * ```js\n * const isAuthenticated = await auth0.isAuthenticated();\n * ```\n *\n * Returns `true` if there's valid information stored,\n * otherwise returns `false`.\n *\n */\n public async isAuthenticated() {\n const user = await this.getUser();\n return !!user;\n }\n\n /**\n * ```js\n * await auth0.buildLogoutUrl(options);\n * ```\n *\n * Builds a URL to the logout endpoint using the parameters provided as arguments.\n * @param options\n */\n private _buildLogoutUrl(options: LogoutUrlOptions): string {\n if (options.clientId !== null) {\n options.clientId = options.clientId || this.options.clientId;\n } else {\n delete options.clientId;\n }\n\n const { federated, ...logoutOptions } = options.logoutParams || {};\n const federatedQuery = federated ? `&federated` : '';\n const url = this._url(\n `/v2/logout?${createQueryParams({\n clientId: options.clientId,\n ...logoutOptions\n })}`\n );\n\n return url + federatedQuery;\n }\n\n /**\n * ```js\n * await auth0.logout(options);\n * ```\n *\n * Clears the application session and performs a redirect to `/v2/logout`, using\n * the parameters provided as arguments, to clear the Auth0 session.\n *\n * If the `federated` option is specified it also clears the Identity Provider session.\n * [Read more about how Logout works at Auth0](https://auth0.com/docs/logout).\n *\n * @param options\n */\n public async logout(options: LogoutOptions = {}): Promise<void> {\n const { openUrl, ...logoutOptions } = patchOpenUrlWithOnRedirect(options);\n\n if (options.clientId === null) {\n await this.cacheManager.clear();\n } else {\n await this.cacheManager.clear(options.clientId || this.options.clientId);\n }\n\n this.cookieStorage.remove(this.orgHintCookieName, {\n cookieDomain: this.options.cookieDomain\n });\n this.cookieStorage.remove(this.isAuthenticatedCookieName, {\n cookieDomain: this.options.cookieDomain\n });\n this.userCache.remove(CACHE_KEY_ID_TOKEN_SUFFIX);\n\n await this.dpop?.clear();\n\n const url = this._buildLogoutUrl(logoutOptions);\n\n if (openUrl) {\n await openUrl(url);\n } else if (openUrl !== false) {\n window.location.assign(url);\n }\n }\n\n private async _getTokenFromIFrame(\n options: GetTokenSilentlyOptions & {\n authorizationParams: AuthorizationParams & { scope: string };\n }\n ): Promise<GetTokenSilentlyResult> {\n const iframeLockKey = buildIframeLockKey(this.options.clientId);\n\n // Acquire global iframe lock to serialize iframe authorization flows.\n // This is necessary because the SDK does not support multiple simultaneous transactions.\n // Since https://github.com/auth0/auth0-spa-js/pull/1408, when calling\n // `getTokenSilently()`, the global locking will lock per `audience` instead of locking\n // only per `client_id`.\n // This means that calls for different audiences would happen in parallel, which does\n // not work when using silent authentication (prompt=none) from within the SDK, as that\n // relies on the same transaction context as a top-level `loginWithRedirect`.\n // To resolve that, we add a second-level locking that locks only the iframe calls in\n // the same way as was done before https://github.com/auth0/auth0-spa-js/pull/1408.\n try {\n return await this.lockManager.runWithLock(\n iframeLockKey,\n 5000,\n async () => {\n const params: AuthorizationParams & { scope: string } = {\n ...options.authorizationParams,\n prompt: 'none'\n };\n\n const orgHint = this.cookieStorage.get<string>(\n this.orgHintCookieName\n );\n\n if (orgHint && !params.organization) {\n params.organization = orgHint;\n }\n\n const {\n url,\n state: stateIn,\n nonce: nonceIn,\n code_verifier,\n redirect_uri,\n scope,\n audience\n } = await this._prepareAuthorizeUrl(\n params,\n { response_mode: 'web_message' },\n window.location.origin\n );\n\n // When a browser is running in a Cross-Origin Isolated context, using iframes is not possible.\n // It doesn't throw an error but times out instead, so we should exit early and inform the user about the reason.\n // https://developer.mozilla.org/en-US/docs/Web/API/crossOriginIsolated\n if ((window as any).crossOriginIsolated) {\n throw new GenericError(\n 'login_required',\n 'The application is running in a Cross-Origin Isolated context, silently retrieving a token without refresh token is not possible.'\n );\n }\n\n const authorizeTimeout =\n options.timeoutInSeconds || this.options.authorizeTimeoutInSeconds;\n\n // Extract origin from domainUrl, fallback to domainUrl if URL parsing fails\n let eventOrigin: string;\n try {\n eventOrigin = new URL(this.domainUrl).origin;\n } catch {\n eventOrigin = this.domainUrl;\n }\n\n const codeResult = await runIframe(\n url,\n eventOrigin,\n authorizeTimeout\n );\n\n if (stateIn !== codeResult.state) {\n throw new GenericError('state_mismatch', 'Invalid state');\n }\n\n const tokenResult = await this._requestToken(\n {\n ...options.authorizationParams,\n code_verifier,\n code: codeResult.code as string,\n grant_type: 'authorization_code',\n redirect_uri,\n timeout: options.authorizationParams.timeout || this.httpTimeoutMs\n },\n {\n nonceIn,\n organization: params.organization\n }\n );\n\n return {\n ...tokenResult,\n scope: scope,\n oauthTokenScope: tokenResult.scope,\n audience: audience\n };\n }\n );\n } catch (e) {\n if (e.error === 'login_required') {\n this.logout({\n openUrl: false\n });\n }\n throw e;\n }\n }\n\n private async _getTokenUsingRefreshToken(\n options: GetTokenSilentlyOptions & {\n authorizationParams: AuthorizationParams & { scope: string };\n }\n ): Promise<GetTokenSilentlyResult> {\n const cache = await this.cacheManager.get(\n new CacheKey({\n scope: options.authorizationParams.scope,\n audience: options.authorizationParams.audience || DEFAULT_AUDIENCE,\n clientId: this.options.clientId\n }),\n undefined,\n this.options.useMrrt\n );\n\n // If you don't have a refresh token in memory\n // and you don't have a refresh token in web worker memory\n // and useRefreshTokensFallback was explicitly enabled\n // fallback to an iframe\n if ((!cache || !cache.refresh_token) && !this.worker) {\n if (this.options.useRefreshTokensFallback) {\n return await this._getTokenFromIFrame(options);\n }\n\n throw new MissingRefreshTokenError(\n options.authorizationParams.audience || DEFAULT_AUDIENCE,\n options.authorizationParams.scope\n );\n }\n\n const redirect_uri =\n options.authorizationParams.redirect_uri ||\n this.options.authorizationParams.redirect_uri ||\n window.location.origin;\n\n const timeout =\n typeof options.timeoutInSeconds === 'number'\n ? options.timeoutInSeconds * 1000\n : null;\n\n const scopesToRequest = getScopeToRequest(\n this.options.useMrrt,\n options.authorizationParams,\n cache?.audience,\n cache?.scope,\n );\n\n try {\n const tokenResult = await this._requestToken({\n ...options.authorizationParams,\n grant_type: 'refresh_token',\n refresh_token: cache && cache.refresh_token,\n redirect_uri,\n ...(timeout && { timeout })\n },\n {\n scopesToRequest,\n }\n );\n\n // If is refreshed with MRRT, we update all entries that have the old\n // refresh_token with the new one if the server responded with one\n if (tokenResult.refresh_token && cache?.refresh_token) {\n await this.cacheManager.updateEntry(\n cache.refresh_token,\n tokenResult.refresh_token\n );\n }\n\n // Some scopes requested to the server might not be inside the refresh policies\n // In order to return a token with all requested scopes when using MRRT we should\n // check if all scopes are returned. If not, we will try to use an iframe to request\n // a token.\n if (this.options.useMrrt) {\n const isRefreshMrrt = isRefreshWithMrrt(\n cache?.audience,\n cache?.scope,\n options.authorizationParams.audience,\n options.authorizationParams.scope,\n );\n\n if (isRefreshMrrt) {\n const tokenHasAllScopes = allScopesAreIncluded(\n scopesToRequest,\n tokenResult.scope,\n );\n\n if (!tokenHasAllScopes) {\n if (this.options.useRefreshTokensFallback) {\n return await this._getTokenFromIFrame(options);\n }\n\n // Before throwing MissingScopesError, we have to remove the previously created entry\n // to avoid storing wrong data\n await this.cacheManager.remove(\n this.options.clientId,\n options.authorizationParams.audience,\n options.authorizationParams.scope,\n );\n\n const missingScopes = getMissingScopes(\n scopesToRequest,\n tokenResult.scope,\n );\n\n throw new MissingScopesError(\n options.authorizationParams.audience || 'default',\n missingScopes,\n );\n }\n }\n }\n\n return {\n ...tokenResult,\n scope: options.authorizationParams.scope,\n oauthTokenScope: tokenResult.scope,\n audience: options.authorizationParams.audience || DEFAULT_AUDIENCE\n };\n } catch (e) {\n if (e.message) {\n // Blocked users should be logged out immediately. No point attempting\n // iframe fallback as the authorization server will reject the request.\n if (e.message.includes(USER_BLOCKED_ERROR_MESSAGE)) {\n await this.logout({ openUrl: false });\n throw e;\n }\n\n // For missing or invalid refresh tokens, attempt iframe fallback if configured.\n // The iframe may succeed if the user still has a valid session.\n if (\n (e.message.includes(MISSING_REFRESH_TOKEN_ERROR_MESSAGE) ||\n e.message.includes(INVALID_REFRESH_TOKEN_ERROR_MESSAGE)) &&\n this.options.useRefreshTokensFallback\n ) {\n return await this._getTokenFromIFrame(options);\n }\n }\n\n if (e instanceof MfaRequiredError) {\n this.mfa.setMFAAuthDetails(\n e.mfa_token,\n options.authorizationParams?.scope,\n options.authorizationParams?.audience,\n e.mfa_requirements\n );\n }\n\n throw e;\n }\n }\n\n private async _saveEntryInCache(\n entry: CacheEntry & { id_token: string; decodedToken: DecodedToken }\n ) {\n const { id_token, decodedToken, ...entryWithoutIdToken } = entry;\n\n this.userCache.set(CACHE_KEY_ID_TOKEN_SUFFIX, {\n id_token,\n decodedToken\n });\n\n await this.cacheManager.setIdToken(\n this.options.clientId,\n entry.id_token,\n entry.decodedToken\n );\n\n await this.cacheManager.set(entryWithoutIdToken);\n }\n\n private async _getIdTokenFromCache() {\n const audience = this.options.authorizationParams.audience || DEFAULT_AUDIENCE;\n const scope = this.scope[audience];\n\n const cache = await this.cacheManager.getIdToken(\n new CacheKey({\n clientId: this.options.clientId,\n audience,\n scope,\n })\n );\n\n const currentCache = this.userCache.get<IdTokenEntry>(\n CACHE_KEY_ID_TOKEN_SUFFIX\n ) as IdTokenEntry;\n\n // If the id_token in the cache matches the value we previously cached in memory return the in-memory\n // value so that object comparison will work\n if (cache && cache.id_token === currentCache?.id_token) {\n return currentCache;\n }\n\n this.userCache.set(CACHE_KEY_ID_TOKEN_SUFFIX, cache);\n return cache;\n }\n\n private async _getEntryFromCache({\n scope,\n audience,\n clientId,\n cacheMode,\n }: {\n scope: string;\n audience: string;\n clientId: string;\n cacheMode?: string;\n }): Promise<undefined | GetTokenSilentlyVerboseResponse> {\n const entry = await this.cacheManager.get(\n new CacheKey({\n scope,\n audience,\n clientId\n }),\n 60, // get a new token if within 60 seconds of expiring\n this.options.useMrrt,\n cacheMode,\n );\n\n if (entry && entry.access_token) {\n const { token_type, access_token, oauthTokenScope, expires_in } =\n entry as CacheEntry;\n const cache = await this._getIdTokenFromCache();\n return (\n cache && {\n id_token: cache.id_token,\n token_type: token_type ? token_type : 'Bearer',\n access_token,\n ...(oauthTokenScope ? { scope: oauthTokenScope } : null),\n expires_in\n }\n );\n }\n }\n\n private async _requestToken(\n options:\n | PKCERequestTokenOptions\n | RefreshTokenRequestTokenOptions\n | TokenExchangeRequestOptions,\n additionalParameters?: RequestTokenAdditionalParameters\n ) {\n const { nonceIn, organization, scopesToRequest } = additionalParameters || {};\n const authResult = await oauthToken(\n {\n baseUrl: this.domainUrl,\n client_id: this.options.clientId,\n auth0Client: this.options.auth0Client,\n useFormData: this.options.useFormData,\n timeout: this.httpTimeoutMs,\n useMrrt: this.options.useMrrt,\n dpop: this.dpop,\n ...options,\n scope: scopesToRequest || options.scope,\n },\n this.worker\n );\n\n const decodedToken = await this._verifyIdToken(\n authResult.id_token,\n nonceIn,\n organization\n );\n\n // When logging in with authorization_code, check if a different user is authenticating\n // If so, clear the cache to prevent tokens from multiple users coexisting\n if (options.grant_type === 'authorization_code') {\n const existingIdToken = await this._getIdTokenFromCache();\n\n if (existingIdToken?.decodedToken?.claims?.sub &&\n existingIdToken.decodedToken.claims.sub !== decodedToken.claims.sub) {\n // Different user detected - clear cached tokens\n await this.cacheManager.clear(this.options.clientId);\n this.userCache.remove(CACHE_KEY_ID_TOKEN_SUFFIX);\n }\n }\n\n await this._saveEntryInCache({\n ...authResult,\n decodedToken,\n scope: options.scope,\n audience: options.audience || DEFAULT_AUDIENCE,\n ...(authResult.scope ? { oauthTokenScope: authResult.scope } : null),\n client_id: this.options.clientId\n });\n\n this.cookieStorage.save(this.isAuthenticatedCookieName, true, {\n daysUntilExpire: this.sessionCheckExpiryDays,\n cookieDomain: this.options.cookieDomain\n });\n\n this._processOrgHint(organization || decodedToken.claims.org_id);\n\n return { ...authResult, decodedToken };\n }\n\n /*\n Custom Token Exchange\n * **Implementation Notes:**\n * - Ensure that the `subject_token` provided has been securely obtained and is valid according\n * to your external identity provider's policies before invoking this function.\n * - The function leverages internal helper methods:\n * - `validateTokenType` confirms that the `subject_token_type` is supported.\n * - `getUniqueScopes` merges and de-duplicates scopes between the provided options and\n * the instance's default scopes.\n * - `_requestToken` performs the actual HTTP request to the token endpoint.\n */\n\n /**\n * ```js\n * await auth0.loginWithCustomTokenExchange(options);\n * ```\n *\n * Exchanges an external subject token for Auth0 tokens and logs the user in.\n * This method implements the Custom Token Exchange grant as specified in RFC 8693.\n *\n * The exchanged tokens are automatically cached, establishing an authenticated session.\n * After calling this method, you can use `getUser()`, `getIdTokenClaims()`, and\n * `getTokenSilently()` to access the user's information and tokens.\n *\n * @param {CustomTokenExchangeOptions} options - The options required to perform the token exchange.\n *\n * @returns {Promise<TokenEndpointResponse>} A promise that resolves to the token endpoint response,\n * which contains the issued Auth0 tokens (access_token, id_token, etc.).\n *\n * The request includes the following parameters:\n * - `grant_type`: \"urn:ietf:params:oauth:grant-type:token-exchange\"\n * - `subject_token`: The external token to exchange\n * - `subject_token_type`: The type identifier of the external token\n * - `scope`: Merged scopes from the request and SDK defaults\n * - `audience`: Target audience (defaults to SDK configuration)\n * - `organization`: Optional organization ID/name for org-scoped authentication\n *\n * **Example Usage:**\n *\n * ```js\n * const options = {\n * subject_token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6Ikp...',\n * subject_token_type: 'urn:acme:legacy-system-token',\n * scope: 'openid profile email',\n * audience: 'https://api.example.com',\n * organization: 'org_12345'\n * };\n *\n * try {\n * const tokenResponse = await auth0.loginWithCustomTokenExchange(options);\n * console.log('Access token:', tokenResponse.access_token);\n *\n * // User is now logged in - access user info\n * const user = await auth0.getUser();\n * console.log('Logged in user:', user);\n * } catch (error) {\n * console.error('Token exchange failed:', error);\n * }\n * ```\n */\n async loginWithCustomTokenExchange(\n options: CustomTokenExchangeOptions\n ): Promise<TokenEndpointResponse> {\n return this._requestToken({\n ...options,\n grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',\n subject_token: options.subject_token,\n subject_token_type: options.subject_token_type,\n scope: scopesToRequest(\n this.scope,\n options.scope,\n options.audience || this.options.authorizationParams.audience\n ),\n audience: options.audience || this.options.authorizationParams.audience,\n organization: options.organization || this.options.authorizationParams.organization\n });\n }\n\n /**\n * @deprecated Use `loginWithCustomTokenExchange()` instead. This method will be removed in the next major version.\n *\n * Exchanges an external subject token for Auth0 tokens.\n *\n * @param {CustomTokenExchangeOptions} options - The options required to perform the token exchange.\n * @returns {Promise<TokenEndpointResponse>} A promise that resolves to the token endpoint response.\n *\n * **Example:**\n * ```js\n * // Instead of:\n * const tokens = await auth0.exchangeToken(options);\n *\n * // Use:\n * const tokens = await auth0.loginWithCustomTokenExchange(options);\n * ```\n */\n async exchangeToken(\n options: CustomTokenExchangeOptions\n ): Promise<TokenEndpointResponse> {\n return this.loginWithCustomTokenExchange(options);\n }\n\n protected _assertDpop(dpop: Dpop | undefined): asserts dpop is Dpop {\n if (!dpop) {\n throw new Error('`useDpop` option must be enabled before using DPoP.');\n }\n }\n\n /**\n * Returns the current DPoP nonce used for making requests to Auth0.\n *\n * It can return `undefined` because when starting fresh it will not\n * be populated until after the first response from the server.\n *\n * It requires enabling the {@link Auth0ClientOptions.useDpop} option.\n *\n * @param nonce The nonce value.\n * @param id The identifier of a nonce: if absent, it will get the nonce\n * used for requests to Auth0. Otherwise, it will be used to\n * select a specific non-Auth0 nonce.\n */\n public getDpopNonce(id?: string): Promise<string | undefined> {\n this._assertDpop(this.dpop);\n\n return this.dpop.getNonce(id);\n }\n\n /**\n * Sets the current DPoP nonce used for making requests to Auth0.\n *\n * It requires enabling the {@link Auth0ClientOptions.useDpop} option.\n *\n * @param nonce The nonce value.\n * @param id The identifier of a nonce: if absent, it will set the nonce\n * used for requests to Auth0. Otherwise, it will be used to\n * select a specific non-Auth0 nonce.\n */\n public setDpopNonce(nonce: string, id?: string): Promise<void> {\n this._assertDpop(this.dpop);\n\n return this.dpop.setNonce(nonce, id);\n }\n\n /**\n * Returns a string to be used to demonstrate possession of the private\n * key used to cryptographically bind access tokens with DPoP.\n *\n * It requires enabling the {@link Auth0ClientOptions.useDpop} option.\n */\n public generateDpopProof(params: {\n url: string;\n method: string;\n nonce?: string;\n accessToken: string;\n }): Promise<string> {\n this._assertDpop(this.dpop);\n\n return this.dpop.generateProof(params);\n }\n\n /**\n * Returns a new `Fetcher` class that will contain a `fetchWithAuth()` method.\n * This is a drop-in replacement for the Fetch API's `fetch()` method, but will\n * handle certain authentication logic for you, like building the proper auth\n * headers or managing DPoP nonces and retries automatically.\n *\n * Check the `EXAMPLES.md` file for a deeper look into this method.\n */\n public createFetcher<TOutput extends CustomFetchMinimalOutput = Response>(\n config: FetcherConfig<TOutput> = {}\n ): Fetcher<TOutput> {\n return new Fetcher(config, {\n isDpopEnabled: () => !!this.options.useDpop,\n getAccessToken: authParams =>\n this.getTokenSilently({\n authorizationParams: {\n scope: authParams?.scope?.join(' '),\n audience: authParams?.audience\n },\n detailedResponse: true\n }),\n getDpopNonce: () => this.getDpopNonce(config.dpopNonceId),\n setDpopNonce: nonce => this.setDpopNonce(nonce, config.dpopNonceId),\n generateDpopProof: params => this.generateDpopProof(params)\n });\n }\n\n\n /**\n * Initiates a redirect to connect the user's account with a specified connection.\n * This method generates PKCE parameters, creates a transaction, and redirects to the /connect endpoint.\n * \n * You must enable `Offline Access` from the Connection Permissions settings to be able to use the connection with Connected Accounts.\n *\n * @template TAppState - The application state to persist through the transaction.\n * @param {RedirectConnectAccountOptions<TAppState>} options - Options for the connect account redirect flow.\n * @param {string} options.connection - The name of the connection to link (e.g. 'google-oauth2').\n * @param {string[]} [options.scopes] - Array of scopes to request from the Identity Provider during the connect account flow.\n * @param {AuthorizationParams} [options.authorization_params] - Additional authorization parameters for the request to the upstream IdP.\n * @param {string} [options.redirectUri] - The URI to redirect back to after connecting the account.\n * @param {TAppState} [options.appState] - Application state to persist through the transaction.\n * @param {(url: string) => Promise<void>} [options.openUrl] - Custom function to open the URL.\n *\n * @returns {Promise<void>} Resolves when the redirect is initiated.\n * @throws {MyAccountApiError} If the connect request to the My Account API fails.\n */\n public async connectAccountWithRedirect<TAppState = any>(\n options: RedirectConnectAccountOptions<TAppState>\n ) {\n const {\n openUrl,\n appState,\n connection,\n scopes,\n authorization_params,\n redirectUri = this.options.authorizationParams.redirect_uri ||\n window.location.origin\n } = options;\n\n if (!connection) {\n throw new Error('connection is required');\n }\n\n const state = encode(createRandomString());\n const code_verifier = createRandomString();\n const code_challengeBuffer = await sha256(code_verifier);\n const code_challenge = bufferToBase64UrlEncoded(code_challengeBuffer);\n\n const { connect_uri, connect_params, auth_session } =\n await this.myAccountApi.connectAccount({\n connection,\n scopes,\n redirect_uri: redirectUri,\n state,\n code_challenge,\n code_challenge_method: 'S256',\n authorization_params\n });\n\n this.transactionManager.create<ConnectAccountTransaction>({\n state,\n code_verifier,\n auth_session,\n redirect_uri: redirectUri,\n appState,\n connection,\n response_type: ResponseType.ConnectCode\n });\n\n const url = new URL(connect_uri);\n url.searchParams.set('ticket', connect_params.ticket);\n if (openUrl) {\n await openUrl(url.toString());\n } else {\n window.location.assign(url);\n }\n }\n\n /**\n * @internal\n * Internal method used by MfaApiClient to exchange MFA tokens for access tokens.\n * This method should not be called directly by applications.\n */\n async _requestTokenForMfa(\n options: {\n grant_type: string;\n mfaToken: string;\n scope?: string;\n audience?: string;\n otp?: string;\n binding_code?: string;\n oob_code?: string;\n recovery_code?: string;\n },\n additionalParameters?: RequestTokenAdditionalParameters\n ): Promise<TokenEndpointResponse> {\n // Need to add better typing here\n const { mfaToken, ...restOptions } = options;\n return this._requestToken({ ...restOptions, mfa_token: mfaToken } as any, additionalParameters);\n }\n}\n\ninterface BaseRequestTokenOptions {\n audience?: string;\n scope: string;\n timeout?: number;\n redirect_uri?: string;\n}\n\ninterface PKCERequestTokenOptions extends BaseRequestTokenOptions {\n code: string;\n grant_type: 'authorization_code';\n code_verifier: string;\n}\n\ninterface RefreshTokenRequestTokenOptions extends BaseRequestTokenOptions {\n grant_type: 'refresh_token';\n refresh_token?: string;\n}\n\ninterface TokenExchangeRequestOptions extends BaseRequestTokenOptions {\n grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange';\n subject_token: string;\n subject_token_type: string;\n actor_token?: string;\n actor_token_type?: string;\n organization?: string;\n}\n\ninterface RequestTokenAdditionalParameters {\n nonceIn?: string;\n organization?: string;\n scopesToRequest?: string;\n}\n","import { Auth0Client } from './Auth0Client';\nimport { Auth0ClientOptions } from './global';\n\nimport './global';\n\nexport * from './global';\n\n/**\n * Asynchronously creates the Auth0Client instance and calls `checkSession`.\n *\n * **Note:** There are caveats to using this in a private browser tab, which may not silently authenticae\n * a user on page refresh. Please see [the checkSession docs](https://auth0.github.io/auth0-spa-js/classes/Auth0Client.html#checksession) for more info.\n *\n * @param options The client options\n * @returns An instance of Auth0Client\n */\nexport async function createAuth0Client(options: Auth0ClientOptions) {\n const auth0 = new Auth0Client(options);\n await auth0.checkSession();\n return auth0;\n}\n\nexport { Auth0Client };\n\nexport {\n ConnectError,\n GenericError,\n AuthenticationError,\n TimeoutError,\n PopupTimeoutError,\n PopupCancelledError,\n PopupOpenError,\n MfaRequiredError,\n MissingRefreshTokenError,\n UseDpopNonceError\n} from './errors';\n\nexport {\n MfaError,\n MfaListAuthenticatorsError,\n MfaEnrollmentError,\n MfaChallengeError,\n MfaVerifyError,\n MfaEnrollmentFactorsError\n} from './mfa/errors';\n\nexport { MfaApiClient } from './mfa';\n\nexport type {\n MfaFactorType,\n EnrollParams,\n EnrollOtpParams,\n EnrollSmsParams,\n EnrollVoiceParams,\n EnrollEmailParams,\n EnrollPushParams,\n VerifyParams\n} from './mfa';\n\nexport {\n ICache,\n LocalStorageCache,\n InMemoryCache,\n Cacheable,\n DecodedToken,\n CacheEntry,\n WrappedCacheEntry,\n KeyManifestEntry,\n MaybePromise,\n CacheKey,\n CacheKeyData\n} from './cache';\n\nexport type {\n FetcherConfig,\n Fetcher,\n CustomFetchMinimalOutput\n} from './fetcher';\n\nexport { MyAccountApiError } from './MyAccountApiClient';\n\nexport { CustomTokenExchangeOptions } from './TokenExchange';\n"],"names":["version","DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS","DEFAULT_POPUP_CONFIG_OPTIONS","timeoutInSeconds","DEFAULT_SILENT_TOKEN_RETRY_COUNT","CLEANUP_IFRAME_TIMEOUT_IN_SECONDS","DEFAULT_FETCH_TIMEOUT_MS","CACHE_LOCATION_MEMORY","MISSING_REFRESH_TOKEN_ERROR_MESSAGE","INVALID_REFRESH_TOKEN_ERROR_MESSAGE","USER_BLOCKED_ERROR_MESSAGE","DEFAULT_SCOPE","DEFAULT_SESSION_CHECK_EXPIRY_DAYS","DEFAULT_AUTH0_CLIENT","name","DEFAULT_NOW_PROVIDER","Date","now","DEFAULT_AUDIENCE","GenericError","Error","constructor","error","error_description","super","this","Object","setPrototypeOf","prototype","static","_ref","AuthenticationError","state","appState","ConnectError","connection","arguments","length","undefined","TimeoutError","PopupTimeoutError","popup","PopupCancelledError","PopupOpenError","MfaRequiredError","mfa_token","mfa_requirements","MissingRefreshTokenError","audience","scope","concat","valueOrEmptyString","MissingScopesError","UseDpopNonceError","newDpopNonce","value","exclude","includes","parseAuthenticationResult","queryString","indexOf","substring","searchParams","URLSearchParams","get","code","connect_code","runIframe","authorizeUrl","eventOrigin","Promise","res","rej","iframe","window","document","createElement","setAttribute","style","display","removeIframe","body","contains","removeChild","removeEventListener","iframeEventHandler","timeoutSetTimeoutId","setTimeout","e","origin","data","type","eventSource","source","close","response","fromPayload","clearTimeout","addEventListener","appendChild","openPopup","url","width","height","left","screenX","innerWidth","top","screenY","innerHeight","open","runPopup","config","resolve","reject","popupEventListener","popupTimer","setInterval","closed","clearInterval","timeoutId","closePopup","getCrypto","crypto","createRandomString","charset","random","randomValues","Array","from","getRandomValues","Uint8Array","forEach","v","encode","btoa","stripUndefined","params","keys","filter","k","reduce","acc","key","assign","ALLOWED_AUTH0CLIENT_PROPERTIES","stripAuth0Client","auth0Client","excludeEnv","allowedProperty","find","p","createQueryParams","_a","clientId","client_id","__rest","toString","sha256","async","digestOp","subtle","digest","TextEncoder","s","urlEncodeB64","input","b64Chars","replace","m","decodeB64","decodeURIComponent","atob","split","map","c","charCodeAt","slice","join","urlDecodeB64","bufferToBase64UrlEncoded","ie11SafeInput","String","fromCharCode","validateCrypto","getDomain","domainUrl","test","getTokenIssuer","issuer","startsWith","parseNumber","parseInt","fromEntries","iterable","obj","val","defineProperty","processLock","ProcessLocking","_this","locked","Map","addToLocked","toAdd","callbacks","set","unshift","isLocked","has","lock","unlock","delete","toCall","pop","getInstance","instance","getLock","default","__awaiter","thisArg","_arguments","P","generator","fulfilled","step","next","rejected","result","done","then","apply","__generator","_","label","sent","t","trys","ops","f","y","g","verb","throw","return","Symbol","iterator","n","op","TypeError","call","push","browserTabsLock","processLock_1","require$$0","LOCK_STORAGE_KEY","DEFAULT_STORAGE_HANDLER","index","getItem","clear","localStorage","removeItem","setItem","keySync","getItemSync","clearSync","removeItemSync","setItemSync","delay","milliseconds","generateRandomString","CHARS","randomstring","i","INDEX","Math","floor","getLockId","SuperTokensLock","storageHandler","acquiredIatSet","Set","id","acquireLock","bind","releaseLock","releaseLock__private__","waitForSomethingToChange","refreshLockWhileAcquired","waiters","lockKey","timeout","iat","MAX_TIME","STORAGE_KEY","STORAGE","lockObj","TIMEOUT_KEY","lockObjPostDelay","parsedLockObjPostDelay","JSON","stringify","timeoutKey","timeAcquired","timeRefreshed","parse","add","lockCorrector","storageKey","parsedLockObj","resolvedCalled","startedAt","MIN_TIME_TO_WAIT","removedListeners","stopWaiting","removeFromWaiting","timeOutId","timeToWait","addToWaiting","max","func","notifyWaiters","parsedlockObj","MIN_ALLOWED_TIME","KEYS","currIndex","LOCK_KEY","_default","WebLocksApiManager","callback","controller","AbortController","abort","navigator","locks","request","mode","signal","LegacyLockManager","activeLocks","BrowserTabsLock","pagehideHandler","retryAttempts","acquired","size","isWebLocksSupported","createLockManager","lockManager","getLockManager","encoder","decoder","TextDecoder","buf","decode","checkRsaKeyAlgorithm","algorithm","modulusLength","OperationProcessingError","subtleAlgorithm","hash","saltLength","UnsupportedOperationError","jwt","header","claimsSet","usages","b64u","signature","sign","encodeBase64Url","toBase64","ArrayBuffer","alphabet","omitPadding","CHUNK_SIZE","arr","byteLength","subarray","message","captureStackTrace","psAlg","rsAlg","esAlg","namedCurve","determineJWSAlgorithm","isCryptoKey","CryptoKey","isPrivateKey","isPublicKey","epochTime","generateProof","keypair","htu","htm","nonce","accessToken","additional","privateKey","publicKey","extractable","isArray","alg","typ","jwk","publicJwk","jti","randomUUID","ath","kty","x","crv","exportKey","generateKeyPair","options","publicExponent","generateKey","calculateThumbprint","components","DPOP_NONCE_HEADER","KEY_PAIR_ALGORITHM","SUPPORTED_GRANT_TYPES","dpopLib","keyPair","normalizeUrl","parsedUrl","URL","search","href","method","normalizedUrl","isGrantTypeSupported","grantType","sendMessage","to","messageChannel","MessageChannel","port1","onmessage","event","postMessage","port2","createAbortController","dofetch","fetchUrl","fetchOptions","fetch","ok","json","headers","fetchWithoutWorker","race","finally","fetchWithWorker","worker","useFormData","useMrrt","auth","switchFetch","getJSON","dpop","isDpopRetry","dpopProof","getNonce","fetchError","setNonce","errorMessage","oauthToken","baseUrl","isTokenExchange","grant_type","refreshWithMrrt","allParams","isDpopSupported","dpopUtils","dedupe","getUniqueScopes","_len","scopes","_key","Boolean","trim","injectDefaultScopes","authScopes","openIdScope","_len2","extraScopes","_key2","requestedScopes","audienceScopes","scopesToRequest","methodScopes","CACHE_KEY_PREFIX","CACHE_KEY_ID_TOKEN_SUFFIX","CacheKey","prefix","suffix","toKey","entry","LocalStorageCache","payload","remove","allKeys","InMemoryCache","enclosedCache","cache","cacheEntry","DEFAULT_EXPIRY_ADJUSTMENT_SECONDS","CacheManager","keyManifest","nowProvider","idToken","decodedToken","cacheKey","getIdTokenCacheKey","id_token","entryByScope","expiryAdjustmentSeconds","cacheMode","wrappedEntry","getCacheKeys","matchedKey","matchExistingCacheKey","getEntryWithRefreshToken","nowSeconds","expiresAt","refresh_token","modifiedCachedEntry","wrapCacheEntry","memo","expiresInTime","expires_in","keyToMatch","fromKey","scopeSet","scopesToMatch","hasAllScopes","current","cachedEntry","oldRefreshToken","newRefreshToken","TRANSACTION_STORAGE_KEY_PREFIX","TransactionManager","storage","cookieDomain","create","transaction","save","daysUntilExpire","isNumber","idTokendecoded","token","parts","payloadJSON","claims","__raw","user","encoded","verify","decoded","iss","sub","aud","azp","max_age","auth_time","exp","leeway","expDate","setUTCSeconds","nbf","nbfDate","authTimeDate","organization","org","orgId","org_id","orgName","toLowerCase","org_name","__assign","hasOwnProperty","stringifyAttribute","stringified","stringifyAttributes","attributes","expires","setMilliseconds","getMilliseconds","toUTCString","domain","path","secure","sameSite","encodeURIComponent","cookieString","cookies","rdecode","cookie","charAt","name_1","getAll","get_1","set_1","remove_1","CookieStorage","Cookies","cookieAttributes","location","protocol","LEGACY_PREFIX","CookieStorageWithLegacySameSite","SessionStorage","sessionStorage","exports","ResponseType","User","singlePromiseMap","singlePromise","cb","promise","CacheKeyManifest","manifestKey","createManifestKeyFrom","GET_TOKEN_SILENTLY_LOCK_KEY","GET_TOKEN_FROM_IFRAME_LOCK_KEY","buildGetTokenSilentlyLockKey","buildIframeLockKey","buildOrganizationHintCookieName","OLD_IS_AUTHENTICATED_COOKIE_NAME","buildIsAuthenticatedCookieName","cacheLocationBuilders","memory","localstorage","cacheFactory","getAuthorizeParams","clientOptions","authorizationParams","code_challenge","redirect_uri","response_mode","thumbprint","response_type","code_challenge_method","dpop_jkt","patchOpenUrlWithOnRedirect","openUrl","onRedirect","originalOptions","allScopesAreIncluded","scopeToInclude","scopeGroup","scopesToInclude","every","getMissingScopes","requestedScope","respondedScope","respondedScopes","missingScopes","getScopeToRequest","cachedAudience","cachedScope","cachedScopes","newScopes","newScopesAreIncluded","isRefreshWithMrrt","requestAudience","requestScope","VERSION","NAME","TABLES","NONCE","KEYPAIR","AUTH0_NONCE_ID","DpopStorage","getVersion","createDbHandle","req","indexedDB","onupgradeneeded","values","createObjectStore","onerror","onsuccess","dbHandle","table","requestFactory","db","getDbHandle","txn","store","objectStore","buildKey","finalId","setKeyPair","executeDbRequest","put","findNonce","findKeyPair","predicate","getAllKeys","deleteByClientId","deleteBy","clearNonces","clearKeyPairs","Dpop","getOrGenerateKeyPair","all","TokenType","Fetcher","hooks","isAbsoluteUrl","buildUrl","getAccessToken","authParams","extractUrl","info","buildBaseRequest","init","Request","finalUrl","finalInfo","setAuthorizationHeader","tokenType","Bearer","dpopNonceId","dpopNonce","getDpopNonce","generateDpopProof","accessTokenResponse","DPoP","token_type","access_token","setDpopProofHeader","getHeader","Headers","hasUseDpopNonceError","status","wwwAuthHeader","setDpopNonce","onUseDpopNonceError","prepareRequest","handleResponse","fetchWithAuth","internalFetchWithAuth","MyAccountApiClient","myAccountFetcher","apiBase","_handleResponse","text","err","MyAccountApiError","title","detail","validation_errors","FACTOR_MAPPING","otp","authenticatorTypes","sms","oobChannels","email","voice","MfaGrantTypes","OTP","OOB","RECOVERY_CODE","getAuthJsEnrollParams","mapping","factorType","mfaToken","phoneNumber","getGrantType","oobCode","recoveryCode","USER_AGENT","_navigator$userAgent","userAgent","_navigator$userAgent$","expected","getPrototypeOf","toStringTag","_unused","ERR_INVALID_ARG_VALUE","ERR_INVALID_ARG_TYPE","CodedTypeError","cause","allowInsecureRequests","clockSkew","customFetch","modifyAssertion","jweDecrypt","fromBase64","decodeBase64Url","binary","bytes","_Error$captureStackTr","_defineProperty","UNSUPPORTED_OPERATION","_Error$captureStackTr2","OPE","assertCryptoKey","it","assertPrivateKey","isJsonObject","prepareHeaders","looseInstanceOf","entries","AbortSignal","pathname","wellKnown","allowTerminatingSlash","appendWellKnown","replaceDoubleSlash","performDiscovery","urlName","checkProtocol","transform","redirect","discoveryRequest","issuerIdentifier","prependWellKnown","assertNumber","Number","isFinite","assertString","processDiscoveryResponse","expectedIssuerIdentifier","_nodiscoverycheck","Response","RESPONSE_IS_NOT_CONFORM","getResponseJsonBody","JSON_ATTRIBUTE_COMPARISON","attribute","notJson","types","last","msg","RESPONSE_IS_NOT_JSON","assertContentType","getContentType","contentType","randomBytes","calculatePKCECodeChallenge","codeVerifier","getKeyAndKid","kid","keyToJws","getClockSkew","client","skew","getClockTolerance","tolerance","clockTolerance","as","clientSecret","_as","_headers","clientAssertionPayload","clientPrivateKey","_options$modifyAssert","signJwt","None","TlsClientAuth","keyToSubtle","URLParse","base","_unused2","enforceHttps","HTTP_REQUEST_FORBIDDEN","REQUEST_PROTOCOL_FORBIDDEN","validateEndpoint","endpoint","useMtlsAlias","MISSING_SERVER_METADATA","INVALID_SERVER_METADATA","resolveEndpoint","mtls_endpoint_aliases","pushedAuthorizationRequest","parameters","_options$DPoP","assertAs","assertClient","use_mtls_endpoint_aliases","assertDPoP","addProof","authenticatedRequest","clientAuthentication","cacheNonce","isDPoPNonceError","WWWAuthenticateChallengeError","challenge","scheme","ResponseBodyError","_Error$captureStackTr3","RESPONSE_BODY_ERROR","enumerable","AuthorizationResponseError","buffers","buffer","string","decodeBase64","JOSEError","JWTClaimValidationFailed","claim","reason","JWTExpired","JOSEAlgNotAllowed","JOSENotSupported","JWEDecryptionFailed","JWEInvalid","JWSInvalid","JWTInvalid","JWKInvalid","JWKSInvalid","JWKSNoMatchingKey","JWKSMultipleMatchingKeys","asyncIterator","JWKSTimeout","JWSSignatureVerificationFailed","unusable","prop","isAlgorithm","getHashLength","getNamedCurve","checkUsage","usage","checkSigCryptoKey","actual","_actual$constructor","invalidKeyInput","withAlg","_len3","_key3","isKeyObject","isKeyLike","isDisjoint","sources","parameter","isObjectLike","isObject","proto","checkKeyLength","bytesEqual","a","b","createASN1State","pos","parseLength","first","lengthOfLen","expectTag","expectedTag","getSubarray","parseAlgorithmOID","oidLen","parsePKCS8Header","verLen","algIdLen","algIdStart","algIdLength","parseECAlgorithmIdentifier","algOid","curveOidLen","curveOid","oid","genericImport","keyFormat","keyData","_options$extractable","keyUsages","isPublic","getSigUsages","getEncUsages","curveMap","ES256","ES384","ES512","importKey","processPEMData","pem","pattern","fromPKCS8","_alg$startsWith","opts","subtleMapping","priv","d","jwkToKey","_jwk$ext","_jwk$key_ops","_objectSpread","use","ext","key_ops","importPKCS8","pkcs8","importJWK","decodeBase64URL","oth","validateCrit","Err","recognizedDefault","recognizedOption","protectedHeader","joseHeader","crit","some","recognized","validateAlgorithms","option","algorithms","isJWK","isPrivateJWK","isPublicJWK","isSecretJWK","handleJWK","freeze","WeakMap","cached","cryptoKey","handleKeyObject","keyObject","asymmetricKeyType","toCryptoKey","toUpperCase","_keyObject$asymmetric","nist","asymmetricKeyDetails","normalizeKey","export","format","tag","jwkMatchesOp","_key$key_ops","_key$key_ops$includes","expectedKeyOp","endsWith","symmetricTypeCheck","asymmetricTypeCheck","checkKeyType","int","props","tbi","ClientSecretPost","client_secret","oauth","PrivateKeyJwt","randomPKCECodeVerifier","ClientError","errorHandler","DOMException","handleEntraId","server","kEntraId","handleB2Clogin","hostname","discovery","metadata","Configuration","internals","execute","extension","getSigKey","flattenedVerify","jws","protected","parsedProt","extensions","b64","resolvedKey","verified","_unused3","unprotectedHeader","compactVerify","epoch","date","getTime","minute","hour","day","week","year","REGEX","secs","str","matched","exec","parseFloat","unit","numericDate","round","normalizeTyp","checkAudiencePresence","audPayload","audOption","validateClaimsSet","encodedPayload","requiredClaims","subject","maxTokenAge","presenceCheck","reverse","currentDate","age","jwtVerify","_verified$protectedHe","getKtyFromAlg","isJWKSLike","jwks","isJWKLike","_jwks","_cached2","LocalJWKSet","_classPrivateFieldInitSpec","_classPrivateFieldSet","structuredClone","_classPrivateFieldGet","candidates","candidate","_cached","_wrapAsyncGenerator","_awaitAsyncGenerator","importWithAlgCache","createLocalJWKSet","localJWKSet","getKey","defineProperties","configurable","writable","isCloudflareWorkers","WebSocketPair","EdgeRuntime","fetchJwks","fetchImpl","catch","jwksCache","isFreshJwksCache","cacheMaxAge","uat","_url","_timeoutDuration","_cooldownDuration","_cacheMaxAge","_jwksTimestamp","_pendingFetch","_customFetch","_local","_cache","RemoteJWKSet","timeoutDuration","cooldownDuration","append","pendingFetch","coolingDown","fresh","_classPrivateFieldGet2","reload","createRemoteJWKSet","remoteJWKSet","reloading","DEFAULT_SCOPES","MAX_ARRAY_VALUES_PER_KEY","PARAM_DENYLIST","validateSubjectToken","TokenExchangeError","appendExtraParams","extra","parameterKey","parameterValue","arrayItem","TOKEN_EXCHANGE_GRANT_TYPE","SUBJECT_TYPE_REFRESH_TOKEN","SUBJECT_TYPE_ACCESS_TOKEN","REQUESTED_TOKEN_TYPE_FEDERATED_CONNECTION_ACCESS_TOKEN","AuthClient","_configuration","_serverMetadata","_options","_Class8_brand","WeakSet","_classPrivateMethodInitSpec","useMtls","NotSupportedError","mfa","MfaClient","serverMetadata","_assertClassBrand","_discover","pushedAuthorizationRequests","pushed_authorization_request_endpoint","_buildAuthorizationUrl","BuildAuthorizationUrlError","requested_connection","requested_connection_scope","connectionScope","id_token_hint","linkUserUrl","authorizationUrl","BuildLinkUserUrlError","unlinkUserUrl","BuildUnlinkUserUrlError","configuration","additionalParams","stripUndefinedProperties","binding_message","bindingMessage","login_hint","loginHint","requestedExpiry","authorizationDetails","tokenEndpointResponse","backchannelAuthenticationResponse","TokenResponse","fromTokenEndpointResponse","BackchannelAuthenticationError","auth_req_id","expiresIn","interval","_ref2","authReqId","_options$accessToken","refreshToken","TokenForConnectionError","subjectTokenValue","exchangeToken","subjectToken","subjectTokenType","_exchangeTokenVaultToken","_exchangeProfileToken","pkceCodeVerifier","TokenByRefreshTokenError","TokenByClientCredentialsError","end_session_endpoint","returnTo","post_logout_redirect_uri","jwks_uri","customFetch2","logoutToken","VerifyLogoutTokenError","sid","events","clientAuth","_getClientAuth","customFetch$1","_options$subjectToken","_options$requestedTok","subject_token","subject_token_type","requested_token_type","requestedTokenType","tokenRequestParams","GRANT_TYPE_FEDERATED_CONNECTION_ACCESS_TOKEN","clientAssertionSigningKey","MissingClientAuthError","clientAssertionSigningAlg","codeChallengeMethod","codeChallenge","MfaError","MfaListAuthenticatorsError","MfaEnrollmentError","MfaChallengeError","MfaVerifyError","MfaEnrollmentFactorsError","DEFAULT_TTL_MS","MfaContextManager","ttlMs","contexts","context","cleanup","createdAt","MfaApiClient","authJsMfaClient","contextManager","setMFAAuthDetails","mfaRequirements","challengeTypes","allAuthenticators","listAuthenticators","Auth0JsMfaListAuthenticatorsError","_b","authJsParams","enrollAuthenticator","Auth0JsMfaEnrollmentError","challengeType","authenticatorId","challengeAuthenticator","Auth0JsMfaChallengeError","enroll","_requestTokenForMfa","oob_code","binding_code","bindingCode","recovery_code","Auth0Client","userCache","defaultOptions","useRefreshTokensFallback","cacheLocation","console","warn","httpTimeoutMs","httpTimeoutInSeconds","cookieStorage","legacySameSiteCookie","orgHintCookieName","isAuthenticatedCookieName","sessionCheckExpiryDays","transactionStorage","useCookiesForTransactions","useRefreshTokens","transactionManager","cacheManager","useDpop","tokenIssuer","myAccountApiIdentifier","createFetcher","getTokenSilently","detailedResponse","myAccountApi","authJsClient","Auth0AuthJsClient","Worker","workerUrl","TokenWorker","getConfiguration","auth0ClientObj","strippedAuth0Client","_authorizeUrl","authorizeOptions","verifyIdToken","_processOrgHint","fallbackRedirectUri","code_verifier","code_challengeBuffer","_prepareAuthorizeUrl","codeResult","authorizeTimeoutInSeconds","_requestToken","nonceIn","_getIdTokenFromCache","fragment","urlOptions","_c","Code","urlWithFragment","queryStringFragments","authenticationResult","ConnectCode","_handleConnectAccountRedirectCallback","_handleLoginRedirectCallback","connectResult","auth_session","completeAccount","localOptions","_getTokenSilently","getTokenOptions","_getEntryFromCache","runWithLock","authResult","_getTokenUsingRefreshToken","_getTokenFromIFrame","oauthTokenScope","_isInteractiveError","interactiveErrorHandler","_handleInteractiveErrorWithPopup","loginWithPopup","getUser","_buildLogoutUrl","logoutParams","federated","logoutOptions","federatedQuery","iframeLockKey","prompt","orgHint","stateIn","crossOriginIsolated","authorizeTimeout","tokenResult","logout","updateEntry","isRefreshMrrt","tokenHasAllScopes","entryWithoutIdToken","setIdToken","getIdToken","currentCache","additionalParameters","_verifyIdToken","existingIdToken","_saveEntryInCache","loginWithCustomTokenExchange","_assertDpop","isDpopEnabled","authorization_params","redirectUri","connect_uri","connect_params","connectAccount","ticket","restOptions","createAuth0Client","auth0","checkSession"],"mappings":";;;;;;;;;;;;;;;;;IAAA,IAAAA,UAAe;ICMR,MAAMC,uCAAuC;IAK7C,MAAMC,+BAAmD;QAC9DC,kBAAkBF;;IAMb,MAAMG,mCAAmC;IAKzC,MAAMC,oCAAoC;IAK1C,MAAMC,2BAA2B;IAEjC,MAAMC,wBAAwB;IAM9B,MAAMC,sCAAsC;IAK5C,MAAMC,sCAAsC;IAK5C,MAAMC,6BAA6B;IAKnC,MAAMC,gBAAgB;IAKtB,MAAMC,oCAAoC;IAK1C,MAAMC,uBAAuB;QAClCC,MAAM;QACNd,SAASA;;IAGJ,MAAMe,uBAAuBA,MAAMC,KAAKC;IAExC,MAAMC,mBAAmB;ICvD1B,MAAOC,qBAAqB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