UNPKG

@azure/msal-node

Version:
1,503 lines (1,480 loc) 531 kB
/*! @azure/msal-node v5.0.3 2026-01-28 */ 'use strict'; 'use strict'; var uuid = require('uuid'); var crypto = require('crypto'); var jwt = require('jsonwebtoken'); var http = require('http'); var fs = require('fs'); var path = require('path'); /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ /** * This class serializes cache entities to be saved into in-memory object types defined internally * @internal */ class Serializer { /** * serialize the JSON blob * @param data - JSON blob cache */ static serializeJSONBlob(data) { return JSON.stringify(data); } /** * Serialize Accounts * @param accCache - cache of accounts */ static serializeAccounts(accCache) { const accounts = {}; Object.keys(accCache).map(function (key) { const accountEntity = accCache[key]; accounts[key] = { home_account_id: accountEntity.homeAccountId, environment: accountEntity.environment, realm: accountEntity.realm, local_account_id: accountEntity.localAccountId, username: accountEntity.username, authority_type: accountEntity.authorityType, name: accountEntity.name, client_info: accountEntity.clientInfo, last_modification_time: accountEntity.lastModificationTime, last_modification_app: accountEntity.lastModificationApp, tenantProfiles: accountEntity.tenantProfiles?.map((tenantProfile) => { return JSON.stringify(tenantProfile); }), }; }); return accounts; } /** * Serialize IdTokens * @param idTCache - cache of ID tokens */ static serializeIdTokens(idTCache) { const idTokens = {}; Object.keys(idTCache).map(function (key) { const idTEntity = idTCache[key]; idTokens[key] = { home_account_id: idTEntity.homeAccountId, environment: idTEntity.environment, credential_type: idTEntity.credentialType, client_id: idTEntity.clientId, secret: idTEntity.secret, realm: idTEntity.realm, }; }); return idTokens; } /** * Serializes AccessTokens * @param atCache - cache of access tokens */ static serializeAccessTokens(atCache) { const accessTokens = {}; Object.keys(atCache).map(function (key) { const atEntity = atCache[key]; accessTokens[key] = { home_account_id: atEntity.homeAccountId, environment: atEntity.environment, credential_type: atEntity.credentialType, client_id: atEntity.clientId, secret: atEntity.secret, realm: atEntity.realm, target: atEntity.target, cached_at: atEntity.cachedAt, expires_on: atEntity.expiresOn, extended_expires_on: atEntity.extendedExpiresOn, refresh_on: atEntity.refreshOn, key_id: atEntity.keyId, token_type: atEntity.tokenType, userAssertionHash: atEntity.userAssertionHash, }; }); return accessTokens; } /** * Serialize refreshTokens * @param rtCache - cache of refresh tokens */ static serializeRefreshTokens(rtCache) { const refreshTokens = {}; Object.keys(rtCache).map(function (key) { const rtEntity = rtCache[key]; refreshTokens[key] = { home_account_id: rtEntity.homeAccountId, environment: rtEntity.environment, credential_type: rtEntity.credentialType, client_id: rtEntity.clientId, secret: rtEntity.secret, family_id: rtEntity.familyId, target: rtEntity.target, realm: rtEntity.realm, }; }); return refreshTokens; } /** * Serialize amdtCache * @param amdtCache - cache of app metadata */ static serializeAppMetadata(amdtCache) { const appMetadata = {}; Object.keys(amdtCache).map(function (key) { const amdtEntity = amdtCache[key]; appMetadata[key] = { client_id: amdtEntity.clientId, environment: amdtEntity.environment, family_id: amdtEntity.familyId, }; }); return appMetadata; } /** * Serialize the cache * @param inMemCache - itemised cache read from the JSON */ static serializeAllCache(inMemCache) { return { Account: this.serializeAccounts(inMemCache.accounts), IdToken: this.serializeIdTokens(inMemCache.idTokens), AccessToken: this.serializeAccessTokens(inMemCache.accessTokens), RefreshToken: this.serializeRefreshTokens(inMemCache.refreshTokens), AppMetadata: this.serializeAppMetadata(inMemCache.appMetadata), }; } } /*! @azure/msal-common v16.0.3 2026-01-28 */ /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ const SKU = "msal.js.common"; // default authority const DEFAULT_AUTHORITY = "https://login.microsoftonline.com/common/"; const DEFAULT_AUTHORITY_HOST = "login.microsoftonline.com"; const DEFAULT_COMMON_TENANT = "common"; // ADFS String const ADFS = "adfs"; const DSTS = "dstsv2"; // Default AAD Instance Discovery Endpoint const AAD_INSTANCE_DISCOVERY_ENDPT = `${DEFAULT_AUTHORITY}discovery/instance?api-version=1.1&authorization_endpoint=`; // CIAM URL const CIAM_AUTH_URL = ".ciamlogin.com"; const AAD_TENANT_DOMAIN_SUFFIX = ".onmicrosoft.com"; // Resource delimiter - used for certain cache entries const RESOURCE_DELIM = "|"; // Default scopes const OPENID_SCOPE = "openid"; const PROFILE_SCOPE = "profile"; const OFFLINE_ACCESS_SCOPE = "offline_access"; const EMAIL_SCOPE = "email"; const URL_FORM_CONTENT_TYPE = "application/x-www-form-urlencoded;charset=utf-8"; const AUTHORIZATION_PENDING = "authorization_pending"; const NOT_APPLICABLE = "N/A"; const NOT_AVAILABLE = "Not Available"; const FORWARD_SLASH = "/"; const IMDS_ENDPOINT = "http://169.254.169.254/metadata/instance/compute/location"; const IMDS_VERSION = "2020-06-01"; const IMDS_TIMEOUT = 2000; const AZURE_REGION_AUTO_DISCOVER_FLAG = "TryAutoDetect"; const REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX = "login.microsoft.com"; const KNOWN_PUBLIC_CLOUDS = [ "login.microsoftonline.com", "login.windows.net", "login.microsoft.com", "sts.windows.net", ]; const INVALID_INSTANCE = "invalid_instance"; const HTTP_SUCCESS = 200; const HTTP_REDIRECT = 302; const HTTP_CLIENT_ERROR_RANGE_START = 400; const HTTP_BAD_REQUEST = 400; const HTTP_UNAUTHORIZED = 401; const HTTP_NOT_FOUND = 404; const HTTP_REQUEST_TIMEOUT = 408; const HTTP_GONE = 410; const HTTP_TOO_MANY_REQUESTS = 429; const HTTP_CLIENT_ERROR_RANGE_END = 499; const HTTP_SERVER_ERROR = 500; const HTTP_SERVER_ERROR_RANGE_START = 500; const HTTP_SERVICE_UNAVAILABLE = 503; const HTTP_GATEWAY_TIMEOUT = 504; const HTTP_SERVER_ERROR_RANGE_END = 599; const OIDC_DEFAULT_SCOPES = [ OPENID_SCOPE, PROFILE_SCOPE, OFFLINE_ACCESS_SCOPE, ]; const OIDC_SCOPES = [...OIDC_DEFAULT_SCOPES, EMAIL_SCOPE]; /** * Request header names */ const HeaderNames = { CONTENT_TYPE: "Content-Type", CONTENT_LENGTH: "Content-Length", RETRY_AFTER: "Retry-After", CCS_HEADER: "X-AnchorMailbox", WWWAuthenticate: "WWW-Authenticate", AuthenticationInfo: "Authentication-Info", X_MS_REQUEST_ID: "x-ms-request-id", X_MS_HTTP_VERSION: "x-ms-httpver", }; /** * String constants related to AAD Authority */ const AADAuthority = { COMMON: "common", ORGANIZATIONS: "organizations", CONSUMERS: "consumers", }; /** * Claims request keys */ const ClaimsRequestKeys = { ACCESS_TOKEN: "access_token", XMS_CC: "xms_cc", }; /** * we considered making this "enum" in the request instead of string, however it looks like the allowed list of * prompt values kept changing over past couple of years. There are some undocumented prompt values for some * internal partners too, hence the choice of generic "string" type instead of the "enum" */ const PromptValue$1 = { LOGIN: "login", SELECT_ACCOUNT: "select_account", CONSENT: "consent", NONE: "none", CREATE: "create", NO_SESSION: "no_session", }; /** * allowed values for codeVerifier */ const CodeChallengeMethodValues = { S256: "S256", }; /** * Allowed values for response_type */ const OAuthResponseType = { CODE: "code", IDTOKEN_TOKEN: "id_token token"}; /** * allowed values for response_mode */ const ResponseMode$1 = { QUERY: "query", FRAGMENT: "fragment", FORM_POST: "form_post", }; /** * allowed grant_type */ const GrantType = { AUTHORIZATION_CODE_GRANT: "authorization_code", CLIENT_CREDENTIALS_GRANT: "client_credentials", RESOURCE_OWNER_PASSWORD_GRANT: "password", REFRESH_TOKEN_GRANT: "refresh_token", DEVICE_CODE_GRANT: "device_code", JWT_BEARER: "urn:ietf:params:oauth:grant-type:jwt-bearer", }; /** * Account types in Cache */ const CACHE_ACCOUNT_TYPE_MSSTS = "MSSTS"; const CACHE_ACCOUNT_TYPE_ADFS = "ADFS"; const CACHE_ACCOUNT_TYPE_GENERIC = "Generic"; /** * Separators used in cache */ const CACHE_KEY_SEPARATOR = "-"; const CLIENT_INFO_SEPARATOR = "."; /** * Credential Type stored in the cache */ const CredentialType = { ID_TOKEN: "IdToken", ACCESS_TOKEN: "AccessToken", ACCESS_TOKEN_WITH_AUTH_SCHEME: "AccessToken_With_AuthScheme", REFRESH_TOKEN: "RefreshToken", }; /** * More Cache related constants */ const APP_METADATA = "appmetadata"; const CLIENT_INFO = "client_info"; const THE_FAMILY_ID = "1"; const AUTHORITY_METADATA_CACHE_KEY = "authority-metadata"; const AUTHORITY_METADATA_REFRESH_TIME_SECONDS = 3600 * 24; // 24 Hours const AuthorityMetadataSource = { CONFIG: "config", CACHE: "cache", NETWORK: "network", HARDCODED_VALUES: "hardcoded_values", }; const SERVER_TELEM_SCHEMA_VERSION = 5; const SERVER_TELEM_MAX_LAST_HEADER_BYTES = 330; // ESTS limit is 350B, set to 330 to provide a 20B buffer, const SERVER_TELEM_MAX_CACHED_ERRORS = 50; // Limit the number of errors that can be stored to prevent uncontrolled size gains const SERVER_TELEM_CACHE_KEY = "server-telemetry"; const SERVER_TELEM_CATEGORY_SEPARATOR = "|"; const SERVER_TELEM_VALUE_SEPARATOR = ","; const SERVER_TELEM_OVERFLOW_TRUE = "1"; const SERVER_TELEM_OVERFLOW_FALSE = "0"; const SERVER_TELEM_UNKNOWN_ERROR = "unknown_error"; /** * Type of the authentication request */ const AuthenticationScheme = { BEARER: "Bearer", POP: "pop", SSH: "ssh-cert", }; /** * Constants related to throttling */ const DEFAULT_THROTTLE_TIME_SECONDS = 60; // Default maximum time to throttle in seconds, overrides what the server sends back const DEFAULT_MAX_THROTTLE_TIME_SECONDS = 3600; // Prefix for storing throttling entries const THROTTLING_PREFIX = "throttling"; // Value assigned to the x-ms-lib-capability header to indicate to the server the library supports throttling const X_MS_LIB_CAPABILITY_VALUE = "retry-after, h429"; /** * Errors */ const INVALID_GRANT_ERROR = "invalid_grant"; const CLIENT_MISMATCH_ERROR = "client_mismatch"; /** * Password grant parameters */ const PasswordGrantConstants = { username: "username", password: "password", }; /** * Region Discovery Sources */ const RegionDiscoverySources = { FAILED_AUTO_DETECTION: "1", INTERNAL_CACHE: "2", ENVIRONMENT_VARIABLE: "3", IMDS: "4", }; /** * Region Discovery Outcomes */ const RegionDiscoveryOutcomes = { CONFIGURED_NO_AUTO_DETECTION: "2", AUTO_DETECTION_REQUESTED_SUCCESSFUL: "4", AUTO_DETECTION_REQUESTED_FAILED: "5", }; /** * Specifies the reason for fetching the access token from the identity provider */ const CacheOutcome = { // When a token is found in the cache or the cache is not supposed to be hit when making the request NOT_APPLICABLE: "0", // When the token request goes to the identity provider because force_refresh was set to true. Also occurs if claims were requested FORCE_REFRESH_OR_CLAIMS: "1", // When the token request goes to the identity provider because no cached access token exists NO_CACHED_ACCESS_TOKEN: "2", // When the token request goes to the identity provider because cached access token expired CACHED_ACCESS_TOKEN_EXPIRED: "3", // When the token request goes to the identity provider because refresh_in was used and the existing token needs to be refreshed PROACTIVELY_REFRESHED: "4", }; // Token renewal offset default in seconds const DEFAULT_TOKEN_RENEWAL_OFFSET_SEC = 300; const EncodingTypes = { BASE64: "base64", HEX: "hex", UTF8: "utf-8", }; /*! @azure/msal-common v16.0.3 2026-01-28 */ /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ const CLIENT_ID = "client_id"; const REDIRECT_URI = "redirect_uri"; const RESPONSE_TYPE = "response_type"; const RESPONSE_MODE = "response_mode"; const GRANT_TYPE = "grant_type"; const CLAIMS = "claims"; const SCOPE = "scope"; const REFRESH_TOKEN = "refresh_token"; const STATE = "state"; const NONCE = "nonce"; const PROMPT = "prompt"; const CODE = "code"; const CODE_CHALLENGE = "code_challenge"; const CODE_CHALLENGE_METHOD = "code_challenge_method"; const CODE_VERIFIER = "code_verifier"; const CLIENT_REQUEST_ID = "client-request-id"; const X_CLIENT_SKU = "x-client-SKU"; const X_CLIENT_VER = "x-client-VER"; const X_CLIENT_OS = "x-client-OS"; const X_CLIENT_CPU = "x-client-CPU"; const X_CLIENT_CURR_TELEM = "x-client-current-telemetry"; const X_CLIENT_LAST_TELEM = "x-client-last-telemetry"; const X_MS_LIB_CAPABILITY = "x-ms-lib-capability"; const X_APP_NAME = "x-app-name"; const X_APP_VER = "x-app-ver"; const POST_LOGOUT_URI = "post_logout_redirect_uri"; const ID_TOKEN_HINT = "id_token_hint"; const DEVICE_CODE = "device_code"; const CLIENT_SECRET = "client_secret"; const CLIENT_ASSERTION = "client_assertion"; const CLIENT_ASSERTION_TYPE = "client_assertion_type"; const TOKEN_TYPE = "token_type"; const REQ_CNF = "req_cnf"; const OBO_ASSERTION = "assertion"; const REQUESTED_TOKEN_USE = "requested_token_use"; const ON_BEHALF_OF = "on_behalf_of"; const RETURN_SPA_CODE = "return_spa_code"; const LOGOUT_HINT = "logout_hint"; const SID = "sid"; const LOGIN_HINT = "login_hint"; const DOMAIN_HINT = "domain_hint"; const X_CLIENT_EXTRA_SKU = "x-client-xtra-sku"; const BROKER_CLIENT_ID = "brk_client_id"; const BROKER_REDIRECT_URI = "brk_redirect_uri"; const INSTANCE_AWARE = "instance_aware"; /*! @azure/msal-common v16.0.3 2026-01-28 */ /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ function getDefaultErrorMessage(code) { return `See https://aka.ms/msal.js.errors#${code} for details`; } /** * General error class thrown by the MSAL.js library. */ class AuthError extends Error { constructor(errorCode, errorMessage, suberror) { const message = errorMessage || (errorCode ? getDefaultErrorMessage(errorCode) : ""); const errorString = message ? `${errorCode}: ${message}` : errorCode; super(errorString); Object.setPrototypeOf(this, AuthError.prototype); this.errorCode = errorCode || ""; this.errorMessage = message || ""; this.subError = suberror || ""; this.name = "AuthError"; } setCorrelationId(correlationId) { this.correlationId = correlationId; } } function createAuthError(code, additionalMessage) { return new AuthError(code, additionalMessage || getDefaultErrorMessage(code)); } /*! @azure/msal-common v16.0.3 2026-01-28 */ /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ /** * Error thrown when there is an error in configuration of the MSAL.js library. */ class ClientConfigurationError extends AuthError { constructor(errorCode) { super(errorCode); this.name = "ClientConfigurationError"; Object.setPrototypeOf(this, ClientConfigurationError.prototype); } } function createClientConfigurationError(errorCode) { return new ClientConfigurationError(errorCode); } /*! @azure/msal-common v16.0.3 2026-01-28 */ /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ /** * @hidden */ class StringUtils { /** * Check if stringified object is empty * @param strObj */ static isEmptyObj(strObj) { if (strObj) { try { const obj = JSON.parse(strObj); return Object.keys(obj).length === 0; } catch (e) { } } return true; } static startsWith(str, search) { return str.indexOf(search) === 0; } static endsWith(str, search) { return (str.length >= search.length && str.lastIndexOf(search) === str.length - search.length); } /** * Parses string into an object. * * @param query */ static queryStringToObject(query) { const obj = {}; const params = query.split("&"); const decode = (s) => decodeURIComponent(s.replace(/\+/g, " ")); params.forEach((pair) => { if (pair.trim()) { const [key, value] = pair.split(/=(.+)/g, 2); // Split on the first occurence of the '=' character if (key && value) { obj[decode(key)] = decode(value); } } }); return obj; } /** * Trims entries in an array. * * @param arr */ static trimArrayEntries(arr) { return arr.map((entry) => entry.trim()); } /** * Removes empty strings from array * @param arr */ static removeEmptyStringsFromArray(arr) { return arr.filter((entry) => { return !!entry; }); } /** * Attempts to parse a string into JSON * @param str */ static jsonParseHelper(str) { try { return JSON.parse(str); } catch (e) { return null; } } /** * Tests if a given string matches a given pattern, with support for wildcards and queries. * @param pattern Wildcard pattern to string match. Supports "*" for wildcards and "?" for queries * @param input String to match against */ static matchPattern(pattern, input) { /** * Wildcard support: https://stackoverflow.com/a/3117248/4888559 * Queries: replaces "?" in string with escaped "\?" for regex test */ // eslint-disable-next-line security/detect-non-literal-regexp const regex = new RegExp(pattern .replace(/\\/g, "\\\\") .replace(/\*/g, "[^ ]*") .replace(/\?/g, "\\?")); return regex.test(input); } } /*! @azure/msal-common v16.0.3 2026-01-28 */ /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ /** * ClientAuthErrorMessage class containing string constants used by error codes and messages. */ /** * Error thrown when there is an error in the client code running on the browser. */ class ClientAuthError extends AuthError { constructor(errorCode, additionalMessage) { super(errorCode, additionalMessage); this.name = "ClientAuthError"; Object.setPrototypeOf(this, ClientAuthError.prototype); } } function createClientAuthError(errorCode, additionalMessage) { return new ClientAuthError(errorCode, additionalMessage); } /*! @azure/msal-common v16.0.3 2026-01-28 */ /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ const redirectUriEmpty = "redirect_uri_empty"; const claimsRequestParsingError = "claims_request_parsing_error"; const authorityUriInsecure = "authority_uri_insecure"; const urlParseError = "url_parse_error"; const urlEmptyError = "empty_url_error"; const emptyInputScopesError = "empty_input_scopes_error"; const invalidClaims = "invalid_claims"; const tokenRequestEmpty = "token_request_empty"; const logoutRequestEmpty = "logout_request_empty"; const invalidCodeChallengeMethod = "invalid_code_challenge_method"; const pkceParamsMissing = "pkce_params_missing"; const invalidCloudDiscoveryMetadata = "invalid_cloud_discovery_metadata"; const invalidAuthorityMetadata = "invalid_authority_metadata"; const untrustedAuthority = "untrusted_authority"; const missingSshJwk = "missing_ssh_jwk"; const missingSshKid = "missing_ssh_kid"; const missingNonceAuthenticationHeader = "missing_nonce_authentication_header"; const invalidAuthenticationHeader = "invalid_authentication_header"; const cannotSetOIDCOptions = "cannot_set_OIDCOptions"; const cannotAllowPlatformBroker = "cannot_allow_platform_broker"; const authorityMismatch = "authority_mismatch"; const invalidRequestMethodForEAR = "invalid_request_method_for_EAR"; var ClientConfigurationErrorCodes = /*#__PURE__*/Object.freeze({ __proto__: null, authorityMismatch: authorityMismatch, authorityUriInsecure: authorityUriInsecure, cannotAllowPlatformBroker: cannotAllowPlatformBroker, cannotSetOIDCOptions: cannotSetOIDCOptions, claimsRequestParsingError: claimsRequestParsingError, emptyInputScopesError: emptyInputScopesError, invalidAuthenticationHeader: invalidAuthenticationHeader, invalidAuthorityMetadata: invalidAuthorityMetadata, invalidClaims: invalidClaims, invalidCloudDiscoveryMetadata: invalidCloudDiscoveryMetadata, invalidCodeChallengeMethod: invalidCodeChallengeMethod, invalidRequestMethodForEAR: invalidRequestMethodForEAR, logoutRequestEmpty: logoutRequestEmpty, missingNonceAuthenticationHeader: missingNonceAuthenticationHeader, missingSshJwk: missingSshJwk, missingSshKid: missingSshKid, pkceParamsMissing: pkceParamsMissing, redirectUriEmpty: redirectUriEmpty, tokenRequestEmpty: tokenRequestEmpty, untrustedAuthority: untrustedAuthority, urlEmptyError: urlEmptyError, urlParseError: urlParseError }); /*! @azure/msal-common v16.0.3 2026-01-28 */ /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ const clientInfoDecodingError = "client_info_decoding_error"; const clientInfoEmptyError = "client_info_empty_error"; const tokenParsingError = "token_parsing_error"; const nullOrEmptyToken = "null_or_empty_token"; const endpointResolutionError = "endpoints_resolution_error"; const networkError = "network_error"; const openIdConfigError = "openid_config_error"; const hashNotDeserialized = "hash_not_deserialized"; const invalidState = "invalid_state"; const stateMismatch = "state_mismatch"; const stateNotFound = "state_not_found"; const nonceMismatch = "nonce_mismatch"; const authTimeNotFound = "auth_time_not_found"; const maxAgeTranspired = "max_age_transpired"; const multipleMatchingTokens = "multiple_matching_tokens"; const multipleMatchingAppMetadata = "multiple_matching_appMetadata"; const requestCannotBeMade = "request_cannot_be_made"; const cannotRemoveEmptyScope = "cannot_remove_empty_scope"; const cannotAppendScopeSet = "cannot_append_scopeset"; const emptyInputScopeSet = "empty_input_scopeset"; const noAccountInSilentRequest = "no_account_in_silent_request"; const invalidCacheRecord = "invalid_cache_record"; const invalidCacheEnvironment = "invalid_cache_environment"; const noAccountFound = "no_account_found"; const noCryptoObject = "no_crypto_object"; const unexpectedCredentialType = "unexpected_credential_type"; const tokenRefreshRequired = "token_refresh_required"; const tokenClaimsCnfRequiredForSignedJwt = "token_claims_cnf_required_for_signedjwt"; const authorizationCodeMissingFromServerResponse = "authorization_code_missing_from_server_response"; const bindingKeyNotRemoved = "binding_key_not_removed"; const endSessionEndpointNotSupported = "end_session_endpoint_not_supported"; const keyIdMissing = "key_id_missing"; const noNetworkConnectivity = "no_network_connectivity"; const userCanceled = "user_canceled"; const methodNotImplemented = "method_not_implemented"; const nestedAppAuthBridgeDisabled = "nested_app_auth_bridge_disabled"; const platformBrokerError = "platform_broker_error"; var ClientAuthErrorCodes = /*#__PURE__*/Object.freeze({ __proto__: null, authTimeNotFound: authTimeNotFound, authorizationCodeMissingFromServerResponse: authorizationCodeMissingFromServerResponse, bindingKeyNotRemoved: bindingKeyNotRemoved, cannotAppendScopeSet: cannotAppendScopeSet, cannotRemoveEmptyScope: cannotRemoveEmptyScope, clientInfoDecodingError: clientInfoDecodingError, clientInfoEmptyError: clientInfoEmptyError, emptyInputScopeSet: emptyInputScopeSet, endSessionEndpointNotSupported: endSessionEndpointNotSupported, endpointResolutionError: endpointResolutionError, hashNotDeserialized: hashNotDeserialized, invalidCacheEnvironment: invalidCacheEnvironment, invalidCacheRecord: invalidCacheRecord, invalidState: invalidState, keyIdMissing: keyIdMissing, maxAgeTranspired: maxAgeTranspired, methodNotImplemented: methodNotImplemented, multipleMatchingAppMetadata: multipleMatchingAppMetadata, multipleMatchingTokens: multipleMatchingTokens, nestedAppAuthBridgeDisabled: nestedAppAuthBridgeDisabled, networkError: networkError, noAccountFound: noAccountFound, noAccountInSilentRequest: noAccountInSilentRequest, noCryptoObject: noCryptoObject, noNetworkConnectivity: noNetworkConnectivity, nonceMismatch: nonceMismatch, nullOrEmptyToken: nullOrEmptyToken, openIdConfigError: openIdConfigError, platformBrokerError: platformBrokerError, requestCannotBeMade: requestCannotBeMade, stateMismatch: stateMismatch, stateNotFound: stateNotFound, tokenClaimsCnfRequiredForSignedJwt: tokenClaimsCnfRequiredForSignedJwt, tokenParsingError: tokenParsingError, tokenRefreshRequired: tokenRefreshRequired, unexpectedCredentialType: unexpectedCredentialType, userCanceled: userCanceled }); /*! @azure/msal-common v16.0.3 2026-01-28 */ /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ /** * The ScopeSet class creates a set of scopes. Scopes are case-insensitive, unique values, so the Set object in JS makes * the most sense to implement for this class. All scopes are trimmed and converted to lower case strings in intersection and union functions * to ensure uniqueness of strings. */ class ScopeSet { constructor(inputScopes) { // Filter empty string and null/undefined array items const scopeArr = inputScopes ? StringUtils.trimArrayEntries([...inputScopes]) : []; const filteredInput = scopeArr ? StringUtils.removeEmptyStringsFromArray(scopeArr) : []; // Check if scopes array has at least one member if (!filteredInput || !filteredInput.length) { throw createClientConfigurationError(emptyInputScopesError); } this.scopes = new Set(); // Iterator in constructor not supported by IE11 filteredInput.forEach((scope) => this.scopes.add(scope)); } /** * Factory method to create ScopeSet from space-delimited string * @param inputScopeString * @param appClientId * @param scopesRequired */ static fromString(inputScopeString) { const scopeString = inputScopeString || ""; const inputScopes = scopeString.split(" "); return new ScopeSet(inputScopes); } /** * Creates the set of scopes to search for in cache lookups * @param inputScopeString * @returns */ static createSearchScopes(inputScopeString) { // Handle empty scopes by using default OIDC scopes for cache lookup const scopesToUse = inputScopeString && inputScopeString.length > 0 ? inputScopeString : [...OIDC_DEFAULT_SCOPES]; const scopeSet = new ScopeSet(scopesToUse); if (!scopeSet.containsOnlyOIDCScopes()) { scopeSet.removeOIDCScopes(); } else { scopeSet.removeScope(OFFLINE_ACCESS_SCOPE); } return scopeSet; } /** * Check if a given scope is present in this set of scopes. * @param scope */ containsScope(scope) { const lowerCaseScopes = this.printScopesLowerCase().split(" "); const lowerCaseScopesSet = new ScopeSet(lowerCaseScopes); // compare lowercase scopes return scope ? lowerCaseScopesSet.scopes.has(scope.toLowerCase()) : false; } /** * Check if a set of scopes is present in this set of scopes. * @param scopeSet */ containsScopeSet(scopeSet) { if (!scopeSet || scopeSet.scopes.size <= 0) { return false; } return (this.scopes.size >= scopeSet.scopes.size && scopeSet.asArray().every((scope) => this.containsScope(scope))); } /** * Check if set of scopes contains only the defaults */ containsOnlyOIDCScopes() { let defaultScopeCount = 0; OIDC_SCOPES.forEach((defaultScope) => { if (this.containsScope(defaultScope)) { defaultScopeCount += 1; } }); return this.scopes.size === defaultScopeCount; } /** * Appends single scope if passed * @param newScope */ appendScope(newScope) { if (newScope) { this.scopes.add(newScope.trim()); } } /** * Appends multiple scopes if passed * @param newScopes */ appendScopes(newScopes) { try { newScopes.forEach((newScope) => this.appendScope(newScope)); } catch (e) { throw createClientAuthError(cannotAppendScopeSet); } } /** * Removes element from set of scopes. * @param scope */ removeScope(scope) { if (!scope) { throw createClientAuthError(cannotRemoveEmptyScope); } this.scopes.delete(scope.trim()); } /** * Removes default scopes from set of scopes * Primarily used to prevent cache misses if the default scopes are not returned from the server */ removeOIDCScopes() { OIDC_SCOPES.forEach((defaultScope) => { this.scopes.delete(defaultScope); }); } /** * Combines an array of scopes with the current set of scopes. * @param otherScopes */ unionScopeSets(otherScopes) { if (!otherScopes) { throw createClientAuthError(emptyInputScopeSet); } const unionScopes = new Set(); // Iterator in constructor not supported in IE11 otherScopes.scopes.forEach((scope) => unionScopes.add(scope.toLowerCase())); this.scopes.forEach((scope) => unionScopes.add(scope.toLowerCase())); return unionScopes; } /** * Check if scopes intersect between this set and another. * @param otherScopes */ intersectingScopeSets(otherScopes) { if (!otherScopes) { throw createClientAuthError(emptyInputScopeSet); } // Do not allow OIDC scopes to be the only intersecting scopes if (!otherScopes.containsOnlyOIDCScopes()) { otherScopes.removeOIDCScopes(); } const unionScopes = this.unionScopeSets(otherScopes); const sizeOtherScopes = otherScopes.getScopeCount(); const sizeThisScopes = this.getScopeCount(); const sizeUnionScopes = unionScopes.size; return sizeUnionScopes < sizeThisScopes + sizeOtherScopes; } /** * Returns size of set of scopes. */ getScopeCount() { return this.scopes.size; } /** * Returns the scopes as an array of string values */ asArray() { const array = []; this.scopes.forEach((val) => array.push(val)); return array; } /** * Prints scopes into a space-delimited string */ printScopes() { if (this.scopes) { const scopeArr = this.asArray(); return scopeArr.join(" "); } return ""; } /** * Prints scopes into a space-delimited lower-case string (used for caching) */ printScopesLowerCase() { return this.printScopes().toLowerCase(); } } /*! @azure/msal-common v16.0.3 2026-01-28 */ /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ function instrumentBrokerParams(parameters, correlationId, performanceClient) { if (!correlationId) { return; } const clientId = parameters.get(CLIENT_ID); if (clientId && parameters.has(BROKER_CLIENT_ID)) { performanceClient?.addFields({ embeddedClientId: clientId, embeddedRedirectUri: parameters.get(REDIRECT_URI), }, correlationId); } } /** * Add the given response_type * @param parameters * @param responseType */ function addResponseType(parameters, responseType) { parameters.set(RESPONSE_TYPE, responseType); } /** * add response_mode. defaults to query. * @param responseMode */ function addResponseMode(parameters, responseMode) { parameters.set(RESPONSE_MODE, responseMode ? responseMode : ResponseMode$1.QUERY); } /** * add scopes. set addOidcScopes to false to prevent default scopes in non-user scenarios * @param scopeSet * @param addOidcScopes */ function addScopes(parameters, scopes, addOidcScopes = true, defaultScopes = OIDC_DEFAULT_SCOPES) { // Always add openid to the scopes when adding OIDC scopes if (addOidcScopes && !defaultScopes.includes("openid") && !scopes.includes("openid")) { defaultScopes.push("openid"); } const requestScopes = addOidcScopes ? [...(scopes || []), ...defaultScopes] : scopes || []; const scopeSet = new ScopeSet(requestScopes); parameters.set(SCOPE, scopeSet.printScopes()); } /** * add clientId * @param clientId */ function addClientId(parameters, clientId) { parameters.set(CLIENT_ID, clientId); } /** * add redirect_uri * @param redirectUri */ function addRedirectUri(parameters, redirectUri) { parameters.set(REDIRECT_URI, redirectUri); } /** * add post logout redirectUri * @param redirectUri */ function addPostLogoutRedirectUri(parameters, redirectUri) { parameters.set(POST_LOGOUT_URI, redirectUri); } /** * add id_token_hint to logout request * @param idTokenHint */ function addIdTokenHint(parameters, idTokenHint) { parameters.set(ID_TOKEN_HINT, idTokenHint); } /** * add domain_hint * @param domainHint */ function addDomainHint(parameters, domainHint) { parameters.set(DOMAIN_HINT, domainHint); } /** * add login_hint * @param loginHint */ function addLoginHint(parameters, loginHint) { parameters.set(LOGIN_HINT, loginHint); } /** * Adds the CCS (Cache Credential Service) query parameter for login_hint * @param loginHint */ function addCcsUpn(parameters, loginHint) { parameters.set(HeaderNames.CCS_HEADER, `UPN:${loginHint}`); } /** * Adds the CCS (Cache Credential Service) query parameter for account object * @param loginHint */ function addCcsOid(parameters, clientInfo) { parameters.set(HeaderNames.CCS_HEADER, `Oid:${clientInfo.uid}@${clientInfo.utid}`); } /** * add sid * @param sid */ function addSid(parameters, sid) { parameters.set(SID, sid); } /** * add claims * @param claims */ function addClaims(parameters, claims, clientCapabilities) { const mergedClaims = addClientCapabilitiesToClaims(claims, clientCapabilities); try { JSON.parse(mergedClaims); } catch (e) { throw createClientConfigurationError(invalidClaims); } parameters.set(CLAIMS, mergedClaims); } /** * add correlationId * @param correlationId */ function addCorrelationId(parameters, correlationId) { parameters.set(CLIENT_REQUEST_ID, correlationId); } /** * add library info query params * @param libraryInfo */ function addLibraryInfo(parameters, libraryInfo) { // Telemetry Info parameters.set(X_CLIENT_SKU, libraryInfo.sku); parameters.set(X_CLIENT_VER, libraryInfo.version); if (libraryInfo.os) { parameters.set(X_CLIENT_OS, libraryInfo.os); } if (libraryInfo.cpu) { parameters.set(X_CLIENT_CPU, libraryInfo.cpu); } } /** * Add client telemetry parameters * @param appTelemetry */ function addApplicationTelemetry(parameters, appTelemetry) { if (appTelemetry?.appName) { parameters.set(X_APP_NAME, appTelemetry.appName); } if (appTelemetry?.appVersion) { parameters.set(X_APP_VER, appTelemetry.appVersion); } } /** * add prompt * @param prompt */ function addPrompt(parameters, prompt) { parameters.set(PROMPT, prompt); } /** * add state * @param state */ function addState(parameters, state) { if (state) { parameters.set(STATE, state); } } /** * add nonce * @param nonce */ function addNonce(parameters, nonce) { parameters.set(NONCE, nonce); } /** * add code_challenge and code_challenge_method * - throw if either of them are not passed * @param codeChallenge * @param codeChallengeMethod */ function addCodeChallengeParams(parameters, codeChallenge, codeChallengeMethod) { if (codeChallenge && codeChallengeMethod) { parameters.set(CODE_CHALLENGE, codeChallenge); parameters.set(CODE_CHALLENGE_METHOD, codeChallengeMethod); } else { throw createClientConfigurationError(pkceParamsMissing); } } /** * add the `authorization_code` passed by the user to exchange for a token * @param code */ function addAuthorizationCode(parameters, code) { parameters.set(CODE, code); } /** * add the `authorization_code` passed by the user to exchange for a token * @param code */ function addDeviceCode(parameters, code) { parameters.set(DEVICE_CODE, code); } /** * add the `refreshToken` passed by the user * @param refreshToken */ function addRefreshToken(parameters, refreshToken) { parameters.set(REFRESH_TOKEN, refreshToken); } /** * add the `code_verifier` passed by the user to exchange for a token * @param codeVerifier */ function addCodeVerifier(parameters, codeVerifier) { parameters.set(CODE_VERIFIER, codeVerifier); } /** * add client_secret * @param clientSecret */ function addClientSecret(parameters, clientSecret) { parameters.set(CLIENT_SECRET, clientSecret); } /** * add clientAssertion for confidential client flows * @param clientAssertion */ function addClientAssertion(parameters, clientAssertion) { if (clientAssertion) { parameters.set(CLIENT_ASSERTION, clientAssertion); } } /** * add clientAssertionType for confidential client flows * @param clientAssertionType */ function addClientAssertionType(parameters, clientAssertionType) { if (clientAssertionType) { parameters.set(CLIENT_ASSERTION_TYPE, clientAssertionType); } } /** * add OBO assertion for confidential client flows * @param clientAssertion */ function addOboAssertion(parameters, oboAssertion) { parameters.set(OBO_ASSERTION, oboAssertion); } /** * add grant type * @param grantType */ function addRequestTokenUse(parameters, tokenUse) { parameters.set(REQUESTED_TOKEN_USE, tokenUse); } /** * add grant type * @param grantType */ function addGrantType(parameters, grantType) { parameters.set(GRANT_TYPE, grantType); } /** * add client info * */ function addClientInfo(parameters) { parameters.set(CLIENT_INFO, "1"); } function addInstanceAware(parameters) { if (!parameters.has(INSTANCE_AWARE)) { parameters.set(INSTANCE_AWARE, "true"); } } /** * Add extraParameters * @param extraParams - String dictionary containing extra parameters to be added. */ function addExtraParameters(parameters, extraParams) { Object.entries(extraParams).forEach(([key, value]) => { if (!parameters.has(key) && value) { parameters.set(key, value); } }); } function addClientCapabilitiesToClaims(claims, clientCapabilities) { let mergedClaims; // Parse provided claims into JSON object or initialize empty object if (!claims) { mergedClaims = {}; } else { try { mergedClaims = JSON.parse(claims); } catch (e) { throw createClientConfigurationError(invalidClaims); } } if (clientCapabilities && clientCapabilities.length > 0) { if (!mergedClaims.hasOwnProperty(ClaimsRequestKeys.ACCESS_TOKEN)) { // Add access_token key to claims object mergedClaims[ClaimsRequestKeys.ACCESS_TOKEN] = {}; } // Add xms_cc claim with provided clientCapabilities to access_token key mergedClaims[ClaimsRequestKeys.ACCESS_TOKEN][ClaimsRequestKeys.XMS_CC] = { values: clientCapabilities, }; } return JSON.stringify(mergedClaims); } /** * adds `username` for Password Grant flow * @param username */ function addUsername(parameters, username) { parameters.set(PasswordGrantConstants.username, username); } /** * adds `password` for Password Grant flow * @param password */ function addPassword(parameters, password) { parameters.set(PasswordGrantConstants.password, password); } /** * add pop_jwk to query params * @param cnfString */ function addPopToken(parameters, cnfString) { if (cnfString) { parameters.set(TOKEN_TYPE, AuthenticationScheme.POP); parameters.set(REQ_CNF, cnfString); } } /** * add SSH JWK and key ID to query params */ function addSshJwk(parameters, sshJwkString) { if (sshJwkString) { parameters.set(TOKEN_TYPE, AuthenticationScheme.SSH); parameters.set(REQ_CNF, sshJwkString); } } /** * add server telemetry fields * @param serverTelemetryManager */ function addServerTelemetry(parameters, serverTelemetryManager) { parameters.set(X_CLIENT_CURR_TELEM, serverTelemetryManager.generateCurrentRequestHeaderValue()); parameters.set(X_CLIENT_LAST_TELEM, serverTelemetryManager.generateLastRequestHeaderValue()); } /** * Adds parameter that indicates to the server that throttling is supported */ function addThrottling(parameters) { parameters.set(X_MS_LIB_CAPABILITY, X_MS_LIB_CAPABILITY_VALUE); } /** * Adds logout_hint parameter for "silent" logout which prevent server account picker */ function addLogoutHint(parameters, logoutHint) { parameters.set(LOGOUT_HINT, logoutHint); } function addBrokerParameters(parameters, brokerClientId, brokerRedirectUri) { if (!parameters.has(BROKER_CLIENT_ID)) { parameters.set(BROKER_CLIENT_ID, brokerClientId); } if (!parameters.has(BROKER_REDIRECT_URI)) { parameters.set(BROKER_REDIRECT_URI, brokerRedirectUri); } } /*! @azure/msal-common v16.0.3 2026-01-28 */ /** * Parses hash string from given string. Returns empty string if no hash symbol is found. * @param hashString */ function stripLeadingHashOrQuery(responseString) { if (responseString.startsWith("#/")) { return responseString.substring(2); } else if (responseString.startsWith("#") || responseString.startsWith("?")) { return responseString.substring(1); } return responseString; } /** * Returns URL hash as server auth code response object. */ function getDeserializedResponse(responseString) { // Check if given hash is empty if (!responseString || responseString.indexOf("=") < 0) { return null; } try { // Strip the # or ? symbol if present const normalizedResponse = stripLeadingHashOrQuery(responseString); // If # symbol was not present, above will return empty string, so give original hash value const deserializedHash = Object.fromEntries(new URLSearchParams(normalizedResponse)); // Check for known response properties if (deserializedHash.code || deserializedHash.ear_jwe || deserializedHash.error || deserializedHash.error_description || deserializedHash.state) { return deserializedHash; } } catch (e) { throw createClientAuthError(hashNotDeserialized); } return null; } /** * Utility to create a URL from the params map */ function mapToQueryString(parameters) { const queryParameterArray = new Array(); parameters.forEach((value, key) => { queryParameterArray.push(`${key}=${encodeURIComponent(value)}`); }); return queryParameterArray.join("&"); } /*! @azure/msal-common v16.0.3 2026-01-28 */ /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ const DEFAULT_CRYPTO_IMPLEMENTATION = { createNewGuid: () => { throw createClientAuthError(methodNotImplemented); }, base64Decode: () => { throw createClientAuthError(methodNotImplemented); }, base64Encode: () => { throw createClientAuthError(methodNotImplemented); }, base64UrlEncode: () => { throw createClientAuthError(methodNotImplemented); }, encodeKid: () => { throw createClientAuthError(methodNotImplemented); }, async getPublicKeyThumbprint() { throw createClientAuthError(methodNotImplemented); }, async removeTokenBindingKey() { throw createClientAuthError(methodNotImplemented); }, async clearKeystore() { throw createClientAuthError(methodNotImplemented); }, async signJwt() { throw createClientAuthError(methodNotImplemented); }, async hashString() { throw createClientAuthError(methodNotImplemented); }, }; /*! @azure/msal-common v16.0.3 2026-01-28 */ /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ /** * Log message level. */ exports.LogLevel = void 0; (function (LogLevel) { LogLevel[LogLevel["Error"] = 0] = "Error"; LogLevel[LogLevel["Warning"] = 1] = "Warning"; LogLevel[LogLevel["Info"] = 2] = "Info"; LogLevel[LogLevel["Verbose"] = 3] = "Verbose"; LogLevel[LogLevel["Trace"] = 4] = "Trace"; })(exports.LogLevel || (exports.LogLevel = {})); // Shared cache state for better minification - using Map's insertion order for LRU const CACHE_CAPACITY = 50; const MAX_LOGS_PER_CORRELATION = 500; const correlationCache = new Map(); /** * Mark correlation ID as recently used by moving it to end of Map * @param correlationId * @param {CorrelationLogData} data */ function markAsRecentlyUsed(correlationId, data) { correlationCache.delete(correlationId); correlationCache.set(correlationId, data); } /** * Add log message to cache for specific correlation ID * @param correlationId * @param {LoggedMessage} loggedMessage */ function addLogToCache(correlationId, loggedMessage) { const currentTime = Date.now(); let data = correlationCache.get(correlationId); if (data) { // Mark as recently used markAsRecentlyUsed(correlationId, data); } else { // Create new entry data = { logs: [], firstEventTime: currentTime }; correlationCache.set(correlationId, data); // Remove LRU (first entry) if capacity exceeded if (correlationCache.size > CACHE_CAPACITY) { const firstKey = correlationCache.keys().next().value; if (firstKey) { correlationCache.delete(firstKey); } } } // Add log to the data, maintaining max logs per correlation data.logs.push({ ...loggedMessage, milliseconds: currentTime - data.firstEventTime, }); if (data.logs.length > MAX_LOGS_PER_CORRELATION) { data.logs.shift(); // Remove oldest log } } /** * Checks if a string is already a hashed logging string (6 alphanumeric characters) */ function isHashedString(str) { if (str.length !== 6) { return false; } for (let i = 0; i < str.length; i++) { const char = str[i];