@azure/msal-browser
Version:
Microsoft Authentication Library for js
27,157 lines • 1.18 MB
JavaScript
/*! @azure/msal-browser v5.25.0 2026-10-06 */
'use strict';
'use strict';
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* 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 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 DPOP_JKT = "dpop_jkt";
const RETURN_SPA_CODE = "return_spa_code";
const NATIVE_BROKER = "nativebroker";
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";
const EAR_JWK = "ear_jwk";
const EAR_JWE_CRYPTO = "ear_jwe_crypto";
const RESOURCE = "resource";
const CLI_DATA = "clidata";
const ATTRIBUTE_TOKENS = "attribute_tokens";
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* 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";
// 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 S256_CODE_CHALLENGE_METHOD = "S256";
const URL_FORM_CONTENT_TYPE = "application/x-www-form-urlencoded;charset=utf-8";
const NOT_APPLICABLE = "N/A";
const NOT_AVAILABLE = "Not Available";
const FORWARD_SLASH = "/";
const IMDS_ENDPOINT = "http://169.254.169.254/metadata/instance/compute";
const IMDS_VERSION = "2021-02-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 SHR_NONCE_VALIDITY = 240;
const INVALID_INSTANCE = "invalid_instance";
const HTTP_SUCCESS = 200;
const HTTP_CLIENT_ERROR_RANGE_START = 400;
const HTTP_BAD_REQUEST = 400;
const HTTP_CLIENT_ERROR_RANGE_END = 499;
const HTTP_SERVER_ERROR_RANGE_START = 500;
const HTTP_SERVER_ERROR_RANGE_END = 599;
const HttpMethod$1 = {
GET: "GET",
POST: "POST",
};
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",
DPOP: "DPoP",
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",
};
/**
* Persistent cache keys MSAL which stay while user is logged in.
*/
const PersistentCacheKeys = {
ACTIVE_ACCOUNT_FILTERS: "active-account-filters", // new cache entry for active_account for a more robust version for browser
};
/**
* 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",
ID_TOKEN: "id_token",
SIGNIN_STATE: "signin_state",
LOGIN_HINT: "login_hint",
TENANT_REGION_SUB_SCOPE: "tenant_region_sub_scope",
};
/**
* 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 = {
LOGIN: "login",
SELECT_ACCOUNT: "select_account",
CONSENT: "consent",
NONE: "none",
NO_SESSION: "no_session",
};
/**
* Allowed values for response_type
*/
const OAuthResponseType = {
CODE: "code",
IDTOKEN_TOKEN_REFRESHTOKEN: "id_token token refresh_token",
};
/**
* allowed values for response_mode
*/
const ResponseMode = {
QUERY: "query",
FRAGMENT: "fragment"};
/**
* allowed grant_type
*/
const GrantType$1 = {
AUTHORIZATION_CODE_GRANT: "authorization_code",
REFRESH_TOKEN_GRANT: "refresh_token"};
/**
* 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$1 = "-";
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",
DPOP: "DPoP",
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";
/**
* 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",
};
const JsonWebTokenTypes = {
Pop: "pop",
Dpop: "dpop+jwt",
};
// Token renewal offset default in seconds
const DEFAULT_TOKEN_RENEWAL_OFFSET_SEC = 300;
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
function getDefaultErrorMessage$1(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, correlationId, errorMessage, suberror) {
const message = errorMessage ||
(errorCode ? getDefaultErrorMessage$1(errorCode) : "");
const errorString = message ? `${errorCode}: ${message}` : errorCode;
super(errorString);
Object.setPrototypeOf(this, AuthError.prototype);
this.errorCode = errorCode || "";
this.errorMessage = message || "";
this.subError = suberror || "";
this.correlationId = correlationId;
this.name = "AuthError";
}
}
function createAuthError(code, correlationId, additionalMessage) {
return new AuthError(code, correlationId, additionalMessage || getDefaultErrorMessage$1(code));
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* 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, correlationId, additionalMessage) {
super(errorCode, correlationId, additionalMessage);
this.name = "ClientAuthError";
Object.setPrototypeOf(this, ClientAuthError.prototype);
}
}
function createClientAuthError(errorCode, correlationId, additionalMessage) {
return new ClientAuthError(errorCode, correlationId, additionalMessage);
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* 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 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 dpopTokenTypeMismatch = "dpop_token_type_mismatch";
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 methodNotImplemented = "method_not_implemented";
const resourceParameterRequired = "resource_parameter_required";
const misplacedResourceParam = "misplaced_resource_parameter";
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Function to build a client info object from server clientInfo string
* @param rawClientInfo
* @param crypto
*/
function buildClientInfo(rawClientInfo, base64Decode) {
if (!rawClientInfo) {
throw createClientAuthError(clientInfoEmptyError, "");
}
try {
const decodedClientInfo = base64Decode(rawClientInfo);
return JSON.parse(decodedClientInfo);
}
catch (e) {
throw createClientAuthError(clientInfoDecodingError, "");
}
}
/**
* Function to build a client info object from cached homeAccountId string
* @param homeAccountId
*/
function buildClientInfoFromHomeAccountId(homeAccountId) {
if (!homeAccountId) {
throw createClientAuthError(clientInfoDecodingError, "");
}
const clientInfoParts = homeAccountId.split(CLIENT_INFO_SEPARATOR, 2);
return {
uid: clientInfoParts[0],
utid: clientInfoParts.length < 2 ? "" : clientInfoParts[1],
};
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Extract token by decoding the rawToken
*
* @param encodedToken
*/
function extractTokenClaims(encodedToken, base64Decode, correlationId) {
const jswPayload = getJWSPayload(encodedToken, correlationId);
// token will be decoded to get the username
try {
// base64Decode() should throw an error if there is an issue
const base64Decoded = base64Decode(jswPayload);
return JSON.parse(base64Decoded);
}
catch (err) {
throw createClientAuthError(tokenParsingError, correlationId);
}
}
/**
* Check if the signin_state claim contains "kmsi"
* @param idTokenClaims
* @returns
*/
function isKmsi(idTokenClaims) {
if (!idTokenClaims.signin_state) {
return false;
}
/**
* Signin_state claim known values:
* dvc_mngd - device is managed
* dvc_dmjd - device is domain joined
* kmsi - user opted to "keep me signed in"
* inknownntwk - Request made inside a known network. Don't use this, use CAE instead.
*/
const kmsiClaims = ["kmsi", "dvc_dmjd"]; // There are some cases where kmsi may not be returned but persistent storage is still OK - allow dvc_dmjd as well
return idTokenClaims.signin_state.some((value) => kmsiClaims.includes(value.trim().toLowerCase()));
}
/**
* decode a JWT
*
* @param authToken
*/
function getJWSPayload(authToken, correlationId) {
if (!authToken) {
throw createClientAuthError(nullOrEmptyToken, correlationId);
}
const tokenPartsRegex = /^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/;
const matches = tokenPartsRegex.exec(authToken);
if (!matches || matches.length < 4) {
throw createClientAuthError(tokenParsingError, correlationId);
}
/**
* const crackedToken = {
* header: matches[1],
* JWSPayload: matches[2],
* JWSSig: matches[3],
* };
*/
return matches[2];
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Returns true if tenantId matches the utid portion of homeAccountId
* @param tenantId
* @param homeAccountId
* @returns
*/
function tenantIdMatchesHomeTenant(tenantId, homeAccountId) {
return (!!tenantId &&
!!homeAccountId &&
tenantId === homeAccountId.split(".")[1]);
}
/**
* Build tenant profile
* @param homeAccountId - Home account identifier for this account object
* @param localAccountId - Local account identifer for this account object
* @param tenantId - Full tenant or organizational id that this account belongs to
* @param nativeAccountId - Native account identifier for this tenant
* @param idTokenClaims - Claims from the ID token
* @returns
*/
function buildTenantProfile(homeAccountId, localAccountId, tenantId, nativeAccountId, idTokenClaims) {
if (idTokenClaims) {
const { oid, sub, tid, name, tfp, acr, preferred_username, upn, login_hint, } = idTokenClaims;
/**
* Since there is no way to determine if the authority is AAD or B2C, we exhaust all the possible claims that can serve as tenant ID with the following precedence:
* tid - TenantID claim that identifies the tenant that issued the token in AAD. Expected in all AAD ID tokens, not present in B2C ID Tokens.
* tfp - Trust Framework Policy claim that identifies the policy that was used to authenticate the user. Functions as tenant for B2C scenarios.
* acr - Authentication Context Class Reference claim used only with older B2C policies. Fallback in case tfp is not present, but likely won't be present anyway.
*/
const tenantId = tid || tfp || acr || "";
return {
tenantId: tenantId,
localAccountId: oid || sub || "",
name: name,
username: preferred_username || upn || "",
loginHint: login_hint,
isHomeTenant: tenantIdMatchesHomeTenant(tenantId, homeAccountId),
upn: upn,
...(nativeAccountId && { nativeAccountId }),
};
}
else {
return {
tenantId,
localAccountId,
username: "",
isHomeTenant: tenantIdMatchesHomeTenant(tenantId, homeAccountId),
...(nativeAccountId && { nativeAccountId }),
};
}
}
/**
* Replaces account info that varies by tenant profile sourced from the ID token claims passed in with the tenant-specific account info
* @param baseAccountInfo
* @param idTokenClaims
* @returns
*/
function updateAccountTenantProfileData(baseAccountInfo, tenantProfile, idTokenClaims, idTokenSecret) {
let updatedAccountInfo = baseAccountInfo;
// Tenant Profile overrides passed in account info
if (tenantProfile) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { isHomeTenant, ...tenantProfileOverride } = tenantProfile;
updatedAccountInfo = { ...baseAccountInfo, ...tenantProfileOverride };
}
// ID token claims override passed in account info and tenant profile
if (idTokenClaims) {
// Ignore isHomeTenant which is a utility property of tenant profile but not required in base account info
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { isHomeTenant, ...claimsSourcedTenantProfile } = buildTenantProfile(baseAccountInfo.homeAccountId, baseAccountInfo.localAccountId, baseAccountInfo.tenantId, updatedAccountInfo.nativeAccountId, idTokenClaims);
updatedAccountInfo = {
...updatedAccountInfo,
...claimsSourcedTenantProfile,
idTokenClaims: idTokenClaims,
idToken: idTokenSecret,
kmsi: isKmsi(idTokenClaims),
};
return updatedAccountInfo;
}
return updatedAccountInfo;
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Authority types supported by MSAL.
*/
const AuthorityType = {
Default: 0,
Adfs: 1,
Ciam: 3,
};
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Gets tenantId from available ID token claims to set as credential realm with the following precedence:
* 1. tid - if the token is acquired from an Azure AD tenant tid will be present
* 2. tfp - if the token is acquired from a modern B2C tenant tfp should be present
* 3. acr - if the token is acquired from a legacy B2C tenant acr should be present
* Downcased to match the realm case-insensitive comparison requirements
* @param idTokenClaims
* @returns
*/
function getTenantIdFromIdTokenClaims(idTokenClaims) {
if (idTokenClaims) {
const tenantId = idTokenClaims.tid || idTokenClaims.tfp || idTokenClaims.acr;
return tenantId || null;
}
return null;
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Protocol modes supported by MSAL.
*/
const ProtocolMode = {
/**
* Auth Code + PKCE with Entra ID (formerly AAD) specific optimizations and features
*/
AAD: "AAD",
/**
* Auth Code + PKCE without Entra ID specific optimizations and features. For use only with non-Microsoft owned authorities.
* Support is limited for this mode.
*/
OIDC: "OIDC",
/**
* Encrypted Authorize Response (EAR) with Entra ID specific optimizations and features
*/
EAR: "EAR",
};
/*! @azure/msal-common v16.14.2 2026-10-06 */
/**
* Returns the AccountInfo interface for this account.
* @internal
*/
function getAccountInfo(accountEntity) {
const tenantProfiles = accountEntity.tenantProfiles || [];
// Ensure at least the home tenant profile exists
if (tenantProfiles.length === 0 &&
accountEntity.realm &&
accountEntity.localAccountId) {
tenantProfiles.push(buildTenantProfile(accountEntity.homeAccountId, accountEntity.localAccountId, accountEntity.realm, accountEntity.nativeAccountId));
}
// Resolve nativeAccountId from the home tenant profile first, fall back to top-level (deprecated) for old cache entries
const homeTenantProfile = tenantProfiles.find((tp) => tp.tenantId === accountEntity.realm);
const nativeAccountId = homeTenantProfile?.nativeAccountId || accountEntity.nativeAccountId;
return {
homeAccountId: accountEntity.homeAccountId,
environment: accountEntity.environment,
tenantId: accountEntity.realm,
username: accountEntity.username,
localAccountId: accountEntity.localAccountId,
loginHint: accountEntity.loginHint,
name: accountEntity.name,
nativeAccountId: nativeAccountId,
authorityType: accountEntity.authorityType,
// Deserialize tenant profiles array into a Map
tenantProfiles: new Map(tenantProfiles.map((tenantProfile) => {
return [tenantProfile.tenantId, tenantProfile];
})),
dataBoundary: accountEntity.dataBoundary,
};
}
/**
* Build Account cache from IdToken, clientInfo and authority/policy. Associated with AAD.
* @param accountDetails
* @internal
*/
function createAccountEntity(accountDetails, authority, correlationId, base64Decode) {
let authorityType;
if (authority.authorityType === AuthorityType.Adfs) {
authorityType = CACHE_ACCOUNT_TYPE_ADFS;
}
else if (authority.protocolMode === ProtocolMode.OIDC) {
authorityType = CACHE_ACCOUNT_TYPE_GENERIC;
}
else {
authorityType = CACHE_ACCOUNT_TYPE_MSSTS;
}
let clientInfo;
let dataBoundary;
if (accountDetails.clientInfo && base64Decode) {
clientInfo = buildClientInfo(accountDetails.clientInfo, base64Decode);
if (clientInfo.xms_tdbr) {
dataBoundary = clientInfo.xms_tdbr === "EU" ? "EU" : "None";
}
}
const env = accountDetails.environment ||
(authority && authority.getPreferredCache());
if (!env) {
throw createClientAuthError(invalidCacheEnvironment, correlationId);
}
/*
* In B2C scenarios the emails claim is used instead of preferred_username and it is an array.
* In most cases it will contain a single email. This field should not be relied upon if a custom
* policy is configured to return more than 1 email.
*/
const preferredUsername = accountDetails.idTokenClaims?.preferred_username ||
accountDetails.idTokenClaims?.upn;
const email = accountDetails.idTokenClaims?.emails
? accountDetails.idTokenClaims.emails[0]
: null;
const username = preferredUsername || email || "";
const loginHint = accountDetails.idTokenClaims?.login_hint;
const realm = clientInfo?.utid ||
getTenantIdFromIdTokenClaims(accountDetails.idTokenClaims) ||
""; // non-AAD scenarios can have empty realm
// How do you account for MSA CID here?
const localAccountId = clientInfo?.uid ||
accountDetails.idTokenClaims?.oid ||
accountDetails.idTokenClaims?.sub ||
"";
let tenantProfiles;
if (accountDetails.tenantProfiles) {
tenantProfiles = accountDetails.tenantProfiles;
}
else {
const tenantProfile = buildTenantProfile(accountDetails.homeAccountId, localAccountId, realm, accountDetails.nativeAccountId, accountDetails.idTokenClaims);
tenantProfiles = [tenantProfile];
}
return {
homeAccountId: accountDetails.homeAccountId,
environment: env,
realm: realm,
localAccountId: localAccountId,
username: username,
authorityType: authorityType,
loginHint: loginHint,
clientInfo: accountDetails.clientInfo,
name: accountDetails.idTokenClaims?.name || "",
lastModificationTime: undefined,
lastModificationApp: undefined,
cloudGraphHostName: accountDetails.cloudGraphHostName,
msGraphHost: accountDetails.msGraphHost,
nativeAccountId: accountDetails.nativeAccountId,
tenantProfiles: tenantProfiles,
dataBoundary,
};
}
/**
* Creates an AccountEntity object from AccountInfo
* @param accountInfo
* @param cloudGraphHostName
* @param msGraphHost
* @returns
* @internal
*/
function createAccountEntityFromAccountInfo(accountInfo, cloudGraphHostName, msGraphHost) {
// Serialize tenant profiles map into an array
const tenantProfiles = Array.from(accountInfo.tenantProfiles?.values() || []);
// Ensure at least the home tenant profile exists
if (tenantProfiles.length === 0 &&
accountInfo.tenantId &&
accountInfo.localAccountId) {
tenantProfiles.push(buildTenantProfile(accountInfo.homeAccountId, accountInfo.localAccountId, accountInfo.tenantId, accountInfo.nativeAccountId, accountInfo.idTokenClaims));
}
else if (accountInfo.nativeAccountId) {
// Ensure nativeAccountId is set on the matching tenant profile
const matchingProfile = tenantProfiles.find((tp) => tp.tenantId === accountInfo.tenantId);
if (matchingProfile && !matchingProfile.nativeAccountId) {
matchingProfile.nativeAccountId = accountInfo.nativeAccountId;
}
}
return {
authorityType: accountInfo.authorityType || CACHE_ACCOUNT_TYPE_GENERIC,
homeAccountId: accountInfo.homeAccountId,
localAccountId: accountInfo.localAccountId,
nativeAccountId: accountInfo.nativeAccountId,
realm: accountInfo.tenantId,
environment: accountInfo.environment,
username: accountInfo.username,
loginHint: accountInfo.loginHint,
name: accountInfo.name,
cloudGraphHostName: cloudGraphHostName,
msGraphHost: msGraphHost,
tenantProfiles: tenantProfiles,
dataBoundary: accountInfo.dataBoundary,
};
}
/**
* Generate HomeAccountId from server response
* @param serverClientInfo
* @param authType
*/
function generateHomeAccountId(serverClientInfo, authType, logger, cryptoObj, correlationId, idTokenClaims) {
// ADFS does not have tid and does not set client_info
if (authType !== AuthorityType.Adfs) {
// for cases where there is clientInfo
if (serverClientInfo) {
try {
const clientInfo = buildClientInfo(serverClientInfo, cryptoObj.base64Decode);
if (clientInfo.uid && clientInfo.utid) {
return `${clientInfo.uid}.${clientInfo.utid}`;
}
}
catch (e) { }
}
logger.warning("1ub6wv", correlationId);
}
// default to "sub" claim
return idTokenClaims?.sub || "";
}
/**
* Validates an entity: checks for all expected params
* @param entity
* @internal
*/
function isAccountEntity(entity) {
if (!entity) {
return false;
}
return (entity.hasOwnProperty("homeAccountId") &&
entity.hasOwnProperty("environment") &&
entity.hasOwnProperty("realm") &&
entity.hasOwnProperty("localAccountId") &&
entity.hasOwnProperty("username") &&
entity.hasOwnProperty("authorityType"));
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* AuthErrorMessage class containing string constants used by error codes and messages.
*/
const unexpectedError = "unexpected_error";
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* 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, correlationId) {
super(errorCode, correlationId);
this.name = "ClientConfigurationError";
Object.setPrototypeOf(this, ClientConfigurationError.prototype);
}
}
function createClientConfigurationError(errorCode, correlationId) {
return new ClientConfigurationError(errorCode, correlationId);
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const redirectUriEmpty = "redirect_uri_empty";
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 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 unsupportedAuthenticationScheme = "unsupported_authentication_scheme";
const cannotSetOIDCOptions = "cannot_set_OIDCOptions";
const cannotAllowPlatformBroker = "cannot_allow_platform_broker";
const authorityMismatch = "authority_mismatch";
const invalidRequestMethodForEAR = "invalid_request_method_for_EAR";
const invalidPlatformBrokerConfiguration = "invalid_platform_broker_configuration";
const issuerValidationFailed = "issuer_validation_failed";
const invalidDpopHtm = "invalid_dpop_htm";
const invalidDpopHtu = "invalid_dpop_htu";
const invalidDpopNonce = "invalid_dpop_nonce";
const dpopMissingResourceContext = "dpop_missing_resource_context";
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
function isOpenIdConfigResponse(response) {
return (response.hasOwnProperty("authorization_endpoint") &&
response.hasOwnProperty("token_endpoint") &&
response.hasOwnProperty("issuer") &&
response.hasOwnProperty("jwks_uri"));
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* 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;
}
}
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Url object class which can perform various transformations on url strings.
*/
class UrlString {
get urlString() {
return this._urlString;
}
constructor(url, correlationId) {
this._urlString = url;
this.correlationId = correlationId;
if (!this._urlString) {
// Throws error if url is empty
throw createClientConfigurationError(urlEmptyError, correlationId);
}
if (!url.includes("#")) {
this._urlString = UrlString.canonicalizeUri(url);
}
}
/**
* Ensure urls are lower case and end with a / character.
* @param url
*/
static canonicalizeUri(url) {
if (url) {
let lowerCaseUrl = url.toLowerCase();
if (StringUtils.endsWith(lowerCaseUrl, "?")) {
lowerCaseUrl = lowerCaseUrl.slice(0, -1);
}
else if (StringUtils.endsWith(lowerCaseUrl, "?/")) {
lowerCaseUrl = lowerCaseUrl.slice(0, -2);
}
if (!StringUtils.endsWith(lowerCaseUrl, "/")) {
lowerCaseUrl += "/";
}
return lowerCaseUrl;
}
return url;
}
/**
* Throws if urlString passed is not a valid authority URI string.
*/
validateAsUri() {
// Attempts to parse url for uri components
let components;
try {
components = this.getUrlComponents();
}
catch (e) {
throw createClientConfigurationError(urlParseError, this.correlationId);
}
// Throw error if URI or path segments are not parseable.
if (!components.HostNameAndPort || !components.PathSegments) {
throw createClientConfigurationError(urlParseError, this.correlationId);
}
// Throw error if uri is insecure.
if (!components.Protocol ||
components.Protocol.toLowerCase() !== "https:") {
throw createClientConfigurationError(authorityUriInsecure, this.correlationId);
}
}
/**
* Given a url and a query string return the url with provided query string appended
* @param url
* @param queryString
*/
static appendQueryString(url, queryString) {
if (!queryString) {
return url;
}
return url.indexOf("?") < 0
? `${url}?${queryString}`
: `${url}&${queryString}`;
}
/**
* Returns a url with the hash removed
* @param url
*/
static removeHashFromUrl(url) {
return UrlString.canonicalizeUri(url.split("#")[0]);
}
/**
* Given a url like https://a:b/common/d?e=f#g, and a tenantId, returns https://a:b/tenantId/d
* @param href The url
* @param tenantId The tenant id to replace
*/
replaceTenantPath(tenantId) {
const urlObject = this.getUrlComponents();
const pathArray = urlObject.PathSegments;
if (tenantId &&
pathArray.length !== 0 &&
(pathArray[0] === AADAuthority.COMMON ||
pathArray[0] === AADAuthority.ORGANIZATIONS)) {
pathArray[0] = tenantId;
}
return UrlString.constructAuthorityUriFromObject(urlObject, this.correlationId);
}
/**
* Parses out the components from a url string.
* @returns An object with the various components. Please cache this value insted of calling this multiple times on the same url.
*/
getUrlComponents() {
// https://gist.github.com/curtisz/11139b2cfcaef4a261e0
const regEx = RegExp("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?");
// If url string does not match regEx, we throw an error
const match = this.urlString.match(regEx);
if (!match) {
throw createClientConfigurationError(urlParseError, this.correlationId);
}
// Url component object
const urlComponents = {
Protocol: match[1],
HostNameAndPort: match[4],
AbsolutePath: match[5],
QueryString: match[7],
};
let pathSegments = urlComponents.AbsolutePath.split("/");
pathSegments = pathSegments.filter((val) => val && val.length > 0); // remove empty elements
urlComponents.PathSegments = pathSegments;
if (urlComponents.QueryString &&
urlComponents.QueryString.endsWith("/")) {
urlComponents.QueryString = urlComponents.QueryString.substring(0, urlComponents.QueryString.length - 1);
}
return urlComponents;
}
static getDomainFromUrl(url, correlationId) {
const regEx = RegExp("^([^:/?#]+://)?([^/?#]*)");
const match = url.match(regEx);
if (!match) {
throw createClientConfigurationError(urlParseError, correlationId);
}
return match[2];
}
static getAbsoluteUrl(relativeUrl, baseUrl, correlationId) {
if (relativeUrl[0] === FORWARD_SLASH) {
const url = new UrlString(baseUrl, correlationId);
const baseComponents = url.getUrlComponents();
return (baseComponents.Protocol +
"//" +
baseComponents.HostNameAndPort +
relativeUrl);
}
return relativeUrl;
}
static constructAuthorityUriFromObject(urlObject, correlationId) {
return new UrlString(urlObject.Protocol +
"//" +
urlObject.HostNameAndPort +
"/" +
urlObject.PathSegments.join("/"), correlationId);
}
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
// Build endpoint metadata dynamically to avoid string duplication
const endpointHosts = [
{ host: "login.microsoftonline.com" },
{ host: "login.partner.microsoftonline.cn" },
{ host: "login.microsoftonline.us" },
{ host: "login.sovcloud-identity.fr" },
{ host: "login.sovcloud-identity.de" },
{ host: "login.sovcloud-identity.sg" },
];
function buildOpenIdConfig(host, issuerHost) {
return {
token_endpoint: `https://${host}/{tenantid}/oauth2/v2.0/token`,
jwks_uri: `https://${host}/{tenantid}/discovery/v2.0/keys`,
issuer: `https://${issuerHost}/{tenantid}/v2.0`,
authorization_endpoint: `https://${host}/{tenantid}/oauth2/v2.0/authorize`,
end_session_endpoint: `https://${host}/{tenantid}/oauth2/v2.0/logout`,
};
}
const dynamicEndpointMetadata = endpointHosts.reduce((acc, { host, issuerHost }) => {
acc[host] = buildOpenIdConfig(host, issuerHost || host);
return acc;
}, {});
const rawMetdataJSON = {
endpointMetadata: dynamicEndpointMetadata,
instanceDiscoveryMetadata: {
metadata: [
{
preferred_network: "login.microsoftonline.com",
preferred_cache: "login.windows.net",
aliases: [
"login.microsoftonline.com",
"login.windows.net",
"login.microsoft.com",
"sts.windows.net",
],
},
{
preferred_network: "login.partner.microsoftonline.cn",
preferred_cache: "login.partner.microsoftonline.cn",
aliases: [
"login.partner.microsoftonline.cn",
"login.chinacloudapi.cn",
],
},
{
preferred_network: "login.microsoftonline.de",
preferred_cache: "login.microsoftonline.de",
aliases: ["login.microsoftonline.de"],
},
{
preferred_network: "login.microsoftonline.us",
preferred_cache: "login.microsoftonline.us",
aliases: [
"login.microsoftonline.us",
"login.usgovcloudapi.net",
],
},
{
preferred_network: "login-us.microsoftonline.com",
preferred_cache: "login-us.microsoftonline.com",
aliases: ["login-us.microsoftonline.com"],
},
{
preferred_network: "login.sovcloud-identity.fr",
preferred_cache: "login.sovcloud-identity.fr",
aliases: ["login.sovcloud-identity.fr"],
},
{
preferred_network: "login.sovcloud-identity.de",
preferred_cache: "login.sovcloud-identity.de",
aliases: ["login.sovcloud-identity.de"],
},
{
preferred_network: "login.sovcloud-identity.sg",
preferred_cache: "login.sovcloud-identity.sg",
aliases: ["login.sovcloud-identity.sg"],
},
],
},
};
const EndpointMetadata = rawMetdataJSON.endpointMetadata;
const InstanceDiscoveryMetadata = rawMetdataJSON.instanceDiscoveryMetadata;
const InstanceDiscoveryMetadataAliases = new Set();
InstanceDiscoveryMetadata.metadata.forEach((metadataEntry) => {
metadataEntry.aliases.forEach((alias) => {
InstanceDiscoveryMetadataAliases.add(alias);
});
});
/**
* Attempts to get an aliases array from the static authority metadata sources based on the canonical authority host
* @param staticAuthorityOptions
* @param logger
* @returns
*/
function getAliasesFromStaticSources(staticAuthorityOptions, logger, correlationId) {
let staticAliases;
const canonicalAuthority = staticAuthorityOptions.canonicalAuthority;
if (canonicalAuthority) {
const authorityHost = new UrlString(canonicalAuthority, correlationId).getUrlComponents().HostNameAndPort;
staticAliases =
getAliasesFromMetadata(logger, correlationId, authorityHost, staticAuthorityOptions.cloudDiscoveryMetadata?.metadata, AuthorityMetadataSource.CONFIG) ||
getAliasesFromMetadata(logger, correlationId, authorityHost, InstanceDiscoveryMetadata.metadata, AuthorityMetadataSource.HARDCODED_VALUES) ||
staticAuthorityOptions.knownAuthorities;
}
return staticAliases || [];
}
/**
* Returns aliases for from the raw cloud discovery metadata passed in
* @param authorityHost
* @param rawCloudDiscoveryMetadata
* @returns
*/
function getAliasesFromMetadata(logger, correlationId, authorityHost, cloudDiscoveryMetadata, source) {
logger.trace(`1bmquz ${source}`, correlationId);
if (authorityHost && cloudDiscoveryMetadata) {
const metadata = getCloudDiscoveryMetadataFromNetworkResponse(cloudDiscoveryMetadata, authorityHost);
if (metadata) {
logger.trace(`1fotbt ${source}`, correlationId);
return metadata.aliases;
}
else {
logger.trace(`14avvj ${source}`, correlationId);
}
}
return null;
}
/**
* Get cloud discovery metadata for common authorities
*/
function getCloudDiscoveryMetadataFromHardcodedValues(authorityHost) {
const metadata = getCloudDiscoveryMetadataFromNetworkResponse(InstanceDiscoveryMetadata.metadata, authorityHost);
return metadata;
}
/**
* Searches instance discovery network response for the entry that contains the host in the aliases list
* @param response
* @param authority
*/
function getCloudDiscoveryMetadataFromNetworkResponse(response, authorityHost) {
for (let i = 0; i < response.length; i++) {
const metadata = response[i];
if (metadata.aliases.includes(authorityHost)) {
return metadata;
}
}
return null;
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const AzureCloudInstance = {
// AzureCloudInstance is not specified.
None: "none"};
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
function isCloudInstanceDiscoveryResponse(response) {
return (response.hasOwnProperty("tenant_discovery_endpoint") &&
response.hasOwnProperty("metadata"));
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
function isCloudInstanceDiscoveryErrorResponse(response) {
return (response.hasOwnProperty("error") &&
response.hasOwnProperty("error_description"));
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Time spent sending/waiting for the response of a request to the token endpoint
*/
const NetworkClientSendPostRequestAsync = "networkClientSendPostRequestAsync";
const RefreshTokenClientExecutePostToTokenEndpoint = "refreshTokenClientExecutePostToTokenEndpoint";
const AuthorizationCodeClientExecutePostToTokenEndpoint = "authorizationCodeClientExecutePostToTokenEndpoint";
/**
* Time spent on the network for refresh token acquisition
*/
const RefreshTokenClientExecuteTokenRequest = "refreshTokenClientExecuteTokenRequest";
/**
* Time taken for acquiring refresh token , records RT size
*/
const RefreshTokenClientAcquireToken = "refreshTokenClientAcquireToken";
/**
* Time taken for acquiring cached refresh token
*/
const RefreshTokenClientAcquireTokenWithCachedRefreshToken = "refreshTokenClientAcquireTokenWithCachedRefreshToken";
/**
* Helper function to create token request body in RefreshTokenClient (msal-common).
*/
const RefreshTokenClientCreateTokenRequestBody = "refreshTokenClientCreateTokenRequestBody";
const SilentFlowClientGenerateResultFromCacheRecord = "silentFlowClientGenerateResultFromCacheRecord";
/**
* getAuthCodeUrl API (msal-browser and msal-node).
*/
const GetAuthCodeUrl = "getAuthCodeUrl";
/**
* Functions from InteractionHandler (msal-browser)
*/
const HandleCodeResponseFromServer = "handleCodeResponseFromServer";
/**
* APIs in Authorization Code Client (msal-common)
*/
const AuthClientExecuteTokenRequest = "authClientExecuteTokenRequest";
const AuthClientCreateTokenRequestBody = "authClientCreateTokenRequestBody";
const UpdateTokenEndpointAuthority = "updateTokenEndpointAuthority";
/**
* Generate functions in PopTokenGenerator (msal-common)
*/
const PopTokenGenerateCnf = "popTokenGenerateCnf";
/**
* handleServerTokenResponse API in ResponseHandler (msal-common)
*/
const HandleServerTokenResponse = "handleServerTokenResponse";
/**
* Authority functions
*/
const AuthorityResolveEndpointsAsync = "authorityResolveEndpointsAsync";
const AuthorityGetCloudDiscoveryMetadataFromNetwork = "authorityGetCloudDiscoveryMetadataFromNetwork";
const AuthorityUpdateCloudDiscoveryMetadata = "authorityUpdateCloudDiscoveryMetadata";
const AuthorityGetEndpointMetadataFromNetwork = "authorityGetEndpointMetadataFromNetwork";
const AuthorityUpdateEndpointMetadata = "authorityUpdateEndpointMetadata";
const AuthorityUpdateMetadataWithRegionalInformation = "authorityUpdateMetadataWithRegionalInformation";
/**
* Region Discovery functions
*/
const RegionDiscoveryDetectRegion = "regionDiscoveryDetectRegion";
const RegionDiscoveryGetRegionFromIMDS = "regionDiscoveryGetRegionFromIMDS";
const RegionDiscoveryGetCurrentVersion = "regionDiscoveryGetCurrentVersion";
/**
* Cache operations
*/
const CacheManagerGetRefreshToken = "cacheManagerGetRefreshToken";
const SetUserData = "setUserData";
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Wraps a function with a performance measurement.
* Usage: invoke(functionToCall, performanceClient, "EventName", "correlationId")(...argsToPassToFunction)
* @param callback
* @param eventName
* @param logger
* @param telemetryClient
* @param correlationId
* @returns
* @internal
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const invoke = (callback, eventName, logger, telemetryClient, correlationId) => {
return (...args) => {
logger.trace(`1plfzx ${eventName}`, correlationId);
const inProgressEvent = telemetryClient.startMeasurement(eventName, correlationId);
if (correlationId) {
// Track number of times this API is called in a single request
telemetryClient.incrementFields({ [`ext.${eventName}CallCount`]: 1 }, correlationId);
}
try {
const result = callback(...args);
inProgressEvent.end({
success: true,
});
logger.trace(`1g8n6a ${eventName}`, correlationId);
return result;
}
catch (e) {
logger.trace(`0cfd8i ${eventName}`, correlationId);
try {
logger.trace(JSON.stringify(e), correlationId);
}
catch (e) {
logger.trace("00dty7", correlationId);
}
inProgressEvent.end({
success: false,
}, e);
throw e;
}
};
};
/**
* Wraps an async function with a performance measurement.
* Usage: invokeAsync(functionToCall, performanceClient, "EventName", "correlationId")(...argsToPassToFunction)
* @param callback
* @param eventName
* @param logger
* @param telemetryClient
* @param correlationId
* @returns
* @internal
*
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const invokeAsync = (callback, eventName, logger, telemetryClient, correlationId) => {
return (...args) => {
logger.trace(`1plfzx ${eventName}`, correlationId);
const inProgressEvent = telemetryClient.startMeasurement(eventName, correlationId);
if (correlationId) {
// Track number of times this API is called in a single request
telemetryClient.incrementFields({ [`ext.${eventName}CallCount`]: 1 }, correlationId);
}
return callback(...args)
.then((response) => {
logger.trace(`1g8n6a ${eventName}`, correlationId);
inProgressEvent.end({
success: true,
});
return response;
})
.catch((e) => {
logger.trace(`0cfd8i ${eventName}`, correlationId);
try {
logger.trace(JSON.stringify(e), correlationId);
}
catch (e) {
logger.trace("00dty7", correlationId);
}
inProgressEvent.end({
success: false,
}, e);
throw e;
});
};
};
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class RegionDiscovery {
constructor(networkInterface, logger, performanceClient, correlationId) {
this.networkInterface = networkInterface;
this.logger = logger;
this.performanceClient = performanceClient;
this.correlationId = correlationId;
}
/**
* Detect the region from the application's environment.
*
* @returns Promise<string | null>
*/
async detectRegion(environmentRegion, regionDiscoveryMetadata) {
// Initialize auto detected region with the region from the envrionment
let autodetectedRegionName = environmentRegion;
// Check if a region was detected from the environment, if not, attempt to get the region from IMDS
if (!autodetectedRegionName) {
const options = RegionDiscovery.IMDS_OPTIONS;
try {
const localIMDSVersionResponse = await invokeAsync(this.getRegionFromIMDS.bind(this), RegionDiscoveryGetRegionFromIMDS, this.logger, this.performanceClient, this.correlationId)(IMDS_VERSION, options);
if (localIMDSVersionResponse.status === HTTP_SUCCESS) {
autodetectedRegionName =
localIMDSVersionResponse.body?.location;
if (autodetectedRegionName) {
regionDiscoveryMetadata.region_source =
RegionDiscoverySources.IMDS;
}
}
// If the response using the local IMDS version failed, try to fetch the current version of IMDS and retry.
if (localIMDSVersionResponse.status ===
HTTP_BAD_REQUEST) {
const currentIMDSVersion = await invokeAsync(this.getCurrentVersion.bind(this), RegionDiscoveryGetCurrentVersion, this.logger, this.performanceClient, this.correlationId)(options);
if (!currentIMDSVersion) {
regionDiscoveryMetadata.region_source =
RegionDiscoverySources.FAILED_AUTO_DETECTION;
return null;
}
const currentIMDSVersionResponse = await invokeAsync(this.getRegionFromIMDS.bind(this), RegionDiscoveryGetRegionFromIMDS, this.logger, this.performanceClient, this.correlationId)(currentIMDSVersion, options);
if (currentIMDSVersionResponse.status ===
HTTP_SUCCESS) {
autodetectedRegionName =
currentIMDSVersionResponse.body?.location;
if (autodetectedRegionName) {
regionDiscoveryMetadata.region_source =
RegionDiscoverySources.IMDS;
}
}
}
}
catch (e) {
regionDiscoveryMetadata.region_source =
RegionDiscoverySources.FAILED_AUTO_DETECTION;
return null;
}
}
else {
regionDiscoveryMetadata.region_source =
RegionDiscoverySources.ENVIRONMENT_VARIABLE;
}
// If no region was auto detected from the environment or from the IMDS endpoint, mark the attempt as a FAILED_AUTO_DETECTION
if (!autodetectedRegionName) {
regionDiscoveryMetadata.region_source =
RegionDiscoverySources.FAILED_AUTO_DETECTION;
}
return autodetectedRegionName || null;
}
/**
* Make the call to the IMDS endpoint
*
* @param version
* @param options
* @returns Promise<NetworkResponse<ImdsComputeResponse>>
*/
async getRegionFromIMDS(version, options) {
return this.networkInterface.sendGetRequestAsync(`${IMDS_ENDPOINT}?api-version=${version}`, options, IMDS_TIMEOUT);
}
/**
* Get the most recent version of the IMDS endpoint available
*
* @returns Promise<string | null>
*/
async getCurrentVersion(options) {
try {
const response = await this.networkInterface.sendGetRequestAsync(`${IMDS_ENDPOINT}?format=json`, options);
// When IMDS endpoint is called without the api version query param, bad request response comes back with latest version.
if (response.status === HTTP_BAD_REQUEST &&
response.body &&
response.body["newest-versions"] &&
response.body["newest-versions"].length > 0) {
return response.body["newest-versions"][0];
}
return null;
}
catch (e) {
return null;
}
}
}
// Options for the IMDS endpoint request
RegionDiscovery.IMDS_OPTIONS = {
headers: {
Metadata: "true",
},
};
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Utility functions for managing date and time operations.
*/
/**
* return the current time in Unix time (seconds).
*/
function nowSeconds() {
// Date.getTime() returns in milliseconds.
return Math.round(new Date().getTime() / 1000.0);
}
/**
* Converts JS Date object to seconds
* @param date Date
*/
function toSecondsFromDate(date) {
// Convert date to seconds
return date.getTime() / 1000;
}
/**
* Convert seconds to JS Date object. Seconds can be in a number or string format or undefined (will still return a date).
* @param seconds
*/
function toDateFromSeconds(seconds) {
if (seconds) {
return new Date(Number(seconds) * 1000);
}
return new Date();
}
/**
* check if a token is expired based on given UTC time in seconds.
* @param expiresOn
*/
function isTokenExpired(expiresOn, offset) {
// check for access token expiry
const expirationSec = Number(expiresOn) || 0;
const offsetCurrentTimeSec = nowSeconds() + offset;
// If current time + offset is greater than token expiration time, then token is expired.
return offsetCurrentTimeSec > expirationSec;
}
/**
* Checks if a cache entry is expired based on the last updated time and cache retention days.
* @param lastUpdatedAt
* @param cacheRetentionDays
* @returns
*/
function isCacheExpired(lastUpdatedAt, cacheRetentionDays) {
const cacheExpirationTimestamp = Number(lastUpdatedAt) + cacheRetentionDays * 24 * 60 * 60 * 1000;
return Date.now() > cacheExpirationTimestamp;
}
/**
* If the current time is earlier than the time that a token was cached at, we must discard the token
* i.e. The system clock was turned back after acquiring the cached token
* @param cachedAt
* @param offset
*/
function wasClockTurnedBack(cachedAt) {
const cachedAtSec = Number(cachedAt);
return cachedAtSec > nowSeconds();
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Create IdTokenEntity
* @param homeAccountId
* @param authenticationResult
* @param clientId
* @param authority
*/
function createIdTokenEntity(homeAccountId, environment, idToken, clientId, tenantId) {
const idTokenEntity = {
credentialType: CredentialType.ID_TOKEN,
homeAccountId: homeAccountId,
environment: environment,
clientId: clientId,
secret: idToken,
realm: tenantId,
lastUpdatedAt: Date.now().toString(), // Set the last updated time to now
};
return idTokenEntity;
}
/**
* Create AccessTokenEntity
* @param homeAccountId
* @param environment
* @param accessToken
* @param clientId
* @param tenantId
* @param scopes
* @param expiresOn
* @param extExpiresOn
*/
function createAccessTokenEntity(homeAccountId, environment, accessToken, clientId, tenantId, scopes, expiresOn, extExpiresOn, base64Decode, correlationId, refreshOn, tokenType, userAssertionHash, keyId, additionalCacheKeyComponents) {
const atEntity = {
homeAccountId: homeAccountId,
credentialType: CredentialType.ACCESS_TOKEN,
secret: accessToken,
cachedAt: nowSeconds().toString(),
expiresOn: expiresOn.toString(),
extendedExpiresOn: extExpiresOn.toString(),
environment: environment,
clientId: clientId,
realm: tenantId,
target: scopes,
tokenType: tokenType || AuthenticationScheme.BEARER,
lastUpdatedAt: Date.now().toString(), // Set the last updated time to now
};
if (userAssertionHash) {
atEntity.userAssertionHash = userAssertionHash;
}
if (refreshOn) {
atEntity.refreshOn = refreshOn.toString();
}
const normalizedTokenType = atEntity.tokenType?.toLowerCase();
/*
* Create Access Token With Auth Scheme instead of regular access token
* Cast to lower to handle "bearer" from ADFS
*/
if (atEntity.tokenType?.toLowerCase() !==
AuthenticationScheme.BEARER.toLowerCase()) {
atEntity.credentialType =
CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME;
switch (normalizedTokenType) {
case AuthenticationScheme.POP:
// Make sure keyId is present and add it to credential
const tokenClaims = extractTokenClaims(accessToken, base64Decode, correlationId);
if (!tokenClaims?.cnf?.kid) {
throw createClientAuthError(tokenClaimsCnfRequiredForSignedJwt, correlationId);
}
atEntity.keyId = tokenClaims.cnf.kid;
break;
case "dpop":
if (!keyId) {
throw createClientAuthError(keyIdMissing, correlationId);
}
atEntity.keyId = keyId;
break;
case AuthenticationScheme.SSH:
atEntity.keyId = keyId;
}
}
/* Additional cache key components for cache isolation (e.g., FMI path) */
if (additionalCacheKeyComponents &&
Object.keys(additionalCacheKeyComponents).length > 0) {
atEntity.additionalCacheKeyComponents = additionalCacheKeyComponents;
}
return atEntity;
}
/**
* Create RefreshTokenEntity
* @param homeAccountId
* @param authenticationResult
* @param clientId
* @param authority
*/
function createRefreshTokenEntity(homeAccountId, environment, refreshToken, clientId, familyId, userAssertionHash, expiresOn) {
const rtEntity = {
credentialType: CredentialType.REFRESH_TOKEN,
homeAccountId: homeAccountId,
environment: environment,
clientId: clientId,
secret: refreshToken,
lastUpdatedAt: Date.now().toString(),
};
if (userAssertionHash) {
rtEntity.userAssertionHash = userAssertionHash;
}
if (familyId) {
rtEntity.familyId = familyId;
}
if (expiresOn) {
rtEntity.expiresOn = expiresOn.toString();
}
return rtEntity;
}
function isCredentialEntity(entity) {
return (entity.hasOwnProperty("homeAccountId") &&
entity.hasOwnProperty("environment") &&
entity.hasOwnProperty("credentialType") &&
entity.hasOwnProperty("clientId") &&
entity.hasOwnProperty("secret"));
}
/**
* Validates an entity: checks for all expected params
* @param entity
*/
function isAccessTokenEntity(entity) {
if (!entity) {
return false;
}
return (isCredentialEntity(entity) &&
entity.hasOwnProperty("realm") &&
entity.hasOwnProperty("target") &&
(entity["credentialType"] === CredentialType.ACCESS_TOKEN ||
entity["credentialType"] ===
CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME));
}
/**
* Validates an entity: checks for all expected params
* @param entity
*/
function isIdTokenEntity(entity) {
if (!entity) {
return false;
}
return (isCredentialEntity(entity) &&
entity.hasOwnProperty("realm") &&
entity["credentialType"] === CredentialType.ID_TOKEN);
}
/**
* Validates an entity: checks for all expected params
* @param entity
*/
function isRefreshTokenEntity(entity) {
if (!entity) {
return false;
}
return (isCredentialEntity(entity) &&
entity["credentialType"] === CredentialType.REFRESH_TOKEN);
}
/**
* validates if a given cache entry is "Telemetry", parses <key,value>
* @param key
* @param entity
*/
function isServerTelemetryEntity(key, entity) {
const validateKey = key.indexOf(SERVER_TELEM_CACHE_KEY) === 0;
let validateEntity = true;
if (entity) {
validateEntity =
entity.hasOwnProperty("failedRequests") &&
entity.hasOwnProperty("errors") &&
entity.hasOwnProperty("cacheHits");
}
return validateKey && validateEntity;
}
/**
* validates if a given cache entry is "Throttling", parses <key,value>
* @param key
* @param entity
*/
function isThrottlingEntity(key, entity) {
let validateKey = false;
if (key) {
validateKey = key.indexOf(THROTTLING_PREFIX) === 0;
}
let validateEntity = true;
if (entity) {
validateEntity = entity.hasOwnProperty("throttleTime");
}
return validateKey && validateEntity;
}
/**
* Generate AppMetadata Cache Key as per the schema: appmetadata-<environment>-<client_id>
*/
function generateAppMetadataKey({ environment, clientId, }) {
const appMetaDataKeyArray = [
APP_METADATA,
environment,
clientId,
];
return appMetaDataKeyArray
.join(CACHE_KEY_SEPARATOR$1)
.toLowerCase();
}
/*
* Validates an entity: checks for all expected params
* @param entity
*/
function isAppMetadataEntity(key, entity) {
if (!entity) {
return false;
}
return (key.indexOf(APP_METADATA) === 0 &&
entity.hasOwnProperty("clientId") &&
entity.hasOwnProperty("environment"));
}
/**
* Validates an entity: checks for all expected params
* @param entity
*/
function isAuthorityMetadataEntity(key, entity) {
if (!entity) {
return false;
}
return (key.indexOf(AUTHORITY_METADATA_CACHE_KEY) === 0 &&
entity.hasOwnProperty("aliases") &&
entity.hasOwnProperty("preferred_cache") &&
entity.hasOwnProperty("preferred_network") &&
entity.hasOwnProperty("canonical_authority") &&
entity.hasOwnProperty("authorization_endpoint") &&
entity.hasOwnProperty("token_endpoint") &&
entity.hasOwnProperty("issuer") &&
entity.hasOwnProperty("aliasesFromNetwork") &&
entity.hasOwnProperty("endpointsFromNetwork") &&
entity.hasOwnProperty("expiresAt") &&
entity.hasOwnProperty("jwks_uri"));
}
/**
* Reset the exiresAt value
*/
function generateAuthorityMetadataExpiresAt() {
return (nowSeconds() +
AUTHORITY_METADATA_REFRESH_TIME_SECONDS);
}
/** @internal */
function updateAuthorityEndpointMetadata(authorityMetadata, updatedValues, fromNetwork) {
authorityMetadata.authorization_endpoint =
updatedValues.authorization_endpoint;
authorityMetadata.token_endpoint = updatedValues.token_endpoint;
authorityMetadata.end_session_endpoint = updatedValues.end_session_endpoint;
authorityMetadata.issuer = updatedValues.issuer;
authorityMetadata.endpointsFromNetwork = fromNetwork;
authorityMetadata.jwks_uri = updatedValues.jwks_uri;
}
/** @internal */
function updateCloudDiscoveryMetadata(authorityMetadata, updatedValues, fromNetwork) {
authorityMetadata.aliases = updatedValues.aliases;
authorityMetadata.preferred_cache = updatedValues.preferred_cache;
authorityMetadata.preferred_network = updatedValues.preferred_network;
authorityMetadata.aliasesFromNetwork = fromNetwork;
}
/**
* Returns whether or not the data needs to be refreshed
* @internal
*/
function isAuthorityMetadataExpired(metadata) {
return metadata.expiresAt <= nowSeconds();
}
/**
* Serialize attribute tokens synchronously (sort and join).
* This is a sync-only operation for use at request construction time.
* @param attributeTokens - array of tokens
* @returns serialized partition string or undefined if no tokens
*/
function serializeAttributeTokens(attributeTokens) {
if (!attributeTokens || attributeTokens.length === 0) {
return undefined;
}
// Serialize: sort and join tokens
return [...attributeTokens].sort().join(" ");
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* The authority class validates the authority URIs used by the user, and retrieves the OpenID Configuration Data from the
* endpoint. It will store the pertinent config data in this object for use during token calls.
* @internal
*/
class Authority {
constructor(authority, networkInterface, cacheManager, authorityOptions, logger, correlationId, performanceClient, managedIdentity) {
this.canonicalAuthority = authority;
this._canonicalAuthority.validateAsUri();
this.networkInterface = networkInterface;
this.cacheManager = cacheManager;
this.authorityOptions = authorityOptions;
this.regionDiscoveryMetadata = {
region_used: undefined,
region_source: undefined,
region_outcome: undefined,
};
this.logger = logger;
this.performanceClient = performanceClient;
this.correlationId = correlationId;
this.managedIdentity = managedIdentity || false;
this.regionDiscovery = new RegionDiscovery(networkInterface, this.logger, this.performanceClient, this.correlationId);
}
/**
* Get {@link AuthorityType:type}
* @param authorityUri {@link IUri}
* @private
*/
getAuthorityType(authorityUri) {
// CIAM auth url pattern is being standardized as: <tenant>.ciamlogin.com
if (authorityUri.HostNameAndPort.endsWith(CIAM_AUTH_URL)) {
return AuthorityType.Ciam;
}
const pathSegments = authorityUri.PathSegments;
if (pathSegments.length) {
switch (pathSegments[0].toLowerCase()) {
case ADFS:
return AuthorityType.Adfs;
}
}
return AuthorityType.Default;
}
// See above for AuthorityType
get authorityType() {
return this.getAuthorityType(this.canonicalAuthorityUrlComponents);
}
/**
* ProtocolMode enum representing the way endpoints are constructed.
*/
get protocolMode() {
return this.authorityOptions.protocolMode;
}
/**
* Returns authorityOptions which can be used to reinstantiate a new authority instance
*/
get options() {
return this.authorityOptions;
}
/**
* A URL that is the authority set by the developer
*/
get canonicalAuthority() {
return this._canonicalAuthority.urlString;
}
/**
* Sets canonical authority.
*/
set canonicalAuthority(url) {
this._canonicalAuthority = new UrlString(url, this.correlationId);
this._canonicalAuthority.validateAsUri();
this._canonicalAuthorityUrlComponents = null;
}
/**
* Get authority components.
*/
get canonicalAuthorityUrlComponents() {
if (!this._canonicalAuthorityUrlComponents) {
this._canonicalAuthorityUrlComponents =
this._canonicalAuthority.getUrlComponents();
}
return this._canonicalAuthorityUrlComponents;
}
/**
* Get hostname and port i.e. login.microsoftonline.com
*/
get hostnameAndPort() {
return this.canonicalAuthorityUrlComponents.HostNameAndPort.toLowerCase();
}
/**
* Get tenant for authority.
*/
get tenant() {
return this.canonicalAuthorityUrlComponents.PathSegments[0];
}
/**
* OAuth /authorize endpoint for requests
*/
get authorizationEndpoint() {
if (this.discoveryComplete()) {
return this.replacePath(this.metadata.authorization_endpoint);
}
else {
throw createClientAuthError(endpointResolutionError, this.correlationId);
}
}
/**
* OAuth /token endpoint for requests
*/
get tokenEndpoint() {
if (this.discoveryComplete()) {
return this.replacePath(this.metadata.token_endpoint);
}
else {
throw createClientAuthError(endpointResolutionError, this.correlationId);
}
}
get deviceCodeEndpoint() {
if (this.discoveryComplete()) {
return this.replacePath(this.metadata.token_endpoint.replace("/token", "/devicecode"));
}
else {
throw createClientAuthError(endpointResolutionError, this.correlationId);
}
}
/**
* OAuth logout endpoint for requests
*/
get endSessionEndpoint() {
if (this.discoveryComplete()) {
// ROPC policies may not have end_session_endpoint set
if (!this.metadata.end_session_endpoint) {
throw createClientAuthError(endSessionEndpointNotSupported, this.correlationId);
}
return this.replacePath(this.metadata.end_session_endpoint);
}
else {
throw createClientAuthError(endpointResolutionError, this.correlationId);
}
}
/**
* OAuth issuer for requests
*/
get selfSignedJwtAudience() {
if (this.discoveryComplete()) {
return this.replacePath(this.metadata.issuer);
}
else {
throw createClientAuthError(endpointResolutionError, this.correlationId);
}
}
/**
* Jwks_uri for token signing keys
*/
get jwksUri() {
if (this.discoveryComplete()) {
return this.replacePath(this.metadata.jwks_uri);
}
else {
throw createClientAuthError(endpointResolutionError, this.correlationId);
}
}
/**
* Returns a flag indicating that tenant name can be replaced in authority {@link IUri}
* @param authorityUri {@link IUri}
* @private
*/
canReplaceTenant(authorityUri) {
return (authorityUri.PathSegments.length === 1 &&
!Authority.reservedTenantDomains.has(authorityUri.PathSegments[0]) &&
this.getAuthorityType(authorityUri) === AuthorityType.Default &&
this.protocolMode !== ProtocolMode.OIDC);
}
/**
* Replaces tenant in url path with current tenant. Defaults to common.
* @param urlString
*/
replaceTenant(urlString) {
return urlString.replace(/{tenant}|{tenantid}/g, this.tenant);
}
/**
* Replaces path such as tenant or policy with the current tenant or policy.
* @param urlString
*/
replacePath(urlString) {
let endpoint = urlString;
const cachedAuthorityUrl = new UrlString(this.metadata.canonical_authority, this.correlationId);
const cachedAuthorityUrlComponents = cachedAuthorityUrl.getUrlComponents();
const cachedAuthorityParts = cachedAuthorityUrlComponents.PathSegments;
const currentAuthorityParts = this.canonicalAuthorityUrlComponents.PathSegments;
currentAuthorityParts.forEach((currentPart, index) => {
let cachedPart = cachedAuthorityParts[index];
if (index === 0 &&
this.canReplaceTenant(cachedAuthorityUrlComponents)) {
const tenantId = new UrlString(this.metadata.authorization_endpoint, this.correlationId).getUrlComponents().PathSegments[0];
/**
* Check if AAD canonical authority contains tenant domain name, for example "testdomain.onmicrosoft.com",
* by comparing its first path segment to the corresponding authorization endpoint path segment, which is
* always resolved with tenant id by OIDC.
*/
if (cachedPart !== tenantId) {
this.logger.verbose(`1q3g2x ${cachedPart} ${tenantId}`, this.correlationId);
cachedPart = tenantId;
}
}
if (currentPart !== cachedPart) {
endpoint = endpoint.replace(`/${cachedPart}/`, `/${currentPart}/`);
}
});
return this.replaceTenant(endpoint);
}
/**
* The default open id configuration endpoint for any canonical authority.
*/
get defaultOpenIdConfigurationEndpoint() {
const canonicalAuthorityHost = this.hostnameAndPort;
if (this.canonicalAuthority.endsWith("v2.0/") ||
this.authorityType === AuthorityType.Adfs ||
(this.protocolMode === ProtocolMode.OIDC &&
!this.isAliasOfKnownMicrosoftAuthority(canonicalAuthorityHost))) {
return `${this.canonicalAuthority}.well-known/openid-configuration`;
}
return `${this.canonicalAuthority}v2.0/.well-known/openid-configuration`;
}
/**
* Boolean that returns whether or not tenant discovery has been completed.
*/
discoveryComplete() {
return !!this.metadata;
}
/**
* Perform endpoint discovery to discover aliases, preferred_cache, preferred_network
* and the /authorize, /token and logout endpoints.
*/
async resolveEndpointsAsync() {
const metadataEntity = this.getCurrentMetadataEntity();
const cloudDiscoverySource = await invokeAsync(this.updateCloudDiscoveryMetadata.bind(this), AuthorityUpdateCloudDiscoveryMetadata, this.logger, this.performanceClient, this.correlationId)(metadataEntity);
this.canonicalAuthority = this.canonicalAuthority.replace(this.hostnameAndPort, metadataEntity.preferred_network);
const endpointSource = await invokeAsync(this.updateEndpointMetadata.bind(this), AuthorityUpdateEndpointMetadata, this.logger, this.performanceClient, this.correlationId)(metadataEntity);
this.updateCachedMetadata(metadataEntity, cloudDiscoverySource, {
source: endpointSource,
});
this.performanceClient?.addFields({
cloudDiscoverySource: cloudDiscoverySource,
authorityEndpointSource: endpointSource,
}, this.correlationId);
}
/**
* Returns metadata entity from cache if it exists, otherwise returns a new metadata entity built
* from the configured canonical authority
* @returns
*/
getCurrentMetadataEntity() {
let metadataEntity = this.cacheManager.getAuthorityMetadataByAlias(this.hostnameAndPort, this.correlationId);
if (!metadataEntity) {
metadataEntity = {
aliases: [],
preferred_cache: this.hostnameAndPort,
preferred_network: this.hostnameAndPort,
canonical_authority: this.canonicalAuthority,
authorization_endpoint: "",
token_endpoint: "",
end_session_endpoint: "",
issuer: "",
aliasesFromNetwork: false,
endpointsFromNetwork: false,
expiresAt: generateAuthorityMetadataExpiresAt(),
jwks_uri: "",
};
}
return metadataEntity;
}
/**
* Updates cached metadata based on metadata source and sets the instance's metadata
* property to the same value
* @param metadataEntity
* @param cloudDiscoverySource
* @param endpointMetadataResult
*/
updateCachedMetadata(metadataEntity, cloudDiscoverySource, endpointMetadataResult) {
if (cloudDiscoverySource !== AuthorityMetadataSource.CACHE &&
endpointMetadataResult?.source !==
AuthorityMetadataSource.CACHE) {
// Reset the expiration time unless both values came from a successful cache lookup
metadataEntity.expiresAt =
generateAuthorityMetadataExpiresAt();
metadataEntity.canonical_authority = this.canonicalAuthority;
}
const cacheKey = this.cacheManager.generateAuthorityMetadataCacheKey(metadataEntity.preferred_cache, this.correlationId);
this.cacheManager.setAuthorityMetadata(cacheKey, metadataEntity, this.correlationId);
this.metadata = metadataEntity;
}
/**
* Update AuthorityMetadataEntity with new endpoints and return where the information came from
* @param metadataEntity
*/
async updateEndpointMetadata(metadataEntity) {
const localMetadata = this.updateEndpointMetadataFromLocalSources(metadataEntity);
// Further update may be required for hardcoded metadata if regional metadata is preferred
if (localMetadata) {
if (localMetadata.source ===
AuthorityMetadataSource.HARDCODED_VALUES) {
// If the user prefers to use an azure region replace the global endpoints with regional information.
if (this.authorityOptions.azureRegionConfiguration?.azureRegion) {
if (localMetadata.metadata) {
const hardcodedMetadata = await invokeAsync(this.updateMetadataWithRegionalInformation.bind(this), AuthorityUpdateMetadataWithRegionalInformation, this.logger, this.performanceClient, this.correlationId)(localMetadata.metadata);
updateAuthorityEndpointMetadata(metadataEntity, hardcodedMetadata, false);
metadataEntity.canonical_authority =
this.canonicalAuthority;
}
}
}
return localMetadata.source;
}
// Get metadata from network if local sources aren't available
let metadata = await invokeAsync(this.getEndpointMetadataFromNetwork.bind(this), AuthorityGetEndpointMetadataFromNetwork, this.logger, this.performanceClient, this.correlationId)();
if (metadata) {
// Validate the issuer returned by the OIDC discovery document.
this.validateIssuer(metadata.issuer);
// If the user prefers to use an azure region replace the global endpoints with regional information.
if (this.authorityOptions.azureRegionConfiguration?.azureRegion) {
metadata = await invokeAsync(this.updateMetadataWithRegionalInformation.bind(this), AuthorityUpdateMetadataWithRegionalInformation, this.logger, this.performanceClient, this.correlationId)(metadata);
}
updateAuthorityEndpointMetadata(metadataEntity, metadata, true);
return AuthorityMetadataSource.NETWORK;
}
else {
// Metadata could not be obtained from the config, cache, network or hardcoded values
throw createClientAuthError(openIdConfigError, this.defaultOpenIdConfigurationEndpoint, this.correlationId);
}
}
/**
* Updates endpoint metadata from local sources and returns where the information was retrieved from and the metadata config
* response if the source is hardcoded metadata
* @param metadataEntity
* @returns
*/
updateEndpointMetadataFromLocalSources(metadataEntity) {
this.logger.verbose("1fi0kc", this.correlationId);
const configMetadata = this.getEndpointMetadataFromConfig();
if (configMetadata) {
this.logger.verbose("06t0uj", this.correlationId);
updateAuthorityEndpointMetadata(metadataEntity, configMetadata, false);
return {
source: AuthorityMetadataSource.CONFIG,
};
}
this.logger.verbose("151k0p", this.correlationId);
const hardcodedMetadata = this.getEndpointMetadataFromHardcodedValues();
if (hardcodedMetadata) {
updateAuthorityEndpointMetadata(metadataEntity, hardcodedMetadata, false);
return {
source: AuthorityMetadataSource.HARDCODED_VALUES,
metadata: hardcodedMetadata,
};
}
else {
this.logger.verbose("1imop5", this.correlationId);
}
// Check cached metadata entity expiration status
const metadataEntityExpired = isAuthorityMetadataExpired(metadataEntity);
if (this.isAuthoritySameType(metadataEntity) &&
metadataEntity.endpointsFromNetwork &&
!metadataEntityExpired) {
// No need to update
this.logger.verbose("16uq31", "");
return { source: AuthorityMetadataSource.CACHE };
}
else if (metadataEntityExpired) {
this.logger.verbose("0uoibc", "");
}
return null;
}
/**
* Compares the number of url components after the domain to determine if the cached
* authority metadata can be used for the requested authority. Protects against same domain different
* authority such as login.microsoftonline.com/tenant and login.microsoftonline.com/tfp/tenant/policy
* @param metadataEntity
*/
isAuthoritySameType(metadataEntity) {
const cachedAuthorityUrl = new UrlString(metadataEntity.canonical_authority, this.correlationId);
const cachedParts = cachedAuthorityUrl.getUrlComponents().PathSegments;
return (cachedParts.length ===
this.canonicalAuthorityUrlComponents.PathSegments.length);
}
/**
* Parse authorityMetadata config option
*/
getEndpointMetadataFromConfig() {
if (this.authorityOptions.authorityMetadata) {
try {
return JSON.parse(this.authorityOptions.authorityMetadata);
}
catch (e) {
throw createClientConfigurationError(invalidAuthorityMetadata, this.correlationId);
}
}
return null;
}
/**
* Gets OAuth endpoints from the given OpenID configuration endpoint.
*
* @param hasHardcodedMetadata boolean
*/
async getEndpointMetadataFromNetwork() {
const options = {};
/*
* TODO: Add a timeout if the authority exists in our library's
* hardcoded list of metadata
*/
const openIdConfigurationEndpoint = this.defaultOpenIdConfigurationEndpoint;
this.logger.verbose(`1y65x6 ${openIdConfigurationEndpoint}`, this.correlationId);
try {
const response = await this.networkInterface.sendGetRequestAsync(openIdConfigurationEndpoint, options);
const isValidResponse = isOpenIdConfigResponse(response.body);
if (isValidResponse) {
return response.body;
}
else {
this.logger.verbose("1koyv8", this.correlationId);
return null;
}
}
catch (e) {
this.logger.verbose(`0a9wik ${e}`, this.correlationId);
return null;
}
}
/**
* Get OAuth endpoints for common authorities.
*/
getEndpointMetadataFromHardcodedValues() {
if (this.hostnameAndPort in EndpointMetadata) {
return EndpointMetadata[this.hostnameAndPort];
}
return null;
}
/**
* Update the retrieved metadata with regional information.
* User selected Azure region will be used if configured.
*/
async updateMetadataWithRegionalInformation(metadata) {
const userConfiguredAzureRegion = this.authorityOptions.azureRegionConfiguration?.azureRegion;
if (userConfiguredAzureRegion) {
if (userConfiguredAzureRegion !==
AZURE_REGION_AUTO_DISCOVER_FLAG) {
this.regionDiscoveryMetadata.region_outcome =
RegionDiscoveryOutcomes.CONFIGURED_NO_AUTO_DETECTION;
this.regionDiscoveryMetadata.region_used =
userConfiguredAzureRegion;
return Authority.replaceWithRegionalInformation(metadata, userConfiguredAzureRegion, this.correlationId);
}
const autodetectedRegionName = await invokeAsync(this.regionDiscovery.detectRegion.bind(this.regionDiscovery), RegionDiscoveryDetectRegion, this.logger, this.performanceClient, this.correlationId)(this.authorityOptions.azureRegionConfiguration
?.environmentRegion, this.regionDiscoveryMetadata);
if (autodetectedRegionName) {
this.regionDiscoveryMetadata.region_outcome =
RegionDiscoveryOutcomes.AUTO_DETECTION_REQUESTED_SUCCESSFUL;
this.regionDiscoveryMetadata.region_used =
autodetectedRegionName;
return Authority.replaceWithRegionalInformation(metadata, autodetectedRegionName, this.correlationId);
}
this.regionDiscoveryMetadata.region_outcome =
RegionDiscoveryOutcomes.AUTO_DETECTION_REQUESTED_FAILED;
}
return metadata;
}
/**
* Updates the AuthorityMetadataEntity with new aliases, preferred_network and preferred_cache
* and returns where the information was retrieved from
* @param metadataEntity
* @returns AuthorityMetadataSource
*/
async updateCloudDiscoveryMetadata(metadataEntity) {
const localMetadataSource = this.updateCloudDiscoveryMetadataFromLocalSources(metadataEntity);
if (localMetadataSource) {
return localMetadataSource;
}
// Fallback to network as metadata source
const metadata = await invokeAsync(this.getCloudDiscoveryMetadataFromNetwork.bind(this), AuthorityGetCloudDiscoveryMetadataFromNetwork, this.logger, this.performanceClient, this.correlationId)();
if (metadata) {
updateCloudDiscoveryMetadata(metadataEntity, metadata, true);
return AuthorityMetadataSource.NETWORK;
}
// Metadata could not be obtained from the config, cache, network or hardcoded values
throw createClientConfigurationError(untrustedAuthority, this.correlationId);
}
updateCloudDiscoveryMetadataFromLocalSources(metadataEntity) {
this.logger.verbose("1tpqlr", this.correlationId);
this.logger.verbosePii(`1fy7uz ${this.authorityOptions.knownAuthorities ||
NOT_APPLICABLE}`, this.correlationId);
this.logger.verbosePii(`08zabj ${this.authorityOptions.authorityMetadata ||
NOT_APPLICABLE}`, this.correlationId);
this.logger.verbosePii(`1o1kv3 ${metadataEntity.canonical_authority || NOT_APPLICABLE}`, this.correlationId);
const metadata = this.getCloudDiscoveryMetadataFromConfig();
if (metadata) {
this.logger.verbose("1nakio", this.correlationId);
updateCloudDiscoveryMetadata(metadataEntity, metadata, false);
return AuthorityMetadataSource.CONFIG;
}
// If the cached metadata came from config but that config was not passed to this instance, we must go to hardcoded values
this.logger.verbose("1x74aj", this.correlationId);
const hardcodedMetadata = getCloudDiscoveryMetadataFromHardcodedValues(this.hostnameAndPort);
if (hardcodedMetadata) {
this.logger.verbose("0by47c", this.correlationId);
updateCloudDiscoveryMetadata(metadataEntity, hardcodedMetadata, false);
return AuthorityMetadataSource.HARDCODED_VALUES;
}
this.logger.verbose("0r2fzy", this.correlationId);
const metadataEntityExpired = isAuthorityMetadataExpired(metadataEntity);
if (this.isAuthoritySameType(metadataEntity) &&
metadataEntity.aliasesFromNetwork &&
!metadataEntityExpired) {
this.logger.verbose("1uffgh", "");
// No need to update
return AuthorityMetadataSource.CACHE;
}
else if (metadataEntityExpired) {
this.logger.verbose("0uoibc", "");
}
return null;
}
/**
* Parse cloudDiscoveryMetadata config or check knownAuthorities
*/
getCloudDiscoveryMetadataFromConfig() {
// CIAM does not support cloud discovery metadata
if (this.authorityType === AuthorityType.Ciam) {
this.logger.verbose("04y84h", this.correlationId);
return Authority.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort);
}
// Check if network response was provided in config
if (this.authorityOptions.cloudDiscoveryMetadata) {
this.logger.verbose("0gszr3", this.correlationId);
try {
this.logger.verbose("1iifkx", this.correlationId);
const parsedResponse = JSON.parse(this.authorityOptions.cloudDiscoveryMetadata);
const metadata = getCloudDiscoveryMetadataFromNetworkResponse(parsedResponse.metadata, this.hostnameAndPort);
this.logger.verbose("0q67e3", "");
if (metadata) {
this.logger.verbose("0hzfao", this.correlationId);
return metadata;
}
else {
this.logger.verbose("1ajz3u", this.correlationId);
}
}
catch (e) {
this.logger.verbose("1wq5tu", this.correlationId);
throw createClientConfigurationError(invalidCloudDiscoveryMetadata, this.correlationId);
}
}
// If cloudDiscoveryMetadata is empty or does not contain the host, check knownAuthorities
if (this.isInKnownAuthorities(this.hostnameAndPort)) {
this.logger.verbose("0mt9al", this.correlationId);
return Authority.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort);
}
return null;
}
/**
* Called to get metadata from network if CloudDiscoveryMetadata was not populated by config
*
* @param hasHardcodedMetadata boolean
*/
async getCloudDiscoveryMetadataFromNetwork() {
const instanceDiscoveryEndpoint = `${AAD_INSTANCE_DISCOVERY_ENDPT}${this.canonicalAuthority}oauth2/v2.0/authorize`;
const options = {};
/*
* TODO: Add a timeout if the authority exists in our library's
* hardcoded list of metadata
*/
let match = null;
try {
const response = await this.networkInterface.sendGetRequestAsync(instanceDiscoveryEndpoint, options);
let typedResponseBody;
let metadata;
if (isCloudInstanceDiscoveryResponse(response.body)) {
typedResponseBody =
response.body;
metadata = typedResponseBody.metadata;
this.logger.verbosePii(`1vglyt ${typedResponseBody.tenant_discovery_endpoint}`, this.correlationId);
}
else if (isCloudInstanceDiscoveryErrorResponse(response.body)) {
this.logger.warning(`062uto ${response.status}`, this.correlationId);
typedResponseBody =
response.body;
if (typedResponseBody.error === INVALID_INSTANCE) {
this.logger.error("1x90tm", this.correlationId);
return null;
}
this.logger.warning(`0wchdm ${typedResponseBody.error}`, this.correlationId);
this.logger.warning(`1s5mpv ${typedResponseBody.error_description}`, this.correlationId);
this.logger.warning("1yhqpw", this.correlationId);
metadata = [];
}
else {
this.logger.error("0768g0", this.correlationId);
return null;
}
this.logger.verbose("1lrobr", this.correlationId);
match = getCloudDiscoveryMetadataFromNetworkResponse(metadata, this.hostnameAndPort);
}
catch (error) {
if (error instanceof AuthError) {
this.logger.error(`0vwhc7 ${error.errorCode} ${error.errorMessage}`, this.correlationId);
}
else {
const typedError = error;
this.logger.error(`0s2z41 ${typedError.name} ${typedError.message}`, this.correlationId);
}
return null;
}
// Custom Domain scenario, host is trusted because Instance Discovery call succeeded
if (!match) {
this.logger.warning("0jp28q", this.correlationId);
this.logger.verbose("130sd8", this.correlationId);
match = Authority.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort);
}
return match;
}
/**
* Helper function to determine if a host is included in the knownAuthorities config option.
*/
isInKnownAuthorities(host) {
const normalizedHost = host.toLowerCase();
const matches = this.authorityOptions.knownAuthorities.filter((authority) => {
return (authority &&
UrlString.getDomainFromUrl(authority, this.correlationId).toLowerCase() === normalizedHost);
});
return matches.length > 0;
}
/**
* helper function to populate the authority based on azureCloudOptions
* @param authorityString
* @param azureCloudOptions
*/
static generateAuthority(authorityString, azureCloudOptions) {
let authorityAzureCloudInstance;
if (azureCloudOptions &&
azureCloudOptions.azureCloudInstance !== AzureCloudInstance.None) {
const tenant = azureCloudOptions.tenant
? azureCloudOptions.tenant
: DEFAULT_COMMON_TENANT;
authorityAzureCloudInstance = `${azureCloudOptions.azureCloudInstance}/${tenant}/`;
}
return authorityAzureCloudInstance
? authorityAzureCloudInstance
: authorityString;
}
/**
* Creates cloud discovery metadata object from a given host
* @param host
*/
static createCloudDiscoveryMetadataFromHost(host) {
return {
preferred_network: host,
preferred_cache: host,
aliases: [host],
};
}
/**
* helper function to generate environment from authority object
*/
getPreferredCache() {
if (this.managedIdentity) {
return DEFAULT_AUTHORITY_HOST;
}
else if (this.discoveryComplete()) {
return this.metadata.preferred_cache;
}
else {
throw createClientAuthError(endpointResolutionError, this.correlationId);
}
}
/**
* Returns whether or not the provided host is an alias of this authority instance
* @param host
*/
isAlias(host) {
return this.metadata.aliases.indexOf(host) > -1;
}
/**
* Returns whether or not the provided host is an alias of a known Microsoft authority for purposes of endpoint discovery
* @param host
*/
isAliasOfKnownMicrosoftAuthority(host) {
return InstanceDiscoveryMetadataAliases.has(host);
}
/**
* Validates the `issuer` returned by an OIDC discovery document against
* this authority, per
* https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationValidation
*
* The issuer is accepted when ANY of the following holds:
* 1. The issuer scheme + host + port match the authority's (path may
* differ). Applies to all authorities.
* 2. The authority is a Microsoft cloud authority (public, sovereign,
* or CIAM), the issuer is HTTPS, and the issuer host is in the known
* Microsoft authority host set.
* 3. Same as (2), but the issuer host is a single-label regional variant
* of a known Microsoft host (e.g. `westus.login.microsoftonline.com`).
* 4. Same as (2), but the issuer host matches the CIAM tenant pattern
* `{tenant}.ciamlogin.com` with an optional `/{tenant}[.onmicrosoft.com][/v2.0]`
* path.
* 5. The issuer host is HTTPS and is explicitly listed in the
* developer-configured `knownAuthorities`. This covers scenarios where
* the OIDC discovery document returns an issuer host that differs from
* the authority (e.g., a GUID-based issuer for a name-based CIAM authority).
*
* @param issuer The `issuer` value returned in the OIDC discovery document.
* @throws ClientConfigurationError("issuer_validation_failed") on failure.
*/
validateIssuer(issuer) {
if (!issuer) {
throw createClientConfigurationError(issuerValidationFailed, this.correlationId);
}
// Parse with the WHATWG URL API. URL normalizes scheme + host to lowercase per RFC 3986.
let issuerUrl;
try {
issuerUrl = new URL(issuer);
}
catch {
throw createClientConfigurationError(issuerValidationFailed, this.correlationId);
}
const issuerScheme = issuerUrl.protocol;
const issuerHost = issuerUrl.host;
const authorityScheme = (this.canonicalAuthorityUrlComponents.Protocol || "").toLowerCase();
const authorityHost = (this.canonicalAuthorityUrlComponents.HostNameAndPort || "").toLowerCase();
// Rule 1: Same scheme and host
const matchesAuthorityOrigin = this.matchesAuthorityOrigin(issuerScheme, issuerHost, authorityScheme, authorityHost);
// Rule 2: The issuer host is a well-known Microsoft authority host (HTTPS only)
const matchesKnownMicrosoftHost = issuerScheme === "https:" &&
this.isAliasOfKnownMicrosoftAuthority(issuerHost);
/*
* Rule 3: The issuer host is a regional variant ({region}.{host}) of a well-known host
* (HTTPS only). E.g. westus2.login.microsoft.com
*/
const matchesRegionalMicrosoftHost = issuerScheme === "https:" &&
this.matchesRegionalMicrosoftHost(issuerHost);
/*
* Rule 4: CIAM-specific validation. In a CIAM scenario the issuer is expected to
* have "{tenant}.ciamlogin.com" as the host, even when using a custom domain.
*/
const matchesCiamTenantPattern = this.matchesCiamTenantPattern(issuerUrl, authorityHost, this.canonicalAuthorityUrlComponents.PathSegments);
/*
* Rule 5: The issuer host is explicitly listed in the developer-configured
* knownAuthorities. This covers scenarios where the OIDC discovery document
* returns an issuer with a different host than the authority
* (e.g., a GUID-based issuer for a name-based authority).
*/
const matchesKnownAuthority = issuerScheme === "https:" && this.isInKnownAuthorities(issuerHost);
// Each rule is an independent boolean; the issuer is valid if ANY rule matches.
if (matchesAuthorityOrigin ||
matchesKnownMicrosoftHost ||
matchesRegionalMicrosoftHost ||
matchesCiamTenantPattern ||
matchesKnownAuthority) {
return;
}
// issuer validation fails if none of the above rules are satisfied
throw createClientConfigurationError(issuerValidationFailed, this.correlationId);
}
/**
* Rule 1: The issuer scheme + host (and port) match the authority's. Path
* may differ. Applies to all authorities.
*/
matchesAuthorityOrigin(issuerScheme, issuerHost, authorityScheme, authorityHost) {
return issuerScheme === authorityScheme && issuerHost === authorityHost;
}
/**
* Rule 3: The issuer host is a regional variant
* (`{region}.{host}`) of a known Microsoft authority host.
* E.g. `westus2.login.microsoft.com`.
*/
matchesRegionalMicrosoftHost(issuerHost) {
const firstDot = issuerHost.indexOf(".");
if (firstDot > 0 && firstDot < issuerHost.length - 1) {
const hostWithoutRegion = issuerHost.substring(firstDot + 1);
return this.isAliasOfKnownMicrosoftAuthority(hostWithoutRegion);
}
return false;
}
/**
* Rule 4: The issuer matches one of the well-known CIAM tenant patterns
* (`https://{tenant}.ciamlogin.com[/{tenant}[.onmicrosoft.com][/v2.0]]`).
*
* The bare tenant name is extracted from the authority's first path segment
* when available (stripping the `.onmicrosoft.com` suffix that
* `transformCIAMAuthority` adds), or otherwise from the leftmost label of
* the authority host (to support CIAM custom domain scenarios).
*
* Both `/{tenant}` and `/{tenant}.onmicrosoft.com` path forms are accepted
* because the OIDC issuer may use either form depending on the authority URL
* that was used to trigger discovery.
*/
matchesCiamTenantPattern(issuerUrl, authorityHost, authorityPathSegments) {
/*
* authorityPathSegments[0] is the first path segment of the *authority
* URL* after transformCIAMAuthority runs (e.g. "contoso.onmicrosoft.com").
* Additional CIAM issuer path segments such as "/v2.0" are part of the
* issuer string, not the authority URL's PathSegments.
*/
const pathSegment = authorityPathSegments[0];
/*
* Extract the bare tenant name: strip the .onmicrosoft.com suffix when
* present (introduced by transformCIAMAuthority), or fall back to the
* first label of the authority hostname for non-transformed/custom-domain
* CIAM authorities.
*/
const tenantName = pathSegment
? pathSegment.endsWith(AAD_TENANT_DOMAIN_SUFFIX)
? pathSegment.slice(0, -AAD_TENANT_DOMAIN_SUFFIX.length)
: pathSegment
: authorityHost.split(".")[0];
if (!tenantName) {
return false;
}
const ciamBaseURL = `https://${tenantName}${CIAM_AUTH_URL}`;
const validCiamPatterns = [
ciamBaseURL,
`${ciamBaseURL}/${tenantName}`,
`${ciamBaseURL}/${tenantName}/v2.0`,
`${ciamBaseURL}/${tenantName}${AAD_TENANT_DOMAIN_SUFFIX}`,
`${ciamBaseURL}/${tenantName}${AAD_TENANT_DOMAIN_SUFFIX}/v2.0`, // https://{tenant}.ciamlogin.com/{tenant}.onmicrosoft.com/v2.0
];
/*
* Compose the canonical issuer string from URL components and strip any
* trailing slashes from the path so it can be compared to the pattern set.
*/
const issuerPath = issuerUrl.pathname.replace(/\/+$/, "");
const normalizedIssuer = `${issuerUrl.protocol}//${issuerUrl.host}${issuerPath}`;
return validCiamPatterns.some((pattern) => pattern === normalizedIssuer);
}
/**
* Checks whether the provided host is that of a public cloud authority
*
* @param authority string
* @returns bool
*/
static isPublicCloudAuthority(host) {
return KNOWN_PUBLIC_CLOUDS.indexOf(host) >= 0;
}
/**
* Rebuild the authority string with the region
*
* @param host string
* @param region string
*/
static buildRegionalAuthorityString(host, region, correlationId, queryString) {
// Create and validate a Url string object with the initial authority string
const authorityUrlInstance = new UrlString(host, correlationId);
authorityUrlInstance.validateAsUri();
const authorityUrlParts = authorityUrlInstance.getUrlComponents();
let hostNameAndPort = `${region}.${authorityUrlParts.HostNameAndPort}`;
if (this.isPublicCloudAuthority(authorityUrlParts.HostNameAndPort)) {
hostNameAndPort = `${region}.${REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX}`;
}
// Include the query string portion of the url
const url = UrlString.constructAuthorityUriFromObject({
...authorityUrlInstance.getUrlComponents(),
HostNameAndPort: hostNameAndPort,
}, correlationId).urlString;
// Add the query string if a query string was provided
if (queryString)
return `${url}?${queryString}`;
return url;
}
/**
* Replace the endpoints in the metadata object with their regional equivalents.
*
* @param metadata OpenIdConfigResponse
* @param azureRegion string
*/
static replaceWithRegionalInformation(metadata, azureRegion, correlationId) {
const regionalMetadata = { ...metadata };
regionalMetadata.authorization_endpoint =
Authority.buildRegionalAuthorityString(regionalMetadata.authorization_endpoint, azureRegion, correlationId);
regionalMetadata.token_endpoint =
Authority.buildRegionalAuthorityString(regionalMetadata.token_endpoint, azureRegion, correlationId);
if (regionalMetadata.end_session_endpoint) {
regionalMetadata.end_session_endpoint =
Authority.buildRegionalAuthorityString(regionalMetadata.end_session_endpoint, azureRegion, correlationId);
}
return regionalMetadata;
}
/**
* Transform CIAM_AUTHORIY as per the below rules:
* If no path segments found and it is a CIAM authority (hostname ends with .ciamlogin.com), then transform it
*
* NOTE: The transformation path should go away once STS supports CIAM with the format: `tenantIdorDomain.ciamlogin.com`
* `ciamlogin.com` can also change in the future and we should accommodate the same
*
* @param authority
*/
static transformCIAMAuthority(authority, correlationId) {
let ciamAuthority = authority;
const authorityUrl = new UrlString(authority, correlationId);
const authorityUrlComponents = authorityUrl.getUrlComponents();
// check if transformation is needed
if (authorityUrlComponents.PathSegments.length === 0 &&
authorityUrlComponents.HostNameAndPort.endsWith(CIAM_AUTH_URL)) {
const tenantIdOrDomain = authorityUrlComponents.HostNameAndPort.split(".")[0];
ciamAuthority = `${ciamAuthority}${tenantIdOrDomain}${AAD_TENANT_DOMAIN_SUFFIX}`;
}
return ciamAuthority;
}
}
// Reserved tenant domain names that will not be replaced with tenant id
Authority.reservedTenantDomains = new Set([
"{tenant}",
"{tenantid}",
AADAuthority.COMMON,
AADAuthority.CONSUMERS,
AADAuthority.ORGANIZATIONS,
]);
/**
* Extract tenantId from authority
*/
function getTenantFromAuthorityString(authority, correlationId) {
const authorityUrl = new UrlString(authority, correlationId);
const authorityUrlComponents = authorityUrl.getUrlComponents();
/**
* For credential matching purposes, tenantId is the last path segment of the authority URL:
* AAD Authority - domain/tenantId -> Credentials are cached with realm = tenantId
* B2C Authority - domain/{tenantId}?/.../policy -> Credentials are cached with realm = policy
* tenantId is downcased because B2C policies can have mixed case but tfp claim is downcased
*
* Note that we may not have any path segments in certain OIDC scenarios.
*/
const tenantId = authorityUrlComponents.PathSegments.slice(-1)[0]?.toLowerCase();
switch (tenantId) {
case AADAuthority.COMMON:
case AADAuthority.ORGANIZATIONS:
case AADAuthority.CONSUMERS:
return undefined;
default:
return tenantId;
}
}
function formatAuthorityUri(authorityUri) {
return authorityUri.endsWith(FORWARD_SLASH)
? authorityUri
: `${authorityUri}${FORWARD_SLASH}`;
}
function buildStaticAuthorityOptions(authOptions) {
const rawCloudDiscoveryMetadata = authOptions.cloudDiscoveryMetadata;
let cloudDiscoveryMetadata = undefined;
if (rawCloudDiscoveryMetadata) {
try {
cloudDiscoveryMetadata = JSON.parse(rawCloudDiscoveryMetadata);
}
catch (e) {
throw createClientConfigurationError(invalidCloudDiscoveryMetadata, "");
}
}
return {
canonicalAuthority: authOptions.authority
? formatAuthorityUri(authOptions.authority)
: undefined,
knownAuthorities: authOptions.knownAuthorities,
cloudDiscoveryMetadata: cloudDiscoveryMetadata,
};
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Create an authority object of the correct type based on the url
* Performs basic authority validation - checks to see if the authority is of a valid type (i.e. aad, b2c, adfs)
*
* Also performs endpoint discovery.
*
* @param authorityUri
* @param networkClient
* @param cacheManager
* @param authorityOptions
* @param logger
* @param correlationId
* @param performanceClient
* @internal
*/
async function createDiscoveredInstance(authorityUri, networkClient, cacheManager, authorityOptions, logger, correlationId, performanceClient) {
const authorityUriFinal = Authority.transformCIAMAuthority(formatAuthorityUri(authorityUri), correlationId);
// Initialize authority and perform discovery endpoint check.
const acquireTokenAuthority = new Authority(authorityUriFinal, networkClient, cacheManager, authorityOptions, logger, correlationId, performanceClient);
try {
await invokeAsync(acquireTokenAuthority.resolveEndpointsAsync.bind(acquireTokenAuthority), AuthorityResolveEndpointsAsync, logger, performanceClient, correlationId)();
return acquireTokenAuthority;
}
catch (e) {
throw createClientAuthError(endpointResolutionError, correlationId);
}
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* 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, correlationId) {
this.correlationId = correlationId;
// 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, correlationId);
}
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, correlationId) {
const scopeString = inputScopeString || "";
const inputScopes = scopeString.split(" ");
return new ScopeSet(inputScopes, correlationId);
}
/**
* Creates the set of scopes to search for in cache lookups
* @param inputScopeString
* @returns
*/
static createSearchScopes(inputScopeString, correlationId) {
// 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, correlationId);
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, this.correlationId);
// 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, this.correlationId);
}
}
/**
* Removes element from set of scopes.
* @param scope
*/
removeScope(scope) {
if (!scope) {
throw createClientAuthError(cannotRemoveEmptyScope, this.correlationId);
}
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, this.correlationId);
}
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, this.correlationId);
}
// 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.14.2 2026-10-06 */
/*
* 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.QUERY);
}
/**
* Add flag to indicate STS should attempt to use WAM if available
*/
function addNativeBroker(parameters) {
parameters.set(NATIVE_BROKER, "1");
}
/**
* add scopes. set addOidcScopes to false to prevent default scopes in non-user scenarios
* @param scopeSet
* @param addOidcScopes
*/
function addScopes(parameters, scopes, correlationId, 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, correlationId);
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);
}
/**
* Adds claims to request parameters, conditionally excluding clientCapabilities
* when skipBrokerClaims is true and a brokered flow is in effect.
* @param parameters - The request parameters map
* @param correlationId - The request correlation id
* @param claims - The claims string from the request
* @param clientCapabilities - The client capabilities from configuration
* @param skipBrokerClaims - When true and BROKER_CLIENT_ID is present, excludes clientCapabilities from claims
* @param claimsToMerge - Optional client-originated claims JSON string (e.g. `claimsFromClient`) deep-merged into `claims` with precedence on conflicts
*/
function addClaims(parameters, correlationId, claims, clientCapabilities, skipBrokerClaims, claimsToMerge) {
// Skip clientCapabilities if skipBrokerClaims is set to true and this is a brokered authentication flow
const configClaims = skipBrokerClaims && parameters.has(BROKER_CLIENT_ID)
? undefined
: clientCapabilities;
const mergedClaims = buildMergedClaims(claims, configClaims, correlationId, claimsToMerge);
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 `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 grant type
* @param grantType
*/
function addGrantType(parameters, grantType) {
parameters.set(GRANT_TYPE, grantType);
}
/**
* add client info
*
*/
function addClientInfo(parameters) {
parameters.set(CLIENT_INFO, "1");
}
/**
* add clidata=1 to request to indicate client data support
*/
function addCliData(parameters) {
parameters.set(CLI_DATA, "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);
}
});
}
/**
* Default optional idToken claims requested on all auth requests.
* signin_state enables KMSI detection; login_hint enables login hint propagation;
* tenant_region_sub_scope identifies the sovereign enclave a tenant belongs to.
*/
const DEFAULT_ID_TOKEN_CLAIMS = {
[ClaimsRequestKeys.SIGNIN_STATE]: { essential: false },
[ClaimsRequestKeys.LOGIN_HINT]: { essential: false },
[ClaimsRequestKeys.TENANT_REGION_SUB_SCOPE]: {
essential: false,
},
};
/**
* Parses a claims JSON string into an object, throwing a ClientConfigurationError
* (error code `invalid_claims`) if the value is not a valid JSON object. The raw
* claims value is never included in the error - it may contain sensitive data.
* @param claims - Claims JSON string. Must be valid JSON representing an object.
* @param correlationId - The request correlation id
* @returns The parsed claims object
*/
function parseClaims(claims, correlationId = "") {
let parsed;
try {
parsed = JSON.parse(claims);
}
catch (e) {
// Malformed JSON
throw createClientConfigurationError(invalidClaims, correlationId);
}
if (!isPlainObject$1(parsed)) {
// Valid JSON, but not an object (e.g. an array, a scalar, or the literal `null`).
throw createClientConfigurationError(invalidClaims, correlationId);
}
return parsed;
}
/**
* Type guard for a non-null, non-array object (a JSON "object" value).
* @param value - The value to test
* @returns True when value is a plain object that can be deep-merged
*/
function isPlainObject$1(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
/**
* Recursively deep-merges two parsed claims objects. Nested objects are merged key-by-key;
* for any other value type (arrays, scalars, null) the value from `claimsToMerge` replaces
* the base. This mirrors the deep merge used by msal-dotnet so that, for example, a server
* `access_token` challenge and a client-originated `access_token` claim are combined rather
* than one clobbering the other.
* @param baseClaims - The parsed base claims object
* @param claimsToMerge - The parsed claims object merged in with precedence
* @returns The deep-merged claims object
*/
function deepMergeClaims(baseClaims, claimsToMerge) {
const merged = { ...baseClaims };
for (const [key, mergeInValue] of Object.entries(claimsToMerge)) {
const baseValue = merged[key];
if (isPlainObject$1(baseValue) && isPlainObject$1(mergeInValue)) {
merged[key] = deepMergeClaims(baseValue, mergeInValue);
}
else {
merged[key] = mergeInValue;
}
}
return merged;
}
/**
* Parses claims JSON, optionally deep-merges a second client-originated claims string
* (`claimsToMerge`, e.g. `claimsFromClient`) with precedence on conflicting keys, merges
* default optional idToken claims (signin_state, login_hint, tenant_region_sub_scope), and appends client
* capabilities (xms_cc) to the access_token section
* Does not overwrite idToken claims already specified by the caller.
* @param claims - Existing claims JSON string from the request (may be undefined)
* @param clientCapabilities - Client capabilities array from configuration
* @param correlationId - The request correlation id
* @param claimsToMerge - Optional second claims JSON string (e.g. client-originated `claimsFromClient`)
* deep-merged into `claims` with precedence on conflicts; parsed and validated when present. Nested
* objects are merged recursively; arrays and scalar values are replaced.
* @returns Merged claims JSON string
*/
function buildMergedClaims(claims, clientCapabilities, correlationId = "", claimsToMerge) {
// Parse provided claims into JSON object or initialize empty object
let mergedClaims = claims ? parseClaims(claims, correlationId) : {};
// Deep-merge client-originated claims (e.g. `claimsFromClient`) with precedence on conflicts
if (claimsToMerge?.trim()) {
mergedClaims = deepMergeClaims(mergedClaims, parseClaims(claimsToMerge, correlationId));
}
// Add default optional idToken claims
if (!Object.prototype.hasOwnProperty.call(mergedClaims, ClaimsRequestKeys.ID_TOKEN)) {
mergedClaims[ClaimsRequestKeys.ID_TOKEN] = {};
}
const idTokenClaims = mergedClaims[ClaimsRequestKeys.ID_TOKEN];
for (const [key, value] of Object.entries(DEFAULT_ID_TOKEN_CLAIMS)) {
if (!(key in idTokenClaims)) {
idTokenClaims[key] = value;
}
}
// Add client capabilities
if (clientCapabilities && clientCapabilities.length > 0) {
if (!Object.prototype.hasOwnProperty.call(mergedClaims, 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);
}
/**
* 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
* @internal
*/
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);
}
}
/**
* Add EAR (Encrypted Authorize Response) request parameters
* @param parameters
* @param jwk
*/
function addEARParameters(parameters, jwk) {
parameters.set(EAR_JWK, encodeURIComponent(jwk));
// ear_jwe_crypto will always have value: {"alg":"dir","enc":"A256GCM"} so we can hardcode this
const jweCryptoB64Encoded = "eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0";
parameters.set(EAR_JWE_CRYPTO, jweCryptoB64Encoded);
}
function addResource(parameters, resource) {
if (resource) {
parameters.set(RESOURCE, resource);
}
}
/**
* Add the `attribute_tokens` parameter to a /token request body.
*
* When `attributeTokens` is a non-empty array the values are sorted lexicographically and joined
* with a single space, then written to the request body. When `attributeTokens` is an empty array
* the parameter is deleted from the request body.
*
* @param parameters - request parameter map that will be serialized into the /token body
* @param attributeTokens - caller-provided attribute token strings
*/
function addAttributeTokens(parameters, attributeTokens) {
const serialized = serializeAttributeTokens(attributeTokens);
if (serialized) {
parameters.set(ATTRIBUTE_TOKENS, serialized);
}
else {
parameters.delete(ATTRIBUTE_TOKENS);
}
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* 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("&");
}
/**
* Normalizes URLs for comparison per MDN & RFC 3986 standards:
* - Hash/fragment is removed
* - Scheme and host are lowercased (case-insensitive per spec)
* - Path and query parameters preserve original casing (case-sensitive per spec)
* - Percent-encoding in pathname is normalized (e.g., %27 and ' are treated equivalently)
* - Ensures pathname ends with /
* Throws a urlParseError if the provided URL is malformed and cannot be parsed.
* @param url - URL to normalize
* @param logger - Optional logger used to log parse failures
* @param correlationId - Optional correlationId associated with the log entry
* @returns Normalized URL string for comparison
*/
function normalizeUrlForComparison(url, logger, correlationId) {
if (!url) {
return url;
}
const urlWithoutHash = url.split("#")[0];
if (!urlWithoutHash) {
return urlWithoutHash;
}
try {
const urlObj = new URL(urlWithoutHash);
// Treat an empty query string (a bare trailing "?") as equivalent to no query
if (!urlObj.search) {
urlObj.search = "";
}
// Decode the pathname to normalize percent-encoding and ensure trailing slash
let pathname;
try {
pathname = decodeURIComponent(urlObj.pathname);
}
catch (e) {
pathname = urlObj.pathname;
}
if (!pathname.endsWith("/")) {
pathname += "/";
}
urlObj.pathname = pathname;
return urlObj.href;
}
catch (e) {
logger?.error(`15apdm ${e}`, correlationId || "");
throw createClientConfigurationError(urlParseError, correlationId || "");
}
}
/**
* Validates that the provided value is a well-formed, parseable absolute URL.
* Throws a urlParseError if the value cannot be parsed by the URL API (e.g. the
* literal string "null", an empty string, or any malformed/relative URL). Use this
* to guard against persisting an invalid value (such as a redirect URL) to the cache.
* @param url - URL to validate
* @param logger - Optional logger used to log validation failures
* @param correlationId - Optional correlationId associated with the log entry
*/
function validateUrl(url, logger, correlationId) {
try {
new URL(url);
}
catch (e) {
logger?.error(`1lrjz7 ${e}`, correlationId || "");
throw createClientConfigurationError(urlParseError, correlationId || "");
}
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Shared JOSE algorithm literals used by MSAL package internals.
* @internal
*/
const JsonWebTokenAlgorithms = {
ES256: "ES256",
RS256: "RS256",
};
/**
* Default crypto implementation used when a platform-specific implementation has
* not been provided.
*/
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 removeTokenBindingKey(kid, correlationId) {
throw createClientAuthError(methodNotImplemented, correlationId);
},
async clearKeystore(correlationId) {
throw createClientAuthError(methodNotImplemented, correlationId);
},
async signTokenBindingJwt(header, payload, kid, correlationId) {
throw createClientAuthError(methodNotImplemented, correlationId);
},
async hashString() {
throw createClientAuthError(methodNotImplemented, "");
},
};
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Default token-binding key manager used when a platform-specific implementation
* has not been provided.
* @internal
*/
const DEFAULT_TOKEN_BINDING_KEY_MANAGER = {
async provisionTokenBindingKey(request) {
throw createClientAuthError(methodNotImplemented, request.correlationId);
},
async removeTokenBindingKey(_kid, correlationId) {
throw createClientAuthError(methodNotImplemented, correlationId);
},
async getTokenBindingPublicKeyJwk(_kid, correlationId) {
throw createClientAuthError(methodNotImplemented, correlationId);
},
};
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* 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 !== undefined) {
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
}
}
/**
* Extracts the leading minification hash from a log message, if present.
*
* Minified messages are produced by the logger-minify rollup plugin and are
* either a bare 6-character alphanumeric hash, or that hash followed by a space
* and runtime variables appended for local (console) logging, e.g.
* "abc123 user-1 popup". Only the leading hash is returned so that telemetry
* never captures the appended variables. Returns null when the message is not
* a minified message.
*/
function getMessageHash(str) {
if (str.length < 6) {
return null;
}
/*
* If the message is longer than the hash, the hash must be delimited by a
* space (the separator the plugin inserts before appended variables).
*/
if (str.length > 6 && str[6] !== " ") {
return null;
}
for (let i = 0; i < 6; i++) {
const char = str[i];
const isAlphaNumeric = (char >= "a" && char <= "z") ||
(char >= "A" && char <= "Z") ||
(char >= "0" && char <= "9");
if (!isAlphaNumeric) {
return null;
}
}
return str.substring(0, 6);
}
/**
* Class which facilitates logging of messages to a specific place.
*/
class Logger {
constructor(loggerOptions, packageName, packageVersion) {
// Current log level, defaults to info.
this.level = exports.LogLevel.Info;
const defaultLoggerCallback = () => {
return;
};
const setLoggerOptions = loggerOptions || Logger.createDefaultLoggerOptions();
this.localCallback =
setLoggerOptions.loggerCallback || defaultLoggerCallback;
this.piiLoggingEnabled = setLoggerOptions.piiLoggingEnabled || false;
this.level =
typeof setLoggerOptions.logLevel === "number"
? setLoggerOptions.logLevel
: exports.LogLevel.Info;
this.packageName = packageName || "";
this.packageVersion = packageVersion || "";
}
static createDefaultLoggerOptions() {
return {
loggerCallback: () => {
// allow users to not set loggerCallback
},
piiLoggingEnabled: false,
logLevel: exports.LogLevel.Info,
};
}
/**
* Create new Logger with existing configurations.
*/
clone(packageName, packageVersion) {
return new Logger({
loggerCallback: this.localCallback,
piiLoggingEnabled: this.piiLoggingEnabled,
logLevel: this.level,
}, packageName, packageVersion);
}
/**
* Log message with required options.
*/
logMessage(logMessage, options) {
const correlationId = options.correlationId;
const messageHash = getMessageHash(logMessage);
if (messageHash) {
const loggedMessage = {
hash: messageHash,
level: options.logLevel,
containsPii: options.containsPii || false,
milliseconds: 0, // Will be calculated in addLogToCache
};
addLogToCache(correlationId, loggedMessage);
}
if (options.logLevel > this.level ||
(!this.piiLoggingEnabled && options.containsPii)) {
return;
}
const timestamp = new Date().toUTCString();
// Add correlationId to logs if set, correlationId provided on log messages take precedence
const logHeader = `[${timestamp}] : [${correlationId}]`;
const log = `${logHeader} : ${this.packageName}@${this.packageVersion} : ${exports.LogLevel[options.logLevel]} - ${logMessage}`;
this.executeCallback(options.logLevel, log, options.containsPii || false);
}
/**
* Execute callback with message.
*/
executeCallback(level, message, containsPii) {
if (this.localCallback) {
this.localCallback(level, message, containsPii);
}
}
/**
* Logs error messages.
*/
error(message, correlationId) {
this.logMessage(message, {
logLevel: exports.LogLevel.Error,
containsPii: false,
correlationId: correlationId,
});
}
/**
* Logs error messages with PII.
*/
errorPii(message, correlationId) {
this.logMessage(message, {
logLevel: exports.LogLevel.Error,
containsPii: true,
correlationId: correlationId,
});
}
/**
* Logs warning messages.
*/
warning(message, correlationId) {
this.logMessage(message, {
logLevel: exports.LogLevel.Warning,
containsPii: false,
correlationId: correlationId,
});
}
/**
* Logs warning messages with PII.
*/
warningPii(message, correlationId) {
this.logMessage(message, {
logLevel: exports.LogLevel.Warning,
containsPii: true,
correlationId: correlationId,
});
}
/**
* Logs info messages.
*/
info(message, correlationId) {
this.logMessage(message, {
logLevel: exports.LogLevel.Info,
containsPii: false,
correlationId: correlationId,
});
}
/**
* Logs info messages with PII.
*/
infoPii(message, correlationId) {
this.logMessage(message, {
logLevel: exports.LogLevel.Info,
containsPii: true,
correlationId: correlationId,
});
}
/**
* Logs verbose messages.
*/
verbose(message, correlationId) {
this.logMessage(message, {
logLevel: exports.LogLevel.Verbose,
containsPii: false,
correlationId: correlationId,
});
}
/**
* Logs verbose messages with PII.
*/
verbosePii(message, correlationId) {
this.logMessage(message, {
logLevel: exports.LogLevel.Verbose,
containsPii: true,
correlationId: correlationId,
});
}
/**
* Logs trace messages.
*/
trace(message, correlationId) {
this.logMessage(message, {
logLevel: exports.LogLevel.Trace,
containsPii: false,
correlationId: correlationId,
});
}
/**
* Logs trace messages with PII.
*/
tracePii(message, correlationId) {
this.logMessage(message, {
logLevel: exports.LogLevel.Trace,
containsPii: true,
correlationId: correlationId,
});
}
/**
* Returns whether PII Logging is enabled or not.
*/
isPiiLoggingEnabled() {
return this.piiLoggingEnabled || false;
}
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/* eslint-disable header/header */
const name$1 = "@azure/msal-common";
const version$1 = "16.14.2";
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const cacheQuotaExceeded = "cache_quota_exceeded";
const cacheErrorUnknown = "cache_error_unknown";
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Error thrown when there is an error with the cache
*/
class CacheError extends Error {
constructor(errorCode, errorMessage) {
const message = errorMessage || getDefaultErrorMessage$1(errorCode);
super(message);
Object.setPrototypeOf(this, CacheError.prototype);
this.name = "CacheError";
this.errorCode = errorCode;
this.errorMessage = message;
}
}
/**
* Helper function to wrap browser errors in a CacheError object
* @param e
* @returns
*/
function createCacheError(e) {
if (!(e instanceof Error)) {
return new CacheError(cacheErrorUnknown);
}
if (e.name === "QuotaExceededError" ||
e.name === "NS_ERROR_DOM_QUOTA_REACHED" ||
e.message.includes("exceeded the quota")) {
return new CacheError(cacheQuotaExceeded);
}
else {
return new CacheError(e.name, e.message);
}
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Interface class which implement cache storage functions used by MSAL to perform validity checks, and store tokens.
* @internal
*/
class CacheManager {
constructor(clientId, cryptoImpl, logger, performanceClient, staticAuthorityOptions, tokenBindingKeyManager) {
this.clientId = clientId;
this.cryptoImpl = cryptoImpl;
this.tokenBindingKeyManager = tokenBindingKeyManager;
this.commonLogger = logger.clone(name$1, version$1);
this.staticAuthorityOptions = staticAuthorityOptions;
this.performanceClient = performanceClient;
}
/**
* Returns all the accounts in the cache that match the optional filter. If no filter is provided, all accounts are returned.
* @param accountFilter - (Optional) filter to narrow down the accounts returned
* @returns Array of AccountInfo objects in cache
*/
getAllAccounts(accountFilter = {}, correlationId) {
return this.buildTenantProfiles(this.getAccountsFilteredBy(accountFilter, correlationId), correlationId, accountFilter);
}
/**
* Gets first tenanted AccountInfo object found based on provided filters
*/
getAccountInfoFilteredBy(accountFilter, correlationId) {
if (Object.keys(accountFilter).length === 0 ||
Object.values(accountFilter).every((value) => value === null || value === undefined || value === "")) {
this.commonLogger.warning("1skb02", correlationId);
return null;
}
const allAccounts = this.getAllAccounts(accountFilter, correlationId);
if (allAccounts.length > 1) {
// If one or more accounts are found, prioritize accounts that have an ID token
const sortedAccounts = allAccounts.sort((a, b) => {
const aHasClaims = a.idTokenClaims ? 1 : 0;
const bHasClaims = b.idTokenClaims ? 1 : 0;
return bHasClaims - aHasClaims;
});
return sortedAccounts[0];
}
else if (allAccounts.length === 1) {
// If only one account is found, return it regardless of whether a matching ID token was found
return allAccounts[0];
}
else {
return null;
}
}
/**
* Returns a single matching
* @param accountFilter
* @returns
*/
getBaseAccountInfo(accountFilter, correlationId) {
const accountEntities = this.getAccountsFilteredBy(accountFilter, correlationId);
if (accountEntities.length > 0) {
return getAccountInfo(accountEntities[0]);
}
else {
return null;
}
}
/**
* Matches filtered account entities with cached ID tokens that match the tenant profile-specific account filters
* and builds the account info objects from the matching ID token's claims
* @param cachedAccounts
* @param accountFilter
* @returns Array of AccountInfo objects that match account and tenant profile filters
*/
buildTenantProfiles(cachedAccounts, correlationId, accountFilter) {
return cachedAccounts.flatMap((accountEntity) => {
return this.getTenantProfilesFromAccountEntity(accountEntity, correlationId, accountFilter?.tenantId, accountFilter);
});
}
getTenantedAccountInfoByFilter(accountInfo, tokenKeys, tenantProfile, correlationId, tenantProfileFilter) {
let tenantedAccountInfo = null;
let idTokenClaims;
if (tenantProfileFilter) {
if (!this.tenantProfileMatchesFilter(tenantProfile, tenantProfileFilter)) {
return null;
}
}
const idToken = this.getIdToken(accountInfo, correlationId, tokenKeys, tenantProfile.tenantId);
if (idToken) {
idTokenClaims = extractTokenClaims(idToken.secret, this.cryptoImpl.base64Decode, correlationId);
if (!this.idTokenClaimsMatchTenantProfileFilter(idTokenClaims, tenantProfileFilter)) {
// ID token sourced claims don't match so this tenant profile is not a match
return null;
}
}
// Expand tenant profile into account info based on matching tenant profile and if available matching ID token claims
tenantedAccountInfo = updateAccountTenantProfileData(accountInfo, tenantProfile, idTokenClaims, idToken?.secret);
return tenantedAccountInfo;
}
getTenantProfilesFromAccountEntity(accountEntity, correlationId, targetTenantId, tenantProfileFilter) {
const accountInfo = getAccountInfo(accountEntity);
let searchTenantProfiles = accountInfo.tenantProfiles || new Map();
const tokenKeys = this.getTokenKeys();
// If a tenant ID was provided, only return the tenant profile for that tenant ID if it exists
if (targetTenantId) {
const tenantProfile = searchTenantProfiles.get(targetTenantId);
if (tenantProfile) {
// Reduce search field to just this tenant profile
searchTenantProfiles = new Map([
[targetTenantId, tenantProfile],
]);
}
else {
// No tenant profile for search tenant ID, return empty array
return [];
}
}
const matchingTenantProfiles = [];
searchTenantProfiles.forEach((tenantProfile) => {
const tenantedAccountInfo = this.getTenantedAccountInfoByFilter(accountInfo, tokenKeys, tenantProfile, correlationId, tenantProfileFilter);
if (tenantedAccountInfo) {
matchingTenantProfiles.push(tenantedAccountInfo);
}
});
return matchingTenantProfiles;
}
tenantProfileMatchesFilter(tenantProfile, tenantProfileFilter) {
if (!!tenantProfileFilter.localAccountId &&
!this.matchLocalAccountIdFromTenantProfile(tenantProfile, tenantProfileFilter.localAccountId)) {
return false;
}
if (!!tenantProfileFilter.name &&
!(tenantProfile.name === tenantProfileFilter.name)) {
return false;
}
if (tenantProfileFilter.isHomeTenant !== undefined &&
!(tenantProfile.isHomeTenant === tenantProfileFilter.isHomeTenant)) {
return false;
}
if (!!tenantProfileFilter.username &&
!this.matchUsername(tenantProfile.username, tenantProfileFilter.username) &&
!this.matchUsername(tenantProfile.upn, tenantProfileFilter.username)) {
return false;
}
if (!!tenantProfileFilter.loginHint &&
!this.matchLoginHintWithTenantProfile(tenantProfile, tenantProfileFilter.loginHint)) {
return false;
}
if (!!tenantProfileFilter.upn &&
!(tenantProfile.upn === tenantProfileFilter.upn)) {
return false;
}
if (!!tenantProfileFilter.nativeAccountId &&
tenantProfile.nativeAccountId !==
tenantProfileFilter.nativeAccountId) {
return false;
}
return true;
}
idTokenClaimsMatchTenantProfileFilter(idTokenClaims, tenantProfileFilter) {
// Tenant Profile filtering
if (tenantProfileFilter) {
if (!!tenantProfileFilter.localAccountId &&
!this.matchLocalAccountIdFromTokenClaims(idTokenClaims, tenantProfileFilter.localAccountId)) {
return false;
}
if (!!tenantProfileFilter.loginHint &&
!this.matchLoginHintFromTokenClaims(idTokenClaims, tenantProfileFilter.loginHint)) {
return false;
}
if (!!tenantProfileFilter.username &&
!this.matchUsername(idTokenClaims.preferred_username, tenantProfileFilter.username) &&
!this.matchUsername(idTokenClaims.upn, tenantProfileFilter.username)) {
return false;
}
if (!!tenantProfileFilter.name &&
!this.matchName(idTokenClaims, tenantProfileFilter.name)) {
return false;
}
if (!!tenantProfileFilter.sid &&
!this.matchSid(idTokenClaims, tenantProfileFilter.sid)) {
return false;
}
}
return true;
}
/**
* saves a cache record
* @param cacheRecord {CacheRecord}
* @param storeInCache {?StoreInCache}
* @param correlationId {?string} correlation id
*/
async saveCacheRecord(cacheRecord, correlationId, kmsi, apiId, storeInCache) {
if (!cacheRecord) {
throw createClientAuthError(invalidCacheRecord, correlationId);
}
try {
if (!!cacheRecord.account) {
await this.setAccount(cacheRecord.account, correlationId, kmsi, apiId);
}
if (!!cacheRecord.idToken && storeInCache?.idToken !== false) {
await this.setIdTokenCredential(cacheRecord.idToken, correlationId, kmsi);
}
if (!!cacheRecord.accessToken &&
storeInCache?.accessToken !== false) {
await this.saveAccessToken(cacheRecord.accessToken, correlationId, kmsi);
}
if (!!cacheRecord.refreshToken &&
storeInCache?.refreshToken !== false) {
await this.setRefreshTokenCredential(cacheRecord.refreshToken, correlationId, kmsi);
}
if (!!cacheRecord.appMetadata) {
this.setAppMetadata(cacheRecord.appMetadata, correlationId);
}
}
catch (e) {
this.commonLogger?.error("0j476p", correlationId);
if (e instanceof AuthError) {
throw e;
}
else {
throw createCacheError(e);
}
}
}
/**
* saves access token credential
* @param credential - the access token entity to save
* @param correlationId - unique identifier for the request
* @param kmsi - keep me signed in flag
*/
async saveAccessToken(credential, correlationId, kmsi) {
// Compute hash from components on the entity itself — no need to thread externally.
let additionalCacheKeyHash;
if (credential.additionalCacheKeyComponents &&
Object.keys(credential.additionalCacheKeyComponents).length > 0) {
additionalCacheKeyHash = await this.cryptoImpl.hashString(JSON.stringify(credential.additionalCacheKeyComponents));
}
const accessTokenFilter = {
clientId: credential.clientId,
credentialType: credential.credentialType,
environment: credential.environment,
homeAccountId: credential.homeAccountId,
realm: credential.realm,
tokenType: credential.tokenType,
};
const tokenKeys = this.getTokenKeys();
const currentScopes = ScopeSet.fromString(credential.target, correlationId);
tokenKeys.accessToken.forEach((key) => {
if (!this.accessTokenKeyMatchesFilter(key, accessTokenFilter, false)) {
return;
}
const tokenEntity = this.getAccessTokenCredential(key, correlationId);
if (tokenEntity &&
this.credentialMatchesFilter(tokenEntity, accessTokenFilter, correlationId)) {
const tokenScopeSet = ScopeSet.fromString(tokenEntity.target, correlationId);
if (tokenScopeSet.intersectingScopeSets(currentScopes)) {
this.removeAccessToken(key, correlationId);
}
}
});
await this.setAccessTokenCredential(credential, correlationId, kmsi, additionalCacheKeyHash);
}
/**
* Retrieve account entities matching all provided tenant-agnostic filters; if no filter is set, get all account entities in the cache
* Not checking for casing as keys are all generated in lower case, remember to convert to lower case if object properties are compared
* @param accountFilter - An object containing Account properties to filter by
*/
getAccountsFilteredBy(accountFilter, correlationId) {
const allAccountKeys = this.getAccountKeys();
const matchingAccounts = [];
allAccountKeys.forEach((cacheKey) => {
const entity = this.getAccount(cacheKey, correlationId);
// Match base account fields
if (!entity) {
return;
}
if (!!accountFilter.homeAccountId &&
!this.matchHomeAccountId(entity, accountFilter.homeAccountId)) {
return;
}
if (!!accountFilter.environment &&
!this.matchEnvironment(entity, accountFilter.environment, correlationId)) {
return;
}
if (!!accountFilter.realm &&
!this.matchRealm(entity, accountFilter.realm)) {
return;
}
if (!!accountFilter.authorityType &&
!this.matchAuthorityType(entity, accountFilter.authorityType)) {
return;
}
// If at least one tenant profile matches the tenant profile filter, add the account to the list of matching accounts
const tenantProfileFilter = {
localAccountId: accountFilter?.localAccountId,
name: accountFilter?.name,
username: accountFilter?.username,
loginHint: accountFilter?.loginHint,
upn: accountFilter?.upn,
nativeAccountId: accountFilter?.nativeAccountId,
};
const matchingTenantProfiles = entity.tenantProfiles?.filter((tenantProfile) => {
return this.tenantProfileMatchesFilter(tenantProfile, tenantProfileFilter);
});
if (matchingTenantProfiles && matchingTenantProfiles.length === 0) {
// No tenant profile for this account matches filter, don't add to list of matching accounts
return;
}
matchingAccounts.push(entity);
});
return matchingAccounts;
}
/**
* Returns whether or not the given credential entity matches the filter
* @param entity
* @param filter
* @param correlationId
* @returns
*/
credentialMatchesFilter(entity, filter, correlationId) {
if (!!filter.clientId && !this.matchClientId(entity, filter.clientId)) {
return false;
}
if (!!filter.userAssertionHash &&
!this.matchUserAssertionHash(entity, filter.userAssertionHash)) {
return false;
}
/*
* homeAccountId can be undefined, and we want to filter out cached items that have a homeAccountId of ""
* because we don't want a client_credential request to return a cached token that has a homeAccountId
*/
if (typeof filter.homeAccountId === "string" &&
!this.matchHomeAccountId(entity, filter.homeAccountId)) {
return false;
}
if (!!filter.environment &&
!this.matchEnvironment(entity, filter.environment, correlationId)) {
return false;
}
if (!!filter.realm && !this.matchRealm(entity, filter.realm)) {
return false;
}
if (!!filter.credentialType &&
!this.matchCredentialType(entity, filter.credentialType)) {
return false;
}
if (!!filter.familyId && !this.matchFamilyId(entity, filter.familyId)) {
return false;
}
/*
* idTokens do not have "target", target specific refreshTokens do exist for some types of authentication
* Resource specific refresh tokens case will be added when the support is deemed necessary
*/
if (!!filter.target &&
!this.matchTarget(entity, filter.target, correlationId)) {
return false;
}
// Access Token with Auth Scheme specific matching
if (entity.credentialType ===
CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME) {
if (!this.matchAccessTokenWithAuthScheme(entity, filter)) {
return false;
}
}
// Additional cache key components matching (bidirectional isolation)
const entityComponents = entity.additionalCacheKeyComponents;
const filterComponents = filter.additionalCacheKeyComponents;
const entityHasComponents = !!entityComponents && Object.keys(entityComponents).length > 0;
const filterHasComponents = !!filterComponents && Object.keys(filterComponents).length > 0;
if (entityHasComponents !== filterHasComponents) {
return false;
}
if (entityHasComponents && filterHasComponents) {
const entityKeys = Object.keys(entityComponents).sort();
const filterKeys = Object.keys(filterComponents).sort();
if (entityKeys.length !== filterKeys.length) {
return false;
}
for (let i = 0; i < entityKeys.length; i++) {
if (entityKeys[i] !== filterKeys[i] ||
entityComponents[entityKeys[i]] !==
filterComponents[filterKeys[i]]) {
return false;
}
}
}
return true;
}
/**
* retrieve appMetadata matching all provided filters; if no filter is set, get all appMetadata
* @param filter
* @param correlationId
*/
getAppMetadataFilteredBy(filter, correlationId) {
const allCacheKeys = this.getKeys();
const matchingAppMetadata = {};
allCacheKeys.forEach((cacheKey) => {
// don't parse any non-appMetadata type cache entities
if (!this.isAppMetadata(cacheKey)) {
return;
}
// Attempt retrieval
const entity = this.getAppMetadata(cacheKey, correlationId);
if (!entity) {
return;
}
if (!!filter.environment &&
!this.matchEnvironment(entity, filter.environment, correlationId)) {
return;
}
if (!!filter.clientId &&
!this.matchClientId(entity, filter.clientId)) {
return;
}
matchingAppMetadata[cacheKey] = entity;
});
return matchingAppMetadata;
}
/**
* retrieve authorityMetadata that contains a matching alias
* @param host
* @param correlationId
*/
getAuthorityMetadataByAlias(host, correlationId) {
const allCacheKeys = this.getAuthorityMetadataKeys();
let matchedEntity = null;
allCacheKeys.forEach((cacheKey) => {
// don't parse any non-authorityMetadata type cache entities
if (!this.isAuthorityMetadata(cacheKey) ||
cacheKey.indexOf(this.clientId) === -1) {
return;
}
// Attempt retrieval
const entity = this.getAuthorityMetadata(cacheKey, correlationId);
if (!entity) {
return;
}
if (entity.aliases.indexOf(host) === -1) {
return;
}
matchedEntity = entity;
});
return matchedEntity;
}
/**
* Removes all accounts and related tokens from cache.
*/
removeAllAccounts(correlationId) {
const accounts = this.getAllAccounts({}, correlationId);
accounts.forEach((account) => {
this.removeAccount(account, correlationId);
});
}
/**
* Removes the account and related tokens for a given account key
* @param account
*/
removeAccount(account, correlationId) {
this.removeAccountContext(account, correlationId);
const accountKeys = this.getAccountKeys();
const keyFilter = (key) => {
return (key.includes(account.homeAccountId) &&
key.includes(account.environment));
};
accountKeys.filter(keyFilter).forEach((key) => {
this.removeItem(key, correlationId);
this.performanceClient.incrementFields({ accountsRemoved: 1 }, correlationId);
});
}
/**
* Removes credentials associated with the provided account
* @param account
*/
removeAccountContext(account, correlationId) {
const allTokenKeys = this.getTokenKeys();
const keyFilter = (key) => {
return (key.includes(account.homeAccountId) &&
key.includes(account.environment));
};
allTokenKeys.idToken.filter(keyFilter).forEach((key) => {
this.removeIdToken(key, correlationId);
});
allTokenKeys.accessToken.filter(keyFilter).forEach((key) => {
this.removeAccessToken(key, correlationId);
});
allTokenKeys.refreshToken.filter(keyFilter).forEach((key) => {
this.removeRefreshToken(key, correlationId);
});
}
/**
* returns a boolean if the given credential is removed
* @param key
* @param correlationId
*/
removeAccessToken(key, correlationId) {
const credential = this.getAccessTokenCredential(key, correlationId);
if (!credential) {
return;
}
this.removeItem(key, correlationId);
this.performanceClient.incrementFields({ accessTokensRemoved: 1 }, correlationId);
// Remove Token Binding Key from key store for token-bound access token credentials
if (credential.credentialType.toLowerCase() ===
CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME.toLowerCase()) {
const tokenType = credential.tokenType?.toLowerCase();
switch (tokenType) {
case AuthenticationScheme.POP:
case AuthenticationScheme.DPOP.toLowerCase(): {
const accessTokenWithAuthSchemeEntity = credential;
const kid = accessTokenWithAuthSchemeEntity.keyId;
if (kid) {
void this.tokenBindingKeyManager
.removeTokenBindingKey(kid, correlationId)
.catch(() => {
this.commonLogger.error("0id34f", correlationId);
this.performanceClient?.incrementFields({ removeTokenBindingKeyFailure: 1 }, correlationId);
});
}
break;
}
}
}
}
/**
* Removes all app metadata objects from cache.
*/
removeAppMetadata(correlationId) {
const allCacheKeys = this.getKeys();
allCacheKeys.forEach((cacheKey) => {
if (this.isAppMetadata(cacheKey)) {
this.removeItem(cacheKey, correlationId);
}
});
return true;
}
/**
* Retrieve IdTokenEntity from cache
* @param account {AccountInfo}
* @param tokenKeys {?TokenKeys}
* @param targetRealm {?string}
* @param performanceClient {?IPerformanceClient}
* @param correlationId {?string}
*/
getIdToken(account, correlationId, tokenKeys, targetRealm) {
this.commonLogger.trace("1drz22", correlationId);
const idTokenFilter = {
homeAccountId: account.homeAccountId,
environment: account.environment,
credentialType: CredentialType.ID_TOKEN,
clientId: this.clientId,
realm: targetRealm,
};
const idTokenMap = this.getIdTokensByFilter(idTokenFilter, correlationId, tokenKeys);
const numIdTokens = idTokenMap.size;
if (numIdTokens < 1) {
this.commonLogger.info("1atvtd", correlationId);
return null;
}
else if (numIdTokens > 1) {
let tokensToBeRemoved = idTokenMap;
// Multiple tenant profiles and no tenant specified, pick home account
if (!targetRealm) {
const homeIdTokenMap = new Map();
idTokenMap.forEach((idToken, key) => {
if (idToken.realm === account.tenantId) {
homeIdTokenMap.set(key, idToken);
}
});
const numHomeIdTokens = homeIdTokenMap.size;
if (numHomeIdTokens < 1) {
this.commonLogger.info("0ooalx", correlationId);
return idTokenMap.values().next().value ?? null;
}
else if (numHomeIdTokens === 1) {
this.commonLogger.info("1eq2vc", correlationId);
return homeIdTokenMap.values().next().value ?? null;
}
else {
// Multiple ID tokens for home tenant profile, remove all and return null
tokensToBeRemoved = homeIdTokenMap;
}
}
// Multiple tokens for a single tenant profile, remove all and return null
this.commonLogger.info("1ws328", correlationId);
tokensToBeRemoved.forEach((idToken, key) => {
this.removeIdToken(key, correlationId);
});
this.performanceClient.addFields({ multiMatchedID: idTokenMap.size }, correlationId);
return null;
}
this.commonLogger.info("1sm769", correlationId);
return idTokenMap.values().next().value ?? null;
}
/**
* Gets all idTokens matching the given filter
* @param filter
* @returns
*/
getIdTokensByFilter(filter, correlationId, tokenKeys) {
const idTokenKeys = (tokenKeys && tokenKeys.idToken) || this.getTokenKeys().idToken;
const idTokens = new Map();
idTokenKeys.forEach((key) => {
if (!this.idTokenKeyMatchesFilter(key, {
clientId: this.clientId,
...filter,
})) {
return;
}
const idToken = this.getIdTokenCredential(key, correlationId);
if (idToken &&
this.credentialMatchesFilter(idToken, filter, correlationId)) {
idTokens.set(key, idToken);
}
});
return idTokens;
}
/**
* Validate the cache key against filter before retrieving and parsing cache value
* @param key
* @param filter
* @returns
*/
idTokenKeyMatchesFilter(inputKey, filter) {
const key = inputKey.toLowerCase();
if (filter.clientId &&
key.indexOf(filter.clientId.toLowerCase()) === -1) {
return false;
}
if (filter.homeAccountId &&
key.indexOf(filter.homeAccountId.toLowerCase()) === -1) {
return false;
}
return true;
}
/**
* Removes idToken from the cache
* @param key
*/
removeIdToken(key, correlationId) {
this.removeItem(key, correlationId);
}
/**
* Removes refresh token from the cache
* @param key
*/
removeRefreshToken(key, correlationId) {
this.removeItem(key, correlationId);
}
/**
* Retrieve AccessTokenEntity from cache
* @param account {AccountInfo}
* @param request {BaseAuthRequest}
* @param tokenKeys {?TokenKeys}
* @param performanceClient {?IPerformanceClient}
*/
getAccessToken(account, request, tokenKeys, targetRealm) {
const correlationId = request.correlationId;
this.commonLogger.trace("1t7hz1", correlationId);
const scopes = ScopeSet.createSearchScopes(request.scopes, correlationId);
const authScheme = request.authenticationScheme ||
AuthenticationScheme.BEARER;
/*
* Distinguish between Bearer and PoP/SSH token cache types
* Cast to lowercase to handle "bearer" from ADFS
*/
const credentialType = authScheme.toLowerCase() !==
AuthenticationScheme.BEARER.toLowerCase()
? CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME
: CredentialType.ACCESS_TOKEN;
const attributeTokenPartition = serializeAttributeTokens(request.attributeTokens);
const additionalCacheKeyComponents = attributeTokenPartition
? {
attribute_tokens: attributeTokenPartition,
}
: undefined;
const accessTokenFilter = {
homeAccountId: account.homeAccountId,
environment: account.environment,
credentialType: credentialType,
clientId: this.clientId,
realm: targetRealm || account.tenantId,
target: scopes,
tokenType: authScheme,
keyId: authScheme === AuthenticationScheme.SSH
? request.sshKid
: undefined,
additionalCacheKeyComponents: additionalCacheKeyComponents,
};
const accessTokenKeys = (tokenKeys && tokenKeys.accessToken) ||
this.getTokenKeys().accessToken;
const accessTokens = [];
const matchedKeys = [];
accessTokenKeys.forEach((key) => {
// Validate key
if (this.accessTokenKeyMatchesFilter(key, accessTokenFilter, true)) {
const accessToken = this.getAccessTokenCredential(key, correlationId);
// Validate value
if (accessToken &&
this.credentialMatchesFilter(accessToken, accessTokenFilter, correlationId)) {
accessTokens.push(accessToken);
matchedKeys.push(key);
}
}
});
if (accessTokens.length < 1) {
this.commonLogger.info("1nckna", correlationId);
return null;
}
else if (accessTokens.length > 1) {
this.commonLogger.info("1wkfwp", correlationId);
matchedKeys.forEach((key) => {
this.removeAccessToken(key, correlationId);
});
this.performanceClient.addFields({ multiMatchedAT: accessTokens.length }, correlationId);
return null;
}
this.commonLogger.info("06yt98", correlationId);
return accessTokens[0];
}
/**
* Validate the cache key against filter before retrieving and parsing cache value
* @param key
* @param filter
* @param keyMustContainAllScopes
* @returns
*/
accessTokenKeyMatchesFilter(inputKey, filter, keyMustContainAllScopes) {
const key = inputKey.toLowerCase();
if (filter.clientId &&
key.indexOf(filter.clientId.toLowerCase()) === -1) {
return false;
}
if (filter.homeAccountId &&
key.indexOf(filter.homeAccountId.toLowerCase()) === -1) {
return false;
}
if (filter.realm && key.indexOf(filter.realm.toLowerCase()) === -1) {
return false;
}
if (filter.target) {
const scopes = filter.target.asArray();
for (let i = 0; i < scopes.length; i++) {
if (keyMustContainAllScopes &&
!key.includes(scopes[i].toLowerCase())) {
// When performing a cache lookup a missing scope would be a cache miss
return false;
}
else if (!keyMustContainAllScopes &&
key.includes(scopes[i].toLowerCase())) {
// When performing a cache write, any token with a subset of requested scopes should be replaced
return true;
}
}
}
return true;
}
/**
* Gets all access tokens matching the filter
* @param filter
* @returns
*/
getAccessTokensByFilter(filter, correlationId) {
const tokenKeys = this.getTokenKeys();
const accessTokens = [];
tokenKeys.accessToken.forEach((key) => {
if (!this.accessTokenKeyMatchesFilter(key, filter, true)) {
return;
}
const accessToken = this.getAccessTokenCredential(key, correlationId);
if (accessToken &&
this.credentialMatchesFilter(accessToken, filter, correlationId)) {
accessTokens.push(accessToken);
}
});
return accessTokens;
}
/**
* Helper to retrieve the appropriate refresh token from cache
* @param account {AccountInfo}
* @param familyRT {boolean}
* @param tokenKeys {?TokenKeys}
* @param performanceClient {?IPerformanceClient}
* @param correlationId {?string}
*/
getRefreshToken(account, familyRT, correlationId, tokenKeys) {
this.commonLogger.trace("0x53vi", correlationId);
const id = familyRT ? THE_FAMILY_ID : undefined;
const refreshTokenFilter = {
homeAccountId: account.homeAccountId,
environment: account.environment,
credentialType: CredentialType.REFRESH_TOKEN,
clientId: this.clientId,
familyId: id,
};
const refreshTokenKeys = (tokenKeys && tokenKeys.refreshToken) ||
this.getTokenKeys().refreshToken;
const refreshTokens = [];
refreshTokenKeys.forEach((key) => {
// Validate key
if (this.refreshTokenKeyMatchesFilter(key, refreshTokenFilter)) {
const refreshToken = this.getRefreshTokenCredential(key, correlationId);
// Validate value
if (refreshToken &&
this.credentialMatchesFilter(refreshToken, refreshTokenFilter, correlationId)) {
refreshTokens.push(refreshToken);
}
}
});
const numRefreshTokens = refreshTokens.length;
if (numRefreshTokens < 1) {
this.commonLogger.info("0dlw11", correlationId);
return null;
}
// address the else case after remove functions address environment aliases
if (numRefreshTokens > 1) {
this.performanceClient.addFields({ multiMatchedRT: numRefreshTokens }, correlationId);
}
this.commonLogger.info("0wcnep", correlationId);
return refreshTokens[0];
}
/**
* Validate the cache key against filter before retrieving and parsing cache value
* @param key
* @param filter
*/
refreshTokenKeyMatchesFilter(inputKey, filter) {
const key = inputKey.toLowerCase();
if (filter.familyId &&
key.indexOf(filter.familyId.toLowerCase()) === -1) {
return false;
}
// If familyId is used, clientId is not in the key
if (!filter.familyId &&
filter.clientId &&
key.indexOf(filter.clientId.toLowerCase()) === -1) {
return false;
}
if (filter.homeAccountId &&
key.indexOf(filter.homeAccountId.toLowerCase()) === -1) {
return false;
}
return true;
}
/**
* Retrieve AppMetadataEntity from cache
*/
readAppMetadataFromCache(environment, correlationId) {
const appMetadataFilter = {
environment,
clientId: this.clientId,
};
const appMetadata = this.getAppMetadataFilteredBy(appMetadataFilter, correlationId);
const appMetadataEntries = Object.keys(appMetadata).map((key) => appMetadata[key]);
const numAppMetadata = appMetadataEntries.length;
if (numAppMetadata < 1) {
return null;
}
else if (numAppMetadata > 1) {
throw createClientAuthError(multipleMatchingAppMetadata, correlationId);
}
return appMetadataEntries[0];
}
/**
* Return the family_id value associated with FOCI
* @param environment
* @param clientId
*/
isAppMetadataFOCI(environment, correlationId) {
const appMetadata = this.readAppMetadataFromCache(environment, correlationId);
return !!(appMetadata && appMetadata.familyId === THE_FAMILY_ID);
}
/**
* helper to match account ids
* @param value
* @param homeAccountId
*/
matchHomeAccountId(entity, homeAccountId) {
return !!(typeof entity.homeAccountId === "string" &&
homeAccountId === entity.homeAccountId);
}
/**
* helper to match account ids
* @param entity
* @param localAccountId
* @returns
*/
matchLocalAccountIdFromTokenClaims(tokenClaims, localAccountId) {
const idTokenLocalAccountId = tokenClaims.oid || tokenClaims.sub;
return localAccountId === idTokenLocalAccountId;
}
matchLocalAccountIdFromTenantProfile(tenantProfile, localAccountId) {
return tenantProfile.localAccountId === localAccountId;
}
/**
* helper to match names
* @param entity
* @param name
* @returns true if the downcased name properties are present and match in the filter and the entity
*/
matchName(claims, name) {
return !!(name.toLowerCase() === claims.name?.toLowerCase());
}
/**
* helper to match usernames
* @param entity
* @param username
* @returns
*/
matchUsername(cachedUsername, filterUsername) {
return !!(cachedUsername &&
typeof cachedUsername === "string" &&
filterUsername?.toLowerCase() === cachedUsername.toLowerCase());
}
/**
* helper to match loginhints
* @param entity
* @param loginHint
* @returns
*/
matchLoginHintWithTenantProfile(tenantProfile, loginHintFilter) {
return (tenantProfile.loginHint === loginHintFilter ||
tenantProfile.username === loginHintFilter ||
tenantProfile.upn === loginHintFilter);
}
/**
* helper to match assertion
* @param value
* @param oboAssertion
*/
matchUserAssertionHash(entity, userAssertionHash) {
return !!(entity.userAssertionHash &&
userAssertionHash === entity.userAssertionHash);
}
/**
* helper to match environment
* @param value
* @param environment
*/
matchEnvironment(entity, environment, correlationId) {
// Check static authority options first for cases where authority metadata has not been resolved and cached yet
if (this.staticAuthorityOptions) {
const staticAliases = getAliasesFromStaticSources(this.staticAuthorityOptions, this.commonLogger, correlationId);
if (staticAliases.includes(environment) &&
staticAliases.includes(entity.environment)) {
return true;
}
}
// Query metadata cache if no static authority configuration has aliases that match enviroment
const cloudMetadata = this.getAuthorityMetadataByAlias(environment, correlationId);
if (cloudMetadata &&
cloudMetadata.aliases.indexOf(entity.environment) > -1) {
return true;
}
return false;
}
/**
* helper to match credential type
* @param entity
* @param credentialType
*/
matchCredentialType(entity, credentialType) {
return (entity.credentialType &&
credentialType.toLowerCase() === entity.credentialType.toLowerCase());
}
/**
* helper to match client ids
* @param entity
* @param clientId
*/
matchClientId(entity, clientId) {
return !!(entity.clientId && clientId === entity.clientId);
}
/**
* helper to match family ids
* @param entity
* @param familyId
*/
matchFamilyId(entity, familyId) {
return !!(entity.familyId && familyId === entity.familyId);
}
/**
* helper to match realm
* @param entity
* @param realm
*/
matchRealm(entity, realm) {
return !!(entity.realm?.toLowerCase() === realm.toLowerCase());
}
/**
* helper to match loginHint which can be either:
* 1. login_hint ID token claim
* 2. username in cached account object
* 3. upn in ID token claims
* @param entity
* @param loginHint
* @returns
*/
matchLoginHintFromTokenClaims(tokenClaims, loginHint) {
if (tokenClaims.login_hint === loginHint) {
return true;
}
if (tokenClaims.preferred_username === loginHint) {
return true;
}
if (tokenClaims.upn === loginHint) {
return true;
}
// check login hint against list of emails in token claims
if (tokenClaims.emails && tokenClaims.emails.includes(loginHint)) {
return true;
}
return false;
}
/**
* Helper to match sid
* @param entity
* @param sid
* @returns true if the sid claim is present and matches the filter
*/
matchSid(idTokenClaims, sid) {
return idTokenClaims.sid === sid;
}
matchAuthorityType(entity, authorityType) {
return !!(entity.authorityType &&
authorityType.toLowerCase() === entity.authorityType.toLowerCase());
}
/**
* Returns true if the target scopes are a subset of the current entity's scopes, false otherwise.
* @param entity
* @param target
*/
matchTarget(entity, target, correlationId) {
const isNotAccessTokenCredential = entity.credentialType !== CredentialType.ACCESS_TOKEN &&
entity.credentialType !==
CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME;
if (isNotAccessTokenCredential || !entity.target) {
return false;
}
const entityScopeSet = ScopeSet.fromString(entity.target, correlationId);
return entityScopeSet.containsScopeSet(target);
}
/**
* Returns true if the credential's tokenType or Authentication Scheme matches the one in the request, false otherwise
* @param entity
* @param tokenType
*/
matchTokenType(entity, tokenType) {
return !!(entity.tokenType &&
entity.tokenType.toLowerCase() === tokenType.toLowerCase());
}
matchAccessTokenWithAuthScheme(entity, filter) {
const normalizedFilterTokenType = filter.tokenType?.toLowerCase();
if (!!filter.tokenType &&
!this.matchTokenType(entity, filter.tokenType)) {
return false;
}
switch (normalizedFilterTokenType) {
case "dpop":
case AuthenticationScheme.SSH:
return this.matchKeyBoundAccessToken(entity, filter);
default:
return true;
}
}
matchKeyBoundAccessToken(entity, filter) {
if (!filter.keyId) {
return true;
}
return this.matchKeyId(entity, filter.keyId);
}
/**
* Returns true if the credential's keyId matches the one in the request, false otherwise
* @param entity
* @param keyId
*/
matchKeyId(entity, keyId) {
return !!(entity.keyId && entity.keyId === keyId);
}
/**
* returns if a given cache entity is of the type appmetadata
* @param key
*/
isAppMetadata(key) {
return key.indexOf(APP_METADATA) !== -1;
}
/**
* returns if a given cache entity is of the type authoritymetadata
* @param key
*/
isAuthorityMetadata(key) {
return key.indexOf(AUTHORITY_METADATA_CACHE_KEY) !== -1;
}
/**
* returns cache key used for cloud instance metadata
*/
generateAuthorityMetadataCacheKey(authority) {
return `${AUTHORITY_METADATA_CACHE_KEY}-${this.clientId}-${authority}`;
}
/**
* Helper to convert serialized data to object
* @param obj
* @param json
*/
static toObject(obj, json) {
for (const propertyName in json) {
obj[propertyName] = json[propertyName];
}
return obj;
}
}
/** @internal */
class DefaultStorageClass extends CacheManager {
async setAccount() {
throw createClientAuthError(methodNotImplemented, "");
}
getAccount() {
throw createClientAuthError(methodNotImplemented, "");
}
async setIdTokenCredential() {
throw createClientAuthError(methodNotImplemented, "");
}
getIdTokenCredential() {
throw createClientAuthError(methodNotImplemented, "");
}
async setAccessTokenCredential() {
throw createClientAuthError(methodNotImplemented, "");
}
getAccessTokenCredential() {
throw createClientAuthError(methodNotImplemented, "");
}
async setRefreshTokenCredential() {
throw createClientAuthError(methodNotImplemented, "");
}
getRefreshTokenCredential() {
throw createClientAuthError(methodNotImplemented, "");
}
setAppMetadata() {
throw createClientAuthError(methodNotImplemented, "");
}
getAppMetadata() {
throw createClientAuthError(methodNotImplemented, "");
}
setServerTelemetry() {
throw createClientAuthError(methodNotImplemented, "");
}
getServerTelemetry() {
throw createClientAuthError(methodNotImplemented, "");
}
setAuthorityMetadata() {
throw createClientAuthError(methodNotImplemented, "");
}
getAuthorityMetadata() {
throw createClientAuthError(methodNotImplemented, "");
}
getAuthorityMetadataKeys() {
throw createClientAuthError(methodNotImplemented, "");
}
setThrottlingCache() {
throw createClientAuthError(methodNotImplemented, "");
}
getThrottlingCache() {
throw createClientAuthError(methodNotImplemented, "");
}
removeItem() {
throw createClientAuthError(methodNotImplemented, "");
}
getKeys() {
throw createClientAuthError(methodNotImplemented, "");
}
getAccountKeys() {
throw createClientAuthError(methodNotImplemented, "");
}
getTokenKeys() {
throw createClientAuthError(methodNotImplemented, "");
}
/* eslint-disable @typescript-eslint/no-unused-vars */
generateCredentialKey(_credential, _hash) {
/* eslint-enable @typescript-eslint/no-unused-vars */
throw createClientAuthError(methodNotImplemented, "");
}
generateAccountKey() {
throw createClientAuthError(methodNotImplemented, "");
}
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* State of the performance event.
*
* @export
* @enum {number}
*/
const PerformanceEventStatus = {
InProgress: 1};
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class StubPerformanceClient {
generateId() {
return "callback-id";
}
startMeasurement(measureName, correlationId) {
return {
end: () => null,
discard: () => { },
add: () => { },
increment: () => { },
event: {
eventId: this.generateId(),
status: PerformanceEventStatus.InProgress,
authority: "",
libraryName: "",
libraryVersion: "",
clientId: "",
name: measureName,
startTimeMs: Date.now(),
correlationId: correlationId || "",
},
};
}
endMeasurement() {
return null;
}
discardMeasurements() {
return;
}
removePerformanceCallback() {
return true;
}
addPerformanceCallback() {
return "";
}
emitEvents() {
return;
}
addFields() {
return;
}
addGlobalFields() {
return;
}
incrementFields() {
return;
}
cacheEventByCorrelationId() {
return;
}
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const DEFAULT_SYSTEM_OPTIONS = {
tokenRenewalOffsetSeconds: DEFAULT_TOKEN_RENEWAL_OFFSET_SEC,
preventCorsPreflight: false,
};
const DEFAULT_LOGGER_IMPLEMENTATION = {
loggerCallback: () => {
// allow users to not set loggerCallback
},
piiLoggingEnabled: false,
logLevel: exports.LogLevel.Info,
correlationId: "",
};
const DEFAULT_NETWORK_IMPLEMENTATION = {
async sendGetRequestAsync() {
throw createClientAuthError(methodNotImplemented, "");
},
async sendPostRequestAsync() {
throw createClientAuthError(methodNotImplemented, "");
},
};
const DEFAULT_LIBRARY_INFO = {
sku: SKU,
version: version$1,
cpu: "",
os: "",
};
const DEFAULT_CLIENT_CREDENTIALS = {
clientSecret: "",
clientAssertion: undefined,
};
const DEFAULT_AZURE_CLOUD_OPTIONS = {
azureCloudInstance: AzureCloudInstance.None,
tenant: `${DEFAULT_COMMON_TENANT}`,
};
const DEFAULT_TELEMETRY_OPTIONS = {
application: {
appName: "",
appVersion: "",
},
};
/**
* Function that sets the default options when not explicitly configured from app developer
*
* @param Configuration
*
* @returns Configuration
* @internal
*/
function buildClientConfiguration({ authOptions: userAuthOptions, systemOptions: userSystemOptions, loggerOptions: userLoggerOption, storageInterface: storageImplementation, networkInterface: networkImplementation, cryptoInterface: cryptoImplementation, tokenBindingKeyManager: tokenBindingKeyManager, clientCredentials: clientCredentials, libraryInfo: libraryInfo, telemetry: telemetry, serverTelemetryManager: serverTelemetryManager, persistencePlugin: persistencePlugin, serializableCache: serializableCache, }) {
const loggerOptions = {
...DEFAULT_LOGGER_IMPLEMENTATION,
...userLoggerOption,
};
const resolvedTokenBindingKeyManager = tokenBindingKeyManager || DEFAULT_TOKEN_BINDING_KEY_MANAGER;
return {
authOptions: buildAuthOptions(userAuthOptions),
systemOptions: { ...DEFAULT_SYSTEM_OPTIONS, ...userSystemOptions },
loggerOptions: loggerOptions,
storageInterface: storageImplementation ||
new DefaultStorageClass(userAuthOptions.clientId, DEFAULT_CRYPTO_IMPLEMENTATION, new Logger(loggerOptions, name$1, version$1), new StubPerformanceClient(), undefined, resolvedTokenBindingKeyManager),
networkInterface: networkImplementation || DEFAULT_NETWORK_IMPLEMENTATION,
cryptoInterface: cryptoImplementation || DEFAULT_CRYPTO_IMPLEMENTATION,
tokenBindingKeyManager: resolvedTokenBindingKeyManager,
clientCredentials: clientCredentials || DEFAULT_CLIENT_CREDENTIALS,
libraryInfo: { ...DEFAULT_LIBRARY_INFO, ...libraryInfo },
telemetry: { ...DEFAULT_TELEMETRY_OPTIONS, ...telemetry },
serverTelemetryManager: serverTelemetryManager || null,
persistencePlugin: persistencePlugin || null,
serializableCache: serializableCache || null,
};
}
/**
* Construct authoptions from the client and platform passed values
* @param authOptions
*/
function buildAuthOptions(authOptions) {
return {
clientCapabilities: [],
azureCloudOptions: DEFAULT_AZURE_CLOUD_OPTIONS,
instanceAware: false,
isMcp: false,
...authOptions,
};
}
/**
* Returns true if config has protocolMode set to ProtocolMode.OIDC, false otherwise
* @param ClientConfiguration
*/
function isOidcProtocolMode(config) {
return (config.authOptions.authority.options.protocolMode === ProtocolMode.OIDC);
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* This class instance helps track the memory changes facilitating
* decisions to read from and write to the persistent cache
*/ class TokenCacheContext {
constructor(tokenCache, hasChanged) {
this.cache = tokenCache;
this.hasChanged = hasChanged;
}
/**
* boolean which indicates the changes in cache
*/
get cacheHasChanged() {
return this.hasChanged;
}
/**
* function to retrieve the token cache
*/
get tokenCache() {
return this.cache;
}
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Error thrown when there is an error in the client code running on the browser.
*/
class JoseHeaderError extends AuthError {
constructor(errorCode, correlationId, errorMessage) {
super(errorCode, correlationId, errorMessage);
this.name = "JoseHeaderError";
Object.setPrototypeOf(this, JoseHeaderError.prototype);
}
}
/** Returns JoseHeaderError object */
function createJoseHeaderError(code, correlationId) {
return new JoseHeaderError(code, correlationId);
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Checks whether a value is a plain JSON-like object.
* Allows objects with null prototypes, but rejects arrays and object subclasses.
*/
function isPlainObject(value) {
if (typeof value !== "object" ||
value === null ||
Object.prototype.toString.call(value) !== "[object Object]") {
return false;
}
if (Object.getPrototypeOf(value) === null) {
return true;
}
let proto = value;
while (Object.getPrototypeOf(proto) !== null) {
proto = Object.getPrototypeOf(proto);
}
return Object.getPrototypeOf(value) === proto;
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const missingKidError = "missing_kid_error";
const missingAlgError = "missing_alg_error";
const missingJwkError = "missing_jwk_error";
const invalidJwkError = "invalid_jwk_error";
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/** @internal */
class JoseHeader {
constructor(options, correlationId) {
if (typeof options.alg !== "string" || !options.alg) {
throw createJoseHeaderError(missingAlgError, correlationId);
}
this.typ = options.typ;
this.alg = options.alg;
this.kid = options.kid;
this.jwk = options.jwk;
}
/**
* Builds SignedHttpRequest formatted JOSE Header from the
* JOSE Header options provided or previously set on the object.
* Throws if keyId or algorithm aren't provided since they are required for Access Token Binding.
* @param shrHeaderOptions
* @param correlationId
* @returns
*/
static getShrHeader(shrHeaderOptions, correlationId) {
// KeyID is required on the SHR header
if (!shrHeaderOptions.kid) {
throw createJoseHeaderError(missingKidError, correlationId);
}
// Alg is required on the SHR header
if (!shrHeaderOptions.alg) {
throw createJoseHeaderError(missingAlgError, correlationId);
}
return new JoseHeader({
// Access Token PoP headers must have type pop, but the type header can be overriden for special cases
typ: shrHeaderOptions.typ || JsonWebTokenTypes.Pop,
kid: shrHeaderOptions.kid,
alg: shrHeaderOptions.alg,
}, correlationId);
}
/**
* Builds a DPoP formatted JOSE Header from the JOSE Header options provided.
* Throws if public JWK or algorithm aren't provided since they are required for DPoP.
* @param dpopHeaderOptions
* @param correlationId
* @returns
*/
static getDpopHeader(dpopHeaderOptions, correlationId) {
if (!isPlainObject(dpopHeaderOptions.jwk)) {
throw createJoseHeaderError(missingJwkError, correlationId);
}
if (!dpopHeaderOptions.alg) {
throw createJoseHeaderError(missingAlgError, correlationId);
}
if (Object.keys(dpopHeaderOptions.jwk).length === 0) {
throw createJoseHeaderError(invalidJwkError, correlationId);
}
return new JoseHeader({
typ: JsonWebTokenTypes.Dpop,
alg: dpopHeaderOptions.alg,
jwk: dpopHeaderOptions.jwk,
}, correlationId);
}
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const KeyLocation = {
SW: "sw"};
const SHR_TOKEN_BINDING_KEY_TYPE = "shr";
const SHR_TOKEN_BINDING_KEY_ALGORITHM = JsonWebTokenAlgorithms.RS256;
/** @internal */
class PopTokenGenerator {
constructor(cryptoUtils, tokenBindingKeyManager, performanceClient) {
this.cryptoUtils = cryptoUtils;
this.tokenBindingKeyManager = tokenBindingKeyManager;
this.performanceClient = performanceClient;
}
/**
* Generates the req_cnf validated at the RP in the POP protocol for SHR parameters
* and returns an object containing the keyid, the full req_cnf string and the req_cnf string hash
* @param request
* @returns
*/
async generateCnf(request, logger) {
const reqCnf = await invokeAsync(this.generateKid.bind(this), PopTokenGenerateCnf, logger, this.performanceClient, request.correlationId)(request);
const reqCnfString = this.cryptoUtils.base64UrlEncode(JSON.stringify(reqCnf));
return {
kid: reqCnf.kid,
reqCnfString,
};
}
/**
* Generates key_id for a SHR token request
* @param request
* @returns
*/
async generateKid(request) {
const kidThumbprint = await this.tokenBindingKeyManager.provisionTokenBindingKey({
correlationId: request.correlationId,
tokenBindingKeyType: SHR_TOKEN_BINDING_KEY_TYPE,
tokenBindingKeyAlgorithm: SHR_TOKEN_BINDING_KEY_ALGORITHM,
});
return {
kid: kidThumbprint,
xms_ksl: KeyLocation.SW,
};
}
/**
* Signs the POP access_token with the local generated key-pair
* @param accessToken
* @param request
* @returns
*/
async signPopToken(accessToken, keyId, request) {
return this.signPayload(accessToken, keyId, request);
}
/**
* Utility function to generate the signed JWT for an access_token
* @param payload
* @param kid
* @param request
* @param claims
* @returns
*/
async signPayload(payload, keyId, request, claims) {
// Deconstruct request to extract SHR parameters
const { resourceRequestMethod, resourceRequestUri, shrClaims, shrNonce, shrOptions, } = request;
const resourceUrlString = resourceRequestUri
? new UrlString(resourceRequestUri, request.correlationId)
: undefined;
const resourceUrlComponents = resourceUrlString?.getUrlComponents();
const publicKeyJwk = await this.tokenBindingKeyManager.getTokenBindingPublicKeyJwk(keyId, request.correlationId);
const encodedKeyIdThumbprint = this.cryptoUtils.base64UrlEncode(JSON.stringify({ kid: keyId }));
const shrAlgorithm = shrOptions?.header?.alg ||
publicKeyJwk.alg ||
SHR_TOKEN_BINDING_KEY_ALGORITHM;
const shrHeader = JoseHeader.getShrHeader({
...shrOptions?.header,
alg: shrAlgorithm,
kid: encodedKeyIdThumbprint,
}, request.correlationId);
const shrPayload = {
at: payload,
ts: nowSeconds(),
m: resourceRequestMethod?.toUpperCase(),
u: resourceUrlComponents?.HostNameAndPort,
nonce: shrNonce || this.cryptoUtils.createNewGuid(),
p: resourceUrlComponents?.AbsolutePath,
q: resourceUrlComponents?.QueryString
? [[], resourceUrlComponents.QueryString]
: undefined,
client_claims: shrClaims || undefined,
...claims,
cnf: {
jwk: publicKeyJwk,
},
};
return this.cryptoUtils.signTokenBindingJwt(shrHeader, shrPayload, keyId, request.correlationId);
}
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const DPOP_HTM_REGEX = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
const DPOP_TOKEN_BINDING_KEY_TYPE = "dpop";
const DPOP_JWT_HEADER_ALGORITHM = JsonWebTokenAlgorithms.ES256;
function buildProofHeader(publicJwk, correlationId) {
return JoseHeader.getDpopHeader({
alg: DPOP_JWT_HEADER_ALGORITHM,
jwk: publicJwk,
}, correlationId);
}
function normalizeHtm(htm, correlationId) {
if (typeof htm !== "string" || !DPOP_HTM_REGEX.test(htm)) {
throw createClientConfigurationError(invalidDpopHtm, correlationId);
}
return htm.toUpperCase();
}
/**
* Normalizes a URL for use as the DPoP htu claim.
* Per RFC 9449 §4.2, htu is the target URI without query and fragment components.
* WHATWG URL serialization handles RFC 3986 syntax- and scheme-based normalization
* such as lowercasing scheme/host and eliding default ports.
*/
function normalizeHtu(url, correlationId) {
let parsedUrl;
try {
parsedUrl = new URL(url);
}
catch {
throw createClientConfigurationError(urlParseError, correlationId);
}
if (!/^https:\/\//i.test(url) ||
parsedUrl.protocol !== "https:" ||
parsedUrl.username ||
parsedUrl.password) {
throw createClientConfigurationError(invalidDpopHtu, correlationId);
}
parsedUrl.search = "";
parsedUrl.hash = "";
return parsedUrl.href;
}
function validateDpopNonce(nonce, correlationId) {
if (nonce !== undefined && nonce.trim().length === 0) {
throw createClientConfigurationError(invalidDpopNonce, correlationId);
}
}
/**
* Builds RFC 9449 DPoP proof JWT payloads for token-endpoint and
* resource-endpoint proof bindings.
*
* Not exported from any public package entry point.
* This helper is internal-only until DPoP is wired into acquisition flows
* in a subsequent work item.
*
* DPoP proofs do not contain SHR fields (at, ts, m, u, p, q).
* @internal
*/
class DpopProofGenerator {
constructor(cryptoUtils, tokenBindingKeyManager) {
this.cryptoUtils = cryptoUtils;
this.tokenBindingKeyManager = tokenBindingKeyManager;
}
/**
* Provisions a fresh DPoP key and returns the RFC 7638 JWK thumbprint used
* as `dpop_jkt`.
*/
async generateJkt(correlationId = "") {
return this.tokenBindingKeyManager.provisionTokenBindingKey({
tokenBindingKeyType: DPOP_TOKEN_BINDING_KEY_TYPE,
tokenBindingKeyAlgorithm: DPOP_JWT_HEADER_ALGORITHM,
correlationId,
});
}
/**
* Builds RFC 9449 claims for a token-endpoint DPoP proof.
* - htm is always "POST" because token endpoint requests use HTTP POST (RFC 9449 §5).
* - htu is the normalized token endpoint URI (query and fragment stripped).
* - jti is a fresh CSPRNG-backed unique identifier for every proof.
*/
buildTokenProofClaims(params, correlationId = "") {
validateDpopNonce(params.nonce, correlationId);
const claims = {
jti: this.cryptoUtils.createNewGuid(),
htm: "POST",
htu: normalizeHtu(params.tokenEndpoint, correlationId),
iat: nowSeconds(),
};
if (params.nonce !== undefined) {
claims.nonce = params.nonce;
}
return claims;
}
/**
* Builds and signs a compact DPoP proof JWT for a token-endpoint request.
*/
async generateTokenProof(params, keyId, correlationId = "") {
return this.generateProof(this.buildTokenProofClaims(params, correlationId), keyId, correlationId);
}
/**
* Builds RFC 9449 claims for a resource-endpoint DPoP proof.
* - htm is uppercased per RFC 9449 §4.2.
* - htu is the normalized resource URI (query and fragment stripped).
* - ath is the base64url-encoded SHA-256 hash of the ASCII access token.
* - jti is a fresh CSPRNG-backed unique identifier for every proof.
*/
buildResourceProofClaims(params, correlationId = "") {
validateDpopNonce(params.nonce, correlationId);
const claims = {
jti: this.cryptoUtils.createNewGuid(),
htm: normalizeHtm(params.htm, correlationId),
htu: normalizeHtu(params.htu, correlationId),
ath: params.ath,
iat: nowSeconds(),
};
if (params.nonce !== undefined) {
claims.nonce = params.nonce;
}
return claims;
}
/**
* Builds and signs a compact DPoP proof JWT for a resource request.
*/
async generateResourceProof(params, keyId, correlationId = "") {
const { htu, htm, nonce } = params;
if (!htu || !htm) {
throw createClientConfigurationError(dpopMissingResourceContext, correlationId);
}
const ath = await this.cryptoUtils.hashString(params.accessToken);
return this.generateProof(this.buildResourceProofClaims({
htu,
htm,
ath,
nonce,
}, correlationId), keyId, correlationId);
}
async generateProof(claims, keyId, correlationId) {
const publicJwk = await this.tokenBindingKeyManager.getTokenBindingPublicKeyJwk(keyId, correlationId);
return this.cryptoUtils.signTokenBindingJwt(buildProofHeader(publicJwk, correlationId), claims, keyId, correlationId);
}
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* MSAL-defined interaction required error code indicating no tokens are found in cache.
* @public
*/
const noTokensFound = "no_tokens_found";
/**
* MSAL-defined error code indicating a native account is unavailable on the platform.
* @public
*/
const nativeAccountUnavailable = "native_account_unavailable";
/**
* MSAL-defined error code indicating the refresh token has expired and user interaction is needed.
* @public
*/
const refreshTokenExpired = "refresh_token_expired";
/**
* MSAL-defined error code indicating UI/UX is not allowed (e.g., blocked by policy), requiring alternate interaction.
* @public
*/
const uiNotAllowed = "ui_not_allowed";
/**
* Server-originated error code indicating interaction is required to complete the request.
* @public
*/
const interactionRequired = "interaction_required";
/**
* Server-originated error code indicating user consent is required.
* @public
*/
const consentRequired = "consent_required";
/**
* Server-originated error code indicating user login is required.
* @public
*/
const loginRequired = "login_required";
/**
* Server-originated error code indicating the token is invalid or corrupted.
* @public
*/
const badToken = "bad_token";
/**
* Server-originated error code indicating the user is in an interrupted state and interaction is required.
* @public
*/
const interruptedUser = "interrupted_user";
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* InteractionRequiredServerErrorMessage contains string constants used by error codes and messages returned by the server indicating interaction is required
*/
const InteractionRequiredServerErrorMessage = [
interactionRequired,
consentRequired,
loginRequired,
badToken,
uiNotAllowed,
interruptedUser,
];
const InteractionRequiredAuthSubErrorMessage = [
"message_only",
"additional_action",
"basic_action",
"user_password_expired",
"consent_required",
"bad_token",
"ui_not_allowed",
"interrupted_user",
];
/**
* Error thrown when user interaction is required.
*/
class InteractionRequiredAuthError extends AuthError {
constructor(errorCode, correlationId, errorMessage, subError, timestamp, traceId, claims, errorNo) {
super(errorCode, correlationId, errorMessage, subError);
Object.setPrototypeOf(this, InteractionRequiredAuthError.prototype);
this.timestamp = timestamp || "";
this.traceId = traceId || "";
this.claims = claims || "";
this.name = "InteractionRequiredAuthError";
this.errorNo = errorNo;
}
}
/**
* Helper function used to determine if an error thrown by the server requires interaction to resolve
* @param errorCode
* @param errorString
* @param subError
*/
function isInteractionRequiredError(errorCode, errorString, subError) {
const isInteractionRequiredErrorCode = !!errorCode &&
InteractionRequiredServerErrorMessage.indexOf(errorCode) > -1;
const isInteractionRequiredSubError = !!subError &&
InteractionRequiredAuthSubErrorMessage.indexOf(subError) > -1;
const isInteractionRequiredErrorDesc = !!errorString &&
InteractionRequiredServerErrorMessage.some((irErrorCode) => {
return errorString.indexOf(irErrorCode) > -1;
});
return (isInteractionRequiredErrorCode ||
isInteractionRequiredErrorDesc ||
isInteractionRequiredSubError);
}
/**
* Creates an InteractionRequiredAuthError
*/
function createInteractionRequiredAuthError(errorCode, correlationId, errorMessage) {
return new InteractionRequiredAuthError(errorCode, correlationId, errorMessage);
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Error thrown when there is an error with the server code, for example, unavailability.
*/
class ServerError extends AuthError {
constructor(errorCode, correlationId, errorMessage, subError, errorNo, status) {
super(errorCode, correlationId, errorMessage, subError);
this.name = "ServerError";
this.errorNo = errorNo;
this.status = status;
Object.setPrototypeOf(this, ServerError.prototype);
}
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Appends user state with random guid, or returns random guid.
* @param cryptoObj
* @param userState
* @param meta
* @param correlationId
*/
function setRequestState(cryptoObj, userState, meta, correlationId) {
const libraryState = generateLibraryState(cryptoObj, correlationId, meta);
return userState
? `${libraryState}${RESOURCE_DELIM}${userState}`
: libraryState;
}
/**
* Generates the state value used by the common library.
* @param cryptoObj
* @param correlationId
* @param meta
*/
function generateLibraryState(cryptoObj, correlationId, meta) {
if (!cryptoObj) {
throw createClientAuthError(noCryptoObject, correlationId);
}
// Create a state object containing a unique id and the timestamp of the request creation
const stateObj = {
id: cryptoObj.createNewGuid(),
};
if (meta) {
stateObj.meta = meta;
}
const stateString = JSON.stringify(stateObj);
return cryptoObj.base64Encode(stateString);
}
/**
* Parses the state into the RequestStateObject, which contains the LibraryState info and the state passed by the user.
* @param base64Decode
* @param state
* @param correlationId
*/
function parseRequestState(base64Decode, state, correlationId) {
if (!base64Decode) {
throw createClientAuthError(noCryptoObject, correlationId);
}
if (!state) {
throw createClientAuthError(invalidState, correlationId);
}
try {
// Split the state between library state and user passed state and decode them separately
const splitState = state.split(RESOURCE_DELIM);
const libraryState = splitState[0];
const userState = splitState.length > 1
? splitState.slice(1).join(RESOURCE_DELIM)
: "";
const libraryStateString = base64Decode(libraryState);
const libraryStateObj = JSON.parse(libraryStateString);
return {
userRequestState: userState || "",
libraryState: libraryStateObj,
};
}
catch (e) {
throw createClientAuthError(invalidState, correlationId);
}
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Class that handles response parsing.
* @internal
*/
class ResponseHandler {
constructor(clientId, cacheStorage, cryptoObj, logger, performanceClient, serializableCache, persistencePlugin, tokenBindingKeyManager = DEFAULT_TOKEN_BINDING_KEY_MANAGER) {
this.clientId = clientId;
this.cacheStorage = cacheStorage;
this.cryptoObj = cryptoObj;
this.tokenBindingKeyManager = tokenBindingKeyManager;
this.logger = logger;
this.performanceClient = performanceClient;
this.serializableCache = serializableCache;
this.persistencePlugin = persistencePlugin;
}
/**
* Function which validates server authorization token response.
* @param serverResponse
* @param correlationId
* @param refreshAccessToken
*/
validateTokenResponse(serverResponse, correlationId, refreshAccessToken) {
// Check for error
if (serverResponse.error ||
serverResponse.error_description ||
serverResponse.suberror) {
const errString = `Error(s): ${serverResponse.error_codes || NOT_AVAILABLE} - Timestamp: ${serverResponse.timestamp || NOT_AVAILABLE} - Description: ${serverResponse.error_description || NOT_AVAILABLE} - Correlation ID: ${serverResponse.correlation_id || NOT_AVAILABLE} - Trace ID: ${serverResponse.trace_id || NOT_AVAILABLE}`;
const serverErrorNo = serverResponse.error_codes?.length
? serverResponse.error_codes[0]
: undefined;
const serverError = new ServerError(serverResponse.error || "", serverResponse.correlation_id || "", errString, serverResponse.suberror, serverErrorNo, serverResponse.status);
// check if 500 error
if (refreshAccessToken &&
serverResponse.status &&
serverResponse.status >=
HTTP_SERVER_ERROR_RANGE_START &&
serverResponse.status <= HTTP_SERVER_ERROR_RANGE_END) {
this.logger.warning(`16ks7j ${serverError}`, correlationId);
// don't throw an exception, but alert the user via a log that the token was unable to be refreshed
return;
// check if 400 error
}
else if (refreshAccessToken &&
serverResponse.status &&
serverResponse.status >=
HTTP_CLIENT_ERROR_RANGE_START &&
serverResponse.status <= HTTP_CLIENT_ERROR_RANGE_END) {
this.logger.warning(`0g61x3 ${serverError}`, correlationId);
// don't throw an exception, but alert the user via a log that the token was unable to be refreshed
return;
}
if (isInteractionRequiredError(serverResponse.error, serverResponse.error_description, serverResponse.suberror)) {
throw new InteractionRequiredAuthError(serverResponse.error || "", serverResponse.correlation_id || "", serverResponse.error_description, serverResponse.suberror, serverResponse.timestamp || "", serverResponse.trace_id || "", serverResponse.claims || "", serverErrorNo);
}
throw serverError;
}
}
/**
* Returns a constructed token response based on given string. Also manages the cache updates and cleanups.
* @param serverTokenResponse
* @param authority
*/
async handleServerTokenResponse(serverTokenResponse, authority, reqTimestamp, request, apiId, authCodePayload, userAssertionHash, handlingRefreshTokenResponse, forceCacheRefreshTokenResponse, serverRequestId, additionalCacheKeyComponents) {
// create an idToken object (not entity)
let idTokenClaims;
if (serverTokenResponse.id_token) {
idTokenClaims = extractTokenClaims(serverTokenResponse.id_token || "", this.cryptoObj.base64Decode, request.correlationId);
}
/*
* Callers opt in to strict nonce-presence validation by including
* the nonce property, even when its value is undefined.
*/
if (authCodePayload &&
Object.prototype.hasOwnProperty.call(authCodePayload, "nonce")) {
const expectedNonce = authCodePayload.nonce;
const tokenNonce = idTokenClaims?.nonce;
// Warn when the ID Token nonce cannot be bound to the request.
if (tokenNonce !== undefined && expectedNonce === undefined) {
this.logger.warning("0thba9", request.correlationId);
throw createClientAuthError(nonceMismatch, request.correlationId);
}
// If the request supplies a nonce, the ID Token value must be a matching string.
if (expectedNonce !== undefined &&
(typeof expectedNonce !== "string" ||
typeof tokenNonce !== "string" ||
expectedNonce !== tokenNonce)) {
throw createClientAuthError(nonceMismatch, request.correlationId);
}
}
// generate homeAccountId
this.homeAccountIdentifier = generateHomeAccountId(serverTokenResponse.client_info || "", authority.authorityType, this.logger, this.cryptoObj, request.correlationId, idTokenClaims);
// save the response tokens
let requestStateObj;
if (!!authCodePayload && !!authCodePayload.state) {
requestStateObj = parseRequestState(this.cryptoObj.base64Decode, authCodePayload.state, request.correlationId);
}
// Add keyId from request to serverTokenResponse if defined
serverTokenResponse.key_id =
serverTokenResponse.key_id ||
request.dpopJkt ||
request.sshKid ||
undefined;
if (request.authenticationScheme === AuthenticationScheme.DPOP) {
if (serverTokenResponse.token_type?.toLowerCase() !==
AuthenticationScheme.DPOP.toLowerCase()) {
this.performanceClient?.addFields({
dpopTokenTypeMismatch: serverTokenResponse.token_type,
}, request.correlationId);
throw createClientAuthError(dpopTokenTypeMismatch, request.correlationId);
}
serverTokenResponse.token_type =
AuthenticationScheme.DPOP;
}
// Compute components once for entity storage (fallback if hash not provided by client)
const attributeTokenPartition = serializeAttributeTokens(request.attributeTokens);
const cacheKeyComponents = additionalCacheKeyComponents ??
(attributeTokenPartition
? {
attribute_tokens: attributeTokenPartition,
}
: undefined);
const cacheRecord = this.generateCacheRecord(serverTokenResponse, authority, reqTimestamp, request, idTokenClaims, userAssertionHash, authCodePayload, cacheKeyComponents);
let cacheContext;
try {
if (this.persistencePlugin && this.serializableCache) {
this.logger.verbose("0jbz5k", request.correlationId);
cacheContext = new TokenCacheContext(this.serializableCache, true);
await this.persistencePlugin.beforeCacheAccess(cacheContext);
}
/*
* When saving a refreshed tokens to the cache, it is expected that the account that was used is present in the cache.
* If not present, we should return null, as it's the case that another application called removeAccount in between
* the calls to getAllAccounts and acquireTokenSilent. We should not overwrite that removal, unless explicitly flagged by
* the developer, as in the case of refresh token flow used in ADAL Node to MSAL Node migration.
*/
if (handlingRefreshTokenResponse &&
!forceCacheRefreshTokenResponse &&
cacheRecord.account) {
const cachedAccounts = this.cacheStorage.getAllAccounts({
homeAccountId: cacheRecord.account.homeAccountId,
environment: cacheRecord.account.environment,
}, request.correlationId);
if (cachedAccounts.length < 1) {
this.logger.warning("1gmt66", request.correlationId);
this.performanceClient?.addFields({
acntLoggedOut: true,
}, request.correlationId);
return await ResponseHandler.generateAuthenticationResult(this.cryptoObj, authority, cacheRecord, false, request, this.performanceClient, {
idTokenClaims,
requestState: requestStateObj,
requestId: serverRequestId,
tokenBindingKeyManager: this.tokenBindingKeyManager,
});
}
}
await this.cacheStorage.saveCacheRecord(cacheRecord, request.correlationId, isKmsi(idTokenClaims || {}), apiId, request.storeInCache);
}
finally {
if (this.persistencePlugin &&
this.serializableCache &&
cacheContext) {
this.logger.verbose("1bh17u", request.correlationId);
await this.persistencePlugin.afterCacheAccess(cacheContext);
}
}
return ResponseHandler.generateAuthenticationResult(this.cryptoObj, authority, cacheRecord, false, request, this.performanceClient, {
idTokenClaims,
requestState: requestStateObj,
serverTokenResponse,
requestId: serverRequestId,
tokenBindingKeyManager: this.tokenBindingKeyManager,
});
}
/**
* Generates CacheRecord
* @param serverTokenResponse
* @param idTokenObj
* @param authority
*/
generateCacheRecord(serverTokenResponse, authority, reqTimestamp, request, idTokenClaims, userAssertionHash, authCodePayload, additionalCacheKeyComponents) {
const env = authority.getPreferredCache();
if (!env) {
throw createClientAuthError(invalidCacheEnvironment, request.correlationId);
}
const claimsTenantId = getTenantIdFromIdTokenClaims(idTokenClaims);
// IdToken: non AAD scenarios can have empty realm
let cachedIdToken;
let cachedAccount;
if (serverTokenResponse.id_token && !!idTokenClaims) {
cachedIdToken = createIdTokenEntity(this.homeAccountIdentifier, env, serverTokenResponse.id_token, this.clientId, claimsTenantId || "");
cachedAccount = buildAccountToCache(this.cacheStorage, authority, this.homeAccountIdentifier, this.cryptoObj.base64Decode, request.correlationId, idTokenClaims, serverTokenResponse.client_info, env, claimsTenantId, authCodePayload, undefined, // nativeAccountId
this.logger, this.performanceClient);
}
// AccessToken
let cachedAccessToken = null;
if (serverTokenResponse.access_token) {
// If scopes not returned in server response, use request scopes
const responseScopes = serverTokenResponse.scope
? ScopeSet.fromString(serverTokenResponse.scope, request.correlationId)
: new ScopeSet(request.scopes || [], request.correlationId);
/*
* Use timestamp calculated before request
* Server may return timestamps as strings, parse to numbers if so.
*/
const expiresIn = (typeof serverTokenResponse.expires_in === "string"
? parseInt(serverTokenResponse.expires_in, 10)
: serverTokenResponse.expires_in) || 0;
const extExpiresIn = (typeof serverTokenResponse.ext_expires_in === "string"
? parseInt(serverTokenResponse.ext_expires_in, 10)
: serverTokenResponse.ext_expires_in) || 0;
const refreshIn = (typeof serverTokenResponse.refresh_in === "string"
? parseInt(serverTokenResponse.refresh_in, 10)
: serverTokenResponse.refresh_in) || undefined;
const tokenExpirationSeconds = reqTimestamp + expiresIn;
const extendedTokenExpirationSeconds = tokenExpirationSeconds + extExpiresIn;
const refreshOnSeconds = refreshIn && refreshIn > 0
? reqTimestamp + refreshIn
: undefined;
// non AAD scenarios can have empty realm
cachedAccessToken = createAccessTokenEntity(this.homeAccountIdentifier, env, serverTokenResponse.access_token, this.clientId, claimsTenantId || authority.tenant || "", responseScopes.printScopes(), tokenExpirationSeconds, extendedTokenExpirationSeconds, this.cryptoObj.base64Decode, request.correlationId, refreshOnSeconds, serverTokenResponse.token_type, userAssertionHash, serverTokenResponse.key_id, additionalCacheKeyComponents);
// Set resource (to be used for MCP scenarios)
const resource = request.resource || null;
if (resource) {
cachedAccessToken.resource = resource;
}
}
// refreshToken
let cachedRefreshToken = null;
if (serverTokenResponse.refresh_token) {
let rtExpiresOn;
if (serverTokenResponse.refresh_token_expires_in) {
const rtExpiresIn = typeof serverTokenResponse.refresh_token_expires_in ===
"string"
? parseInt(serverTokenResponse.refresh_token_expires_in, 10)
: serverTokenResponse.refresh_token_expires_in;
rtExpiresOn = reqTimestamp + rtExpiresIn;
this.performanceClient?.addFields({ ntwkRtExpiresOnSeconds: rtExpiresOn }, request.correlationId);
}
cachedRefreshToken = createRefreshTokenEntity(this.homeAccountIdentifier, env, serverTokenResponse.refresh_token, this.clientId, serverTokenResponse.foci, userAssertionHash, rtExpiresOn);
}
// appMetadata
let cachedAppMetadata = null;
if (serverTokenResponse.foci) {
cachedAppMetadata = {
clientId: this.clientId,
environment: env,
familyId: serverTokenResponse.foci,
};
}
return {
account: cachedAccount,
idToken: cachedIdToken,
accessToken: cachedAccessToken,
refreshToken: cachedRefreshToken,
appMetadata: cachedAppMetadata,
};
}
/**
* Creates an @AuthenticationResult from @CacheRecord , @IdToken , and a boolean that states whether or not the result is from cache.
*
* Optionally takes a state string that is set as-is in the response.
*
* @param cacheRecord
* @param idTokenObj
* @param fromTokenCache
* @param stateString
*/
static async generateAuthenticationResult(cryptoObj, authority, cacheRecord, fromTokenCache, request, performanceClient, options = {}) {
const { idTokenClaims, requestState, serverTokenResponse, requestId, tokenBindingKeyManager = DEFAULT_TOKEN_BINDING_KEY_MANAGER, } = options;
let accessToken = "";
let responseScopes = [];
let expiresOn = null;
let extExpiresOn;
let refreshOn;
let familyId = "";
let dpopProof;
if (cacheRecord.accessToken) {
const accessTokenType = cacheRecord.accessToken.tokenType?.toLowerCase();
/*
* if the request object has `popKid` property, `signPopToken` will be set to false and
* the token will be returned unsigned
*/
if (cacheRecord.accessToken.tokenType ===
AuthenticationScheme.POP &&
!request.popKid) {
const popTokenGenerator = new PopTokenGenerator(cryptoObj, tokenBindingKeyManager, performanceClient);
const { secret, keyId } = cacheRecord.accessToken;
if (!keyId) {
throw createClientAuthError(keyIdMissing, request.correlationId);
}
accessToken = await popTokenGenerator.signPopToken(secret, keyId, request);
}
else {
accessToken = cacheRecord.accessToken.secret;
}
if (accessTokenType ===
AuthenticationScheme.DPOP.toLowerCase()) {
if (!cacheRecord.accessToken.keyId) {
throw createClientAuthError(keyIdMissing, request.correlationId);
}
const dpopProofGenerator = new DpopProofGenerator(cryptoObj, tokenBindingKeyManager);
dpopProof = await dpopProofGenerator.generateResourceProof({
htu: request.resourceRequestUri,
htm: request.resourceRequestMethod,
accessToken: cacheRecord.accessToken.secret,
}, cacheRecord.accessToken.keyId, request.correlationId);
}
responseScopes = ScopeSet.fromString(cacheRecord.accessToken.target, request.correlationId).asArray();
// Access token expiresOn cached in seconds, converting to Date for AuthenticationResult
expiresOn = toDateFromSeconds(cacheRecord.accessToken.expiresOn);
extExpiresOn = toDateFromSeconds(cacheRecord.accessToken.extendedExpiresOn);
if (cacheRecord.accessToken.refreshOn) {
refreshOn = toDateFromSeconds(cacheRecord.accessToken.refreshOn);
}
}
if (cacheRecord.appMetadata) {
familyId =
cacheRecord.appMetadata.familyId === THE_FAMILY_ID
? THE_FAMILY_ID
: "";
}
const uid = idTokenClaims?.oid || idTokenClaims?.sub || "";
const tid = idTokenClaims?.tid || "";
/*
* Surface the sovereign enclave for telemetry. This runs for both freshly acquired
* and cache-served tokens because SilentFlowClient shares this method, so the field
* is present on silent requests that never hit the network.
*/
const regionSubScope = idTokenClaims?.tenant_region_sub_scope;
if (typeof regionSubScope === "string") {
performanceClient?.addFields({ regionSubScope }, request.correlationId);
}
// for hybrid + native bridge enablement, send back the native account Id
if (serverTokenResponse?.spa_accountid && !!cacheRecord.account) {
// Set on deprecated top-level for downgrade compat
cacheRecord.account.nativeAccountId =
serverTokenResponse?.spa_accountid;
// Set on the matching tenant profile (source of truth)
const targetTenantId = tid || cacheRecord.account.realm;
if (cacheRecord.account.tenantProfiles) {
const matchingProfile = cacheRecord.account.tenantProfiles.find((tp) => tp.tenantId === targetTenantId);
if (matchingProfile) {
matchingProfile.nativeAccountId =
serverTokenResponse.spa_accountid;
}
}
}
const accountInfo = cacheRecord.account
? updateAccountTenantProfileData(getAccountInfo(cacheRecord.account), undefined, // tenantProfile optional
idTokenClaims, cacheRecord.idToken?.secret)
: null;
return {
authority: authority.canonicalAuthority,
uniqueId: uid,
tenantId: tid,
scopes: responseScopes,
account: accountInfo,
idToken: cacheRecord?.idToken?.secret || "",
idTokenClaims: idTokenClaims || {},
accessToken: accessToken,
dpopProof,
fromCache: fromTokenCache,
expiresOn: expiresOn,
extExpiresOn: extExpiresOn,
refreshOn: refreshOn,
correlationId: request.correlationId,
requestId: requestId || "",
familyId: familyId,
tokenType: cacheRecord.accessToken?.tokenType?.toLowerCase() ===
AuthenticationScheme.DPOP.toLowerCase()
? AuthenticationScheme.DPOP
: cacheRecord.accessToken?.tokenType || "",
state: requestState ? requestState.userRequestState : "",
cloudGraphHostName: cacheRecord.account?.cloudGraphHostName || "",
msGraphHost: cacheRecord.account?.msGraphHost || "",
code: serverTokenResponse?.spa_code,
fromPlatformBroker: false,
};
}
}
/** @internal */
function buildAccountToCache(cacheStorage, authority, homeAccountId, base64Decode, correlationId, idTokenClaims, clientInfo, environment, claimsTenantId, authCodePayload, nativeAccountId, logger, performanceClient) {
logger?.verbose("09jz0t", correlationId);
/*
* Check if base account is already cached. Filter by homeAccountId (identifies
* the user's home identity) and environment (identifies the cloud) — the two
* tenant-agnostic properties that uniquely locate a base AccountEntity.
*/
const accountEnvironment = environment || authority.getPreferredCache();
const matchedAccounts = cacheStorage.getAccountsFilteredBy({ homeAccountId, environment: accountEnvironment }, correlationId);
performanceClient?.addFields({ cacheMatchedAccounts: matchedAccounts.length }, correlationId);
if (matchedAccounts.length > 1) {
/*
* Base accounts are expected to be unique for a given homeAccountId in normal cache usage.
* If multiple matches exist, ignore the cache hit rather than arbitrarily choosing one.
*/
logger?.warning("0x7ad1", correlationId);
}
const cachedAccount = matchedAccounts.length === 1 ? matchedAccounts[0] : null;
const baseAccount = cachedAccount ||
createAccountEntity({
homeAccountId,
idTokenClaims,
clientInfo,
environment,
cloudGraphHostName: authCodePayload?.cloud_graph_host_name,
msGraphHost: authCodePayload?.msgraph_host,
nativeAccountId: nativeAccountId,
}, authority, correlationId, base64Decode);
const tenantProfiles = baseAccount.tenantProfiles || [];
const tenantId = claimsTenantId || baseAccount.realm;
if (tenantId &&
!tenantProfiles.find((tenantProfile) => {
return tenantProfile.tenantId === tenantId;
})) {
const newTenantProfile = buildTenantProfile(homeAccountId, baseAccount.localAccountId, tenantId, nativeAccountId, idTokenClaims);
tenantProfiles.push(newTenantProfile);
}
baseAccount.tenantProfiles = tenantProfiles;
return baseAccount;
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const CcsCredentialType = {
HOME_ACCOUNT_ID: "home_account_id",
UPN: "UPN",
};
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
async function getClientAssertion(clientAssertion, clientId, tokenEndpoint, fmiPath) {
if (typeof clientAssertion === "string") {
return clientAssertion;
}
else {
const config = {
clientId: clientId,
tokenEndpoint: tokenEndpoint,
fmiPath: fmiPath,
};
return clientAssertion(config);
}
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
function getRequestThumbprint(clientId, request, homeAccountId) {
return {
clientId: clientId,
authority: request.authority,
scopes: request.scopes,
homeAccountIdentifier: homeAccountId,
claims: request.claims,
authenticationScheme: request.authenticationScheme,
resourceRequestMethod: request.resourceRequestMethod,
resourceRequestUri: request.resourceRequestUri,
shrClaims: request.shrClaims,
sshKid: request.sshKid,
embeddedClientId: request.embeddedClientId || request.extraParameters?.clientId,
resource: request.resource,
attributeTokens: serializeAttributeTokens(request.attributeTokens),
};
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/** @internal */
class ThrottlingUtils {
/**
* Prepares a RequestThumbprint to be stored as a key.
* @param thumbprint
*/
static generateThrottlingStorageKey(thumbprint) {
return `${THROTTLING_PREFIX}.${JSON.stringify(thumbprint)}`;
}
/**
* Performs necessary throttling checks before a network request.
* @param cacheManager
* @param thumbprint
*/
static preProcess(cacheManager, thumbprint, correlationId) {
const key = ThrottlingUtils.generateThrottlingStorageKey(thumbprint);
const value = cacheManager.getThrottlingCache(key, correlationId);
if (value) {
if (value.throttleTime < Date.now()) {
cacheManager.removeItem(key, correlationId);
return;
}
throw new ServerError(value.errorCodes?.join(" ") || "", correlationId, value.errorMessage, value.subError);
}
}
/**
* Performs necessary throttling checks after a network request.
* @param cacheManager
* @param thumbprint
* @param response
*/
static postProcess(cacheManager, thumbprint, response, correlationId) {
if (ThrottlingUtils.checkResponseStatus(response) ||
ThrottlingUtils.checkResponseForRetryAfter(response)) {
const thumbprintValue = {
throttleTime: ThrottlingUtils.calculateThrottleTime(parseInt(response.headers[HeaderNames.RETRY_AFTER])),
error: response.body.error,
errorCodes: response.body.error_codes,
errorMessage: response.body.error_description,
subError: response.body.suberror,
};
cacheManager.setThrottlingCache(ThrottlingUtils.generateThrottlingStorageKey(thumbprint), thumbprintValue, correlationId);
}
}
/**
* Checks a NetworkResponse object's status codes against 429 or 5xx
* @param response
*/
static checkResponseStatus(response) {
return (response.status === 429 ||
(response.status >= 500 && response.status < 600));
}
/**
* Checks a NetworkResponse object's RetryAfter header
* @param response
*/
static checkResponseForRetryAfter(response) {
if (response.headers) {
return (response.headers.hasOwnProperty(HeaderNames.RETRY_AFTER) &&
(response.status < 200 || response.status >= 300));
}
return false;
}
/**
* Calculates the Unix-time value for a throttle to expire given throttleTime in seconds.
* @param throttleTime
*/
static calculateThrottleTime(throttleTime) {
const time = throttleTime <= 0 ? 0 : throttleTime;
const currentSeconds = Date.now() / 1000;
return Math.floor(Math.min(currentSeconds +
(time || DEFAULT_THROTTLE_TIME_SECONDS), currentSeconds + DEFAULT_MAX_THROTTLE_TIME_SECONDS) * 1000);
}
static removeThrottle(cacheManager, clientId, request, homeAccountIdentifier) {
const thumbprint = getRequestThumbprint(clientId, request, homeAccountIdentifier);
const key = this.generateThrottlingStorageKey(thumbprint);
cacheManager.removeItem(key, request.correlationId);
}
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Represents network related errors
*/
class NetworkError extends AuthError {
constructor(error, httpStatus, responseHeaders) {
super(error.errorCode, error.correlationId, error.errorMessage, error.subError);
Object.setPrototypeOf(this, NetworkError.prototype);
this.name = "NetworkError";
this.error = error;
this.httpStatus = httpStatus;
this.responseHeaders = responseHeaders;
}
}
/**
* Creates NetworkError object for a failed network request
* @param error - Error to be thrown back to the caller
* @param httpStatus - Status code of the network request
* @param responseHeaders - Response headers of the network request, when available
* @returns NetworkError object
*/
function createNetworkError(error, httpStatus, responseHeaders, additionalError) {
error.errorMessage = `${error.errorMessage}, additionalErrorInfo: error.name:${additionalError?.name}, error.message:${additionalError?.message}`;
return new NetworkError(error, httpStatus, responseHeaders);
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Creates default headers for requests to token endpoint
*/
function createTokenRequestHeaders(logger, preventCorsPreflight, ccsCred) {
const headers = {};
headers[HeaderNames.CONTENT_TYPE] = URL_FORM_CONTENT_TYPE;
if (!preventCorsPreflight && ccsCred) {
switch (ccsCred.type) {
case CcsCredentialType.HOME_ACCOUNT_ID:
try {
const clientInfo = buildClientInfoFromHomeAccountId(ccsCred.credential);
headers[HeaderNames.CCS_HEADER] = `Oid:${clientInfo.uid}@${clientInfo.utid}`;
}
catch (e) {
logger.verbose(`1qhtee ${e}`, "");
}
break;
case CcsCredentialType.UPN:
headers[HeaderNames.CCS_HEADER] = `UPN: ${ccsCred.credential}`;
break;
}
}
return headers;
}
/**
* Adds the DPoP proof header for token endpoint requests when DPoP is requested.
* @internal
*/
async function addDpopTokenProofHeader(headers, request, tokenEndpoint, cryptoUtils, tokenBindingKeyManager) {
if (request.authenticationScheme !== AuthenticationScheme.DPOP) {
return;
}
const dpopProofGenerator = new DpopProofGenerator(cryptoUtils, tokenBindingKeyManager);
const keyId = request.dpopJkt;
if (!keyId?.trim()) {
throw createClientAuthError(keyIdMissing, request.correlationId);
}
headers[HeaderNames.DPOP] = await dpopProofGenerator.generateTokenProof({
tokenEndpoint,
}, keyId, request.correlationId);
}
/**
* Creates query string for the /token request
* @param request
*/
function createTokenQueryParameters(request, clientId, redirectUri, performanceClient) {
const parameters = new Map();
if (request.embeddedClientId) {
addBrokerParameters(parameters, clientId, redirectUri);
}
if (request.extraQueryParameters) {
addExtraParameters(parameters, request.extraQueryParameters);
}
addCorrelationId(parameters, request.correlationId);
instrumentBrokerParams(parameters, request.correlationId, performanceClient);
return mapToQueryString(parameters);
}
/**
* Http post to token endpoint
* @param tokenEndpoint
* @param queryString
* @param headers
* @param thumbprint
* @internal
*/
async function executePostToTokenEndpoint(tokenEndpoint, queryString, headers, thumbprint, correlationId, cacheManager, networkClient, logger, performanceClient, serverTelemetryManager) {
const response = await sendPostRequest(thumbprint, tokenEndpoint, { body: queryString, headers: headers }, correlationId, cacheManager, networkClient, logger, performanceClient);
if (serverTelemetryManager &&
response.status < 500 &&
response.status !== 429) {
// Telemetry data successfully logged by server, clear Telemetry cache
serverTelemetryManager.clearTelemetryCache();
}
return response;
}
/**
* Wraps sendPostRequestAsync with necessary preflight and postflight logic
* @param thumbprint - Request thumbprint for throttling
* @param tokenEndpoint - Endpoint to make the POST to
* @param options - Body and Headers to include on the POST request
* @param correlationId - CorrelationId for telemetry
* @param cacheManager - Cache manager instance
* @param networkClient - Network module instance
* @param logger - Logger instance
* @param performanceClient - Performance client instance
* @internal
*/
async function sendPostRequest(thumbprint, tokenEndpoint, options, correlationId, cacheManager, networkClient, logger, performanceClient) {
ThrottlingUtils.preProcess(cacheManager, thumbprint, correlationId);
let response;
try {
response = await invokeAsync((networkClient.sendPostRequestAsync.bind(networkClient)), NetworkClientSendPostRequestAsync, logger, performanceClient, correlationId)(tokenEndpoint, { ...options, correlationId, performanceClient });
const responseHeaders = response.headers || {};
performanceClient?.addFields({
refreshTokenSize: response.body.refresh_token?.length || 0,
httpVerToken: responseHeaders[HeaderNames.X_MS_HTTP_VERSION] || "",
requestId: responseHeaders[HeaderNames.X_MS_REQUEST_ID] || "",
}, correlationId);
}
catch (e) {
if (e instanceof NetworkError) {
const responseHeaders = e.responseHeaders;
if (responseHeaders) {
performanceClient?.addFields({
httpVerToken: responseHeaders[HeaderNames.X_MS_HTTP_VERSION] ||
"",
requestId: responseHeaders[HeaderNames.X_MS_REQUEST_ID] || "",
contentTypeHeader: responseHeaders[HeaderNames.CONTENT_TYPE] ||
undefined,
contentLengthHeader: responseHeaders[HeaderNames.CONTENT_LENGTH] ||
undefined,
httpStatus: e.httpStatus,
}, correlationId);
}
throw e.error;
}
if (e instanceof AuthError) {
throw e;
}
else {
throw createClientAuthError(networkError, correlationId);
}
}
ThrottlingUtils.postProcess(cacheManager, thumbprint, response, correlationId);
return response;
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Oauth2.0 Authorization Code client
* @internal
*/
class AuthorizationCodeClient {
constructor(configuration, performanceClient) {
// Flag to indicate if client is for hybrid spa auth code redemption
this.includeRedirectUri = true;
// Set the configuration
this.config = buildClientConfiguration(configuration);
// Initialize the logger
this.logger = new Logger(this.config.loggerOptions, name$1, version$1);
// Initialize crypto
this.cryptoUtils = this.config.cryptoInterface;
// Initialize storage interface
this.cacheManager = this.config.storageInterface;
// Set the network interface
this.networkClient = this.config.networkInterface;
// Set TelemetryManager
this.serverTelemetryManager = this.config.serverTelemetryManager;
// set Authority
this.authority = this.config.authOptions.authority;
// set performance telemetry client
this.performanceClient = performanceClient;
this.oidcDefaultScopes =
this.config.authOptions.authority.options.OIDCOptions?.defaultScopes;
}
/**
* API to acquire a token in exchange of 'authorization_code` acquired by the user in the first leg of the
* authorization_code_grant
* @param request
*/
async acquireToken(request, apiId, authCodePayload) {
if (!request.code) {
throw createClientAuthError(requestCannotBeMade, request.correlationId);
}
// Check for new cloud instance
if (authCodePayload && authCodePayload.cloud_instance_host_name) {
await invokeAsync(this.updateTokenEndpointAuthority.bind(this), UpdateTokenEndpointAuthority, this.logger, this.performanceClient, request.correlationId)(authCodePayload.cloud_instance_host_name, request.correlationId);
}
const reqTimestamp = nowSeconds();
const response = await invokeAsync(this.executeTokenRequest.bind(this), AuthClientExecuteTokenRequest, this.logger, this.performanceClient, request.correlationId)(this.authority, request, this.serverTelemetryManager);
// Retrieve requestId from response headers
const requestId = response.headers?.[HeaderNames.X_MS_REQUEST_ID];
const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.performanceClient, this.config.serializableCache, this.config.persistencePlugin, this.config.tokenBindingKeyManager);
// Validate response. This function throws a server error if an error is returned by the server.
responseHandler.validateTokenResponse(response.body, request.correlationId);
return invokeAsync(responseHandler.handleServerTokenResponse.bind(responseHandler), HandleServerTokenResponse, this.logger, this.performanceClient, request.correlationId)(response.body, this.authority, reqTimestamp, request, apiId, authCodePayload, undefined, undefined, undefined, requestId);
}
/**
* Used to log out the current user, and redirect the user to the postLogoutRedirectUri.
* Default behaviour is to redirect the user to `window.location.href`.
* @param authorityUri
*/
getLogoutUri(logoutRequest) {
// Throw error if logoutRequest is null/undefined
if (!logoutRequest) {
throw createClientConfigurationError(logoutRequestEmpty, "");
}
const queryString = this.createLogoutUrlQueryString(logoutRequest);
// Construct logout URI
return UrlString.appendQueryString(this.authority.endSessionEndpoint, queryString);
}
/**
* Executes POST request to token endpoint
* @param authority
* @param request
*/
async executeTokenRequest(authority, request, serverTelemetryManager) {
const queryParametersString = createTokenQueryParameters(request, this.config.authOptions.clientId, this.config.authOptions.redirectUri, this.performanceClient);
const endpoint = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString);
const requestBody = await invokeAsync(this.createTokenRequestBody.bind(this), AuthClientCreateTokenRequestBody, this.logger, this.performanceClient, request.correlationId)(request);
let ccsCredential = undefined;
if (request.clientInfo) {
try {
const clientInfo = buildClientInfo(request.clientInfo, this.cryptoUtils.base64Decode);
ccsCredential = {
credential: `${clientInfo.uid}${CLIENT_INFO_SEPARATOR}${clientInfo.utid}`,
type: CcsCredentialType.HOME_ACCOUNT_ID,
};
}
catch (e) {
this.logger.verbose(`0wznt3 ${e}`, request.correlationId);
}
}
const headers = createTokenRequestHeaders(this.logger, this.config.systemOptions.preventCorsPreflight, ccsCredential || request.ccsCredential);
await addDpopTokenProofHeader(headers, request, endpoint, this.cryptoUtils, this.config.tokenBindingKeyManager);
const thumbprint = getRequestThumbprint(this.config.authOptions.clientId, request);
return invokeAsync(executePostToTokenEndpoint, AuthorizationCodeClientExecutePostToTokenEndpoint, this.logger, this.performanceClient, request.correlationId)(endpoint, requestBody, headers, thumbprint, request.correlationId, this.cacheManager, this.networkClient, this.logger, this.performanceClient, serverTelemetryManager);
}
/**
* Generates a map for all the params to be sent to the service
* @param request
*/
async createTokenRequestBody(request) {
const parameters = new Map();
addClientId(parameters, request.embeddedClientId ||
request.extraParameters?.[CLIENT_ID] ||
this.config.authOptions.clientId);
/*
* For hybrid spa flow, there will be a code but no verifier
* In this scenario, don't include redirect uri as auth code will not be bound to redirect URI
*/
if (!this.includeRedirectUri) {
// Just validate
if (!request.redirectUri) {
throw createClientConfigurationError(redirectUriEmpty, request.correlationId);
}
}
else {
// Validate and include redirect uri
addRedirectUri(parameters, request.redirectUri);
}
// Add scope array, parameter builder will add default scopes and dedupe
addScopes(parameters, request.scopes, request.correlationId, true, this.oidcDefaultScopes);
addResource(parameters, request.resource);
if (request.attributeTokens) {
addAttributeTokens(parameters, request.attributeTokens);
}
this.performanceClient?.addFields({
hasAttributeTokens: !!request.attributeTokens?.length,
}, request.correlationId);
// add code: user set, not validated
addAuthorizationCode(parameters, request.code);
// Add library metadata
addLibraryInfo(parameters, this.config.libraryInfo);
addApplicationTelemetry(parameters, this.config.telemetry.application);
addThrottling(parameters);
if (this.serverTelemetryManager && !isOidcProtocolMode(this.config)) {
addServerTelemetry(parameters, this.serverTelemetryManager);
}
// add code_verifier if passed
if (request.codeVerifier) {
addCodeVerifier(parameters, request.codeVerifier);
}
if (this.config.clientCredentials.clientSecret) {
addClientSecret(parameters, this.config.clientCredentials.clientSecret);
}
if (this.config.clientCredentials.clientAssertion) {
const clientAssertion = this.config.clientCredentials.clientAssertion;
addClientAssertion(parameters, await getClientAssertion(clientAssertion.assertion, this.config.authOptions.clientId, request.resourceRequestUri));
addClientAssertionType(parameters, clientAssertion.assertionType);
}
addGrantType(parameters, GrantType$1.AUTHORIZATION_CODE_GRANT);
addClientInfo(parameters);
if (request.authenticationScheme === AuthenticationScheme.POP) {
const popTokenGenerator = new PopTokenGenerator(this.cryptoUtils, this.config.tokenBindingKeyManager, this.performanceClient);
let reqCnfData;
if (!request.popKid) {
const generatedReqCnfData = await invokeAsync(popTokenGenerator.generateCnf.bind(popTokenGenerator), PopTokenGenerateCnf, this.logger, this.performanceClient, request.correlationId)(request, this.logger);
reqCnfData = generatedReqCnfData.reqCnfString;
}
else {
reqCnfData = this.cryptoUtils.encodeKid(request.popKid);
}
// SPA PoP requires full Base64Url encoded req_cnf string (unhashed)
addPopToken(parameters, reqCnfData);
}
else if (request.authenticationScheme === AuthenticationScheme.SSH) {
if (request.sshJwk) {
addSshJwk(parameters, request.sshJwk);
}
else {
throw createClientConfigurationError(missingSshJwk, request.correlationId);
}
}
let ccsCred = undefined;
if (request.clientInfo) {
try {
const clientInfo = buildClientInfo(request.clientInfo, this.cryptoUtils.base64Decode);
ccsCred = {
credential: `${clientInfo.uid}${CLIENT_INFO_SEPARATOR}${clientInfo.utid}`,
type: CcsCredentialType.HOME_ACCOUNT_ID,
};
}
catch (e) {
this.logger.verbose(`0wznt3 ${e}`, request.correlationId);
}
}
else {
ccsCred = request.ccsCredential;
}
// Adds these as parameters in the request instead of headers to prevent CORS preflight request
if (this.config.systemOptions.preventCorsPreflight && ccsCred) {
switch (ccsCred.type) {
case CcsCredentialType.HOME_ACCOUNT_ID:
try {
const clientInfo = buildClientInfoFromHomeAccountId(ccsCred.credential);
addCcsOid(parameters, clientInfo);
}
catch (e) {
this.logger.verbose(`1qhtee ${e}`, request.correlationId);
}
break;
case CcsCredentialType.UPN:
addCcsUpn(parameters, ccsCred.credential);
break;
}
}
if (request.embeddedClientId) {
addBrokerParameters(parameters, this.config.authOptions.clientId, this.config.authOptions.redirectUri);
}
if (request.extraParameters) {
addExtraParameters(parameters, request.extraParameters);
}
// Add hybrid spa parameters if not already provided
if (request.enableSpaAuthorizationCode &&
(!request.extraParameters ||
!request.extraParameters[RETURN_SPA_CODE])) {
addExtraParameters(parameters, {
[RETURN_SPA_CODE]: "1",
});
}
instrumentBrokerParams(parameters, request.correlationId, this.performanceClient);
addClaims(parameters, request.correlationId, request.claims, this.config.authOptions.clientCapabilities, request.skipBrokerClaims);
return mapToQueryString(parameters);
}
/**
* This API validates the `EndSessionRequest` and creates a URL
* @param request
*/
createLogoutUrlQueryString(request) {
const parameters = new Map();
if (request.postLogoutRedirectUri) {
addPostLogoutRedirectUri(parameters, request.postLogoutRedirectUri);
}
if (request.correlationId) {
addCorrelationId(parameters, request.correlationId);
}
if (request.idTokenHint) {
addIdTokenHint(parameters, request.idTokenHint);
}
if (request.state) {
addState(parameters, request.state);
}
if (request.logoutHint) {
addLogoutHint(parameters, request.logoutHint);
}
if (request.extraQueryParameters) {
addExtraParameters(parameters, request.extraQueryParameters);
}
if (this.config.authOptions.instanceAware) {
addInstanceAware(parameters);
}
return mapToQueryString(parameters);
}
/**
* Updates the authority to the cloud instance provided in the authorization response
* @param cloudInstanceHostName - cloud instance host name from authorization code payload
* @param correlationId - request correlation id
*/
async updateTokenEndpointAuthority(cloudInstanceHostName, correlationId) {
const cloudInstanceAuthorityUri = `https://${cloudInstanceHostName}/${this.authority.tenant}/`;
const cloudInstanceAuthority = await createDiscoveredInstance(cloudInstanceAuthorityUri, this.networkClient, this.cacheManager, this.authority.options, this.logger, correlationId, this.performanceClient);
this.authority = cloudInstanceAuthority;
}
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Returns map of parameters that are applicable to all calls to /authorize whether using PKCE or EAR
* @param config
* @param request
* @param logger
* @param performanceClient
* @returns
* @internal
*/
function getStandardAuthorizeRequestParameters(authOptions, request, logger, performanceClient) {
// generate the correlationId if not set by the user and add
const correlationId = request.correlationId;
const parameters = new Map();
addClientId(parameters, request.embeddedClientId ||
request.extraQueryParameters?.[CLIENT_ID] ||
authOptions.clientId);
const requestScopes = [
...(request.scopes || []),
...(request.extraScopesToConsent || []),
];
addScopes(parameters, requestScopes, request.correlationId, true, authOptions.authority.options.OIDCOptions?.defaultScopes);
addResource(parameters, request.resource);
addRedirectUri(parameters, request.redirectUri);
addCorrelationId(parameters, correlationId);
// add response_mode. If not passed in it defaults to query.
addResponseMode(parameters, request.responseMode);
// add client_info=1
addClientInfo(parameters);
// add clidata=1
addCliData(parameters);
if (request.prompt) {
addPrompt(parameters, request.prompt);
performanceClient?.addFields({ prompt: request.prompt }, correlationId);
}
if (request.domainHint) {
addDomainHint(parameters, request.domainHint);
performanceClient?.addFields({ domainHintFromRequest: true }, correlationId);
}
// Add sid or loginHint with preference for login_hint claim (in request) -> sid -> loginHint (upn/email) -> username of AccountInfo object
if (request.prompt !== PromptValue.SELECT_ACCOUNT) {
// AAD will throw if prompt=select_account is passed with an account hint
if (request.sid && request.prompt === PromptValue.NONE) {
// SessionID is only used in silent calls
logger.verbose("1tvqyx", request.correlationId);
addSid(parameters, request.sid);
performanceClient?.addFields({ sidFromRequest: true }, correlationId);
}
else if (request.account) {
const accountSid = extractAccountSid(request.account);
let accountLoginHintClaim = extractLoginHint(request.account);
if (accountLoginHintClaim && request.domainHint) {
logger.warning("0wkg3v", request.correlationId);
accountLoginHintClaim = null;
}
// If login_hint claim is present, use it over sid/username
if (accountLoginHintClaim) {
logger.verbose("1eyfsw", request.correlationId);
addLoginHint(parameters, accountLoginHintClaim);
performanceClient?.addFields({ loginHintFromClaim: true }, correlationId);
try {
const clientInfo = buildClientInfoFromHomeAccountId(request.account.homeAccountId);
addCcsOid(parameters, clientInfo);
}
catch (e) {
logger.verbose("12ugck", request.correlationId);
}
}
else if (accountSid && request.prompt === PromptValue.NONE) {
/*
* If account and loginHint are provided, we will check account first for sid before adding loginHint
* SessionId is only used in silent calls
*/
logger.verbose("1rmd8s", request.correlationId);
addSid(parameters, accountSid);
performanceClient?.addFields({ sidFromClaim: true }, correlationId);
try {
const clientInfo = buildClientInfoFromHomeAccountId(request.account.homeAccountId);
addCcsOid(parameters, clientInfo);
}
catch (e) {
logger.verbose("12ugck", request.correlationId);
}
}
else if (request.loginHint) {
logger.verbose("0y3007", request.correlationId);
addLoginHint(parameters, request.loginHint);
addCcsUpn(parameters, request.loginHint);
performanceClient?.addFields({ loginHintFromRequest: true }, correlationId);
}
else if (request.account.username) {
// Fallback to account username if provided
logger.verbose("02f507", request.correlationId);
addLoginHint(parameters, request.account.username);
performanceClient?.addFields({ loginHintFromUpn: true }, correlationId);
try {
const clientInfo = buildClientInfoFromHomeAccountId(request.account.homeAccountId);
addCcsOid(parameters, clientInfo);
}
catch (e) {
logger.verbose("12ugck", request.correlationId);
}
}
}
else if (request.loginHint) {
logger.verbose("0g01ey", request.correlationId);
addLoginHint(parameters, request.loginHint);
addCcsUpn(parameters, request.loginHint);
performanceClient?.addFields({ loginHintFromRequest: true }, correlationId);
}
}
else {
logger.verbose("169k9v", request.correlationId);
}
if (request.nonce) {
addNonce(parameters, request.nonce);
}
if (request.state) {
addState(parameters, request.state);
}
if (request.embeddedClientId) {
addBrokerParameters(parameters, authOptions.clientId, authOptions.redirectUri);
}
addClaims(parameters, request.correlationId, request.claims, authOptions.clientCapabilities, request.skipBrokerClaims);
// If extraQueryParameters includes instance_aware its value will be added when extraQueryParameters are added
if (authOptions.instanceAware &&
(!request.extraQueryParameters ||
!Object.keys(request.extraQueryParameters).includes(INSTANCE_AWARE))) {
addInstanceAware(parameters);
}
return parameters;
}
/**
* Returns authorize endpoint with given request parameters in the query string
* @param authority
* @param requestParameters
* @returns
* @internal
*/
function getAuthorizeUrl(authority, requestParameters) {
const queryString = mapToQueryString(requestParameters);
return UrlString.appendQueryString(authority.authorizationEndpoint, queryString);
}
/**
* Handles the hash fragment response from public client code request. Returns a code response used by
* the client to exchange for a token in acquireToken.
* @param serverParams
* @param cachedState
* @param correlationId
*/
function getAuthorizationCodePayload(serverParams, cachedState, correlationId) {
// Get code response
validateAuthorizationResponse(serverParams, cachedState, correlationId);
// throw when there is no auth code in the response
if (!serverParams.code) {
throw createClientAuthError(authorizationCodeMissingFromServerResponse, correlationId);
}
return serverParams;
}
/**
* Function which validates server authorization code response.
* @param serverResponseHash
* @param requestState
* @param correlationId
*/
function validateAuthorizationResponse(serverResponse, requestState, correlationId) {
if (!serverResponse.state || !requestState) {
throw serverResponse.state
? createClientAuthError(stateNotFound, correlationId, "Cached State")
: createClientAuthError(stateNotFound, correlationId, "Server State");
}
let decodedServerResponseState;
let decodedRequestState;
try {
decodedServerResponseState = decodeURIComponent(serverResponse.state);
}
catch (e) {
throw createClientAuthError(invalidState, correlationId, serverResponse.state);
}
try {
decodedRequestState = decodeURIComponent(requestState);
}
catch (e) {
throw createClientAuthError(invalidState, correlationId, serverResponse.state);
}
if (decodedServerResponseState !== decodedRequestState) {
throw createClientAuthError(stateMismatch, correlationId);
}
// Check for error
if (serverResponse.error ||
serverResponse.error_description ||
serverResponse.suberror) {
const serverErrorNo = parseServerErrorNo(serverResponse);
if (isInteractionRequiredError(serverResponse.error, serverResponse.error_description, serverResponse.suberror)) {
throw new InteractionRequiredAuthError(serverResponse.error || "", serverResponse.correlation_id || correlationId, serverResponse.error_description, serverResponse.suberror, serverResponse.timestamp || "", serverResponse.trace_id || "", serverResponse.claims || "", serverErrorNo);
}
throw new ServerError(serverResponse.error || "", serverResponse.correlation_id || correlationId, serverResponse.error_description, serverResponse.suberror, serverErrorNo);
}
}
/**
* Get server error No from the error_uri
* @param serverResponse
* @returns
*/
function parseServerErrorNo(serverResponse) {
const errorCodePrefix = "code=";
const errorCodePrefixIndex = serverResponse.error_uri?.lastIndexOf(errorCodePrefix);
return errorCodePrefixIndex && errorCodePrefixIndex >= 0
? serverResponse.error_uri?.substring(errorCodePrefixIndex + errorCodePrefix.length)
: undefined;
}
/**
* Helper to get sid from account. Returns null if idTokenClaims are not present or sid is not present.
* @param account
*/
function extractAccountSid(account) {
return account.idTokenClaims?.sid || null;
}
function extractLoginHint(account) {
return account.loginHint || account.idTokenClaims?.login_hint || null;
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const DEFAULT_REFRESH_TOKEN_EXPIRATION_OFFSET_SECONDS = 300; // 5 Minutes
/**
* OAuth2.0 refresh token client
* @internal
*/
class RefreshTokenClient {
constructor(configuration, performanceClient) {
// Set the configuration
this.config = buildClientConfiguration(configuration);
// Initialize the logger
this.logger = new Logger(this.config.loggerOptions, name$1, version$1);
// Initialize crypto
this.cryptoUtils = this.config.cryptoInterface;
// Initialize storage interface
this.cacheManager = this.config.storageInterface;
// Set the network interface
this.networkClient = this.config.networkInterface;
// Set TelemetryManager
this.serverTelemetryManager = this.config.serverTelemetryManager;
// set Authority
this.authority = this.config.authOptions.authority;
// set performance telemetry client
this.performanceClient = performanceClient;
}
async acquireToken(request, apiId) {
const reqTimestamp = nowSeconds();
const response = await invokeAsync(this.executeTokenRequest.bind(this), RefreshTokenClientExecuteTokenRequest, this.logger, this.performanceClient, request.correlationId)(request, this.authority);
// Retrieve requestId from response headers
const requestId = response.headers?.[HeaderNames.X_MS_REQUEST_ID];
const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.performanceClient, this.config.serializableCache, this.config.persistencePlugin, this.config.tokenBindingKeyManager);
responseHandler.validateTokenResponse(response.body, request.correlationId);
return invokeAsync(responseHandler.handleServerTokenResponse.bind(responseHandler), HandleServerTokenResponse, this.logger, this.performanceClient, request.correlationId)(response.body, this.authority, reqTimestamp, request, apiId, undefined, undefined, true, request.forceCache, requestId);
}
/**
* Gets cached refresh token and attaches to request, then calls acquireToken API
* @param request
*/
async acquireTokenByRefreshToken(request, apiId) {
// Cannot renew token if no request object is given.
if (!request) {
throw createClientConfigurationError(tokenRequestEmpty, "");
}
// We currently do not support silent flow for account === null use cases; This will be revisited for confidential flow usecases
if (!request.account) {
throw createClientAuthError(noAccountInSilentRequest, request.correlationId);
}
// try checking if FOCI is enabled for the given application
const isFOCI = this.cacheManager.isAppMetadataFOCI(request.account.environment, request.correlationId);
// if the app is part of the family, retrive a Family refresh token if present and make a refreshTokenRequest
if (isFOCI) {
try {
return await invokeAsync(this.acquireTokenWithCachedRefreshToken.bind(this), RefreshTokenClientAcquireTokenWithCachedRefreshToken, this.logger, this.performanceClient, request.correlationId)(request, true, apiId);
}
catch (e) {
const noFamilyRTInCache = e instanceof InteractionRequiredAuthError &&
e.errorCode ===
noTokensFound;
const clientMismatchErrorWithFamilyRT = e instanceof ServerError &&
e.errorCode === INVALID_GRANT_ERROR &&
e.subError === CLIENT_MISMATCH_ERROR;
// if family Refresh Token (FRT) cache acquisition fails or if client_mismatch error is seen with FRT, reattempt with application Refresh Token (ART)
if (noFamilyRTInCache || clientMismatchErrorWithFamilyRT) {
return invokeAsync(this.acquireTokenWithCachedRefreshToken.bind(this), RefreshTokenClientAcquireTokenWithCachedRefreshToken, this.logger, this.performanceClient, request.correlationId)(request, false, apiId);
// throw in all other cases
}
else {
throw e;
}
}
}
// fall back to application refresh token acquisition
return invokeAsync(this.acquireTokenWithCachedRefreshToken.bind(this), RefreshTokenClientAcquireTokenWithCachedRefreshToken, this.logger, this.performanceClient, request.correlationId)(request, false, apiId);
}
/**
* makes a network call to acquire tokens by exchanging RefreshToken available in userCache; throws if refresh token is not cached
* @param request
*/
async acquireTokenWithCachedRefreshToken(request, foci, apiId) {
// fetches family RT or application RT based on FOCI value
const refreshToken = invoke(this.cacheManager.getRefreshToken.bind(this.cacheManager), CacheManagerGetRefreshToken, this.logger, this.performanceClient, request.correlationId)(request.account, foci, request.correlationId, undefined);
if (!refreshToken) {
throw createInteractionRequiredAuthError(noTokensFound, request.correlationId);
}
if (refreshToken.expiresOn) {
const offset = request.refreshTokenExpirationOffsetSeconds ||
DEFAULT_REFRESH_TOKEN_EXPIRATION_OFFSET_SECONDS;
this.performanceClient?.addFields({
cacheRtExpiresOnSeconds: Number(refreshToken.expiresOn),
rtOffsetSeconds: offset,
}, request.correlationId);
if (isTokenExpired(refreshToken.expiresOn, offset)) {
throw createInteractionRequiredAuthError(refreshTokenExpired, request.correlationId);
}
}
// attach cached RT size to the current measurement
const refreshTokenRequest = {
...request,
refreshToken: refreshToken.secret,
authenticationScheme: request.authenticationScheme ||
AuthenticationScheme.BEARER,
ccsCredential: {
credential: request.account.homeAccountId,
type: CcsCredentialType.HOME_ACCOUNT_ID,
},
};
if (refreshTokenRequest.authenticationScheme ===
AuthenticationScheme.DPOP &&
!refreshTokenRequest.dpopJkt) {
const dpopProofGenerator = new DpopProofGenerator(this.cryptoUtils, this.config.tokenBindingKeyManager);
refreshTokenRequest.dpopJkt = await dpopProofGenerator.generateJkt(request.correlationId);
}
try {
return await invokeAsync(this.acquireToken.bind(this), RefreshTokenClientAcquireToken, this.logger, this.performanceClient, request.correlationId)(refreshTokenRequest, apiId);
}
catch (e) {
if (e instanceof InteractionRequiredAuthError) {
if (e.subError === badToken) {
// Remove bad refresh token from cache
this.logger.verbose("1pg3ap", request.correlationId);
const badRefreshTokenKey = this.cacheManager.generateCredentialKey(refreshToken);
this.cacheManager.removeRefreshToken(badRefreshTokenKey, request.correlationId);
}
}
throw e;
}
}
/**
* Constructs the network message and makes a NW call to the underlying secure token service
* @param request
* @param authority
*/
async executeTokenRequest(request, authority) {
const queryParametersString = createTokenQueryParameters(request, this.config.authOptions.clientId, this.config.authOptions.redirectUri, this.performanceClient);
const endpoint = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString);
const requestBody = await invokeAsync(this.createTokenRequestBody.bind(this), RefreshTokenClientCreateTokenRequestBody, this.logger, this.performanceClient, request.correlationId)(request);
const headers = createTokenRequestHeaders(this.logger, this.config.systemOptions.preventCorsPreflight, request.ccsCredential);
await addDpopTokenProofHeader(headers, request, endpoint, this.cryptoUtils, this.config.tokenBindingKeyManager);
const thumbprint = getRequestThumbprint(this.config.authOptions.clientId, request);
return invokeAsync(executePostToTokenEndpoint, RefreshTokenClientExecutePostToTokenEndpoint, this.logger, this.performanceClient, request.correlationId)(endpoint, requestBody, headers, thumbprint, request.correlationId, this.cacheManager, this.networkClient, this.logger, this.performanceClient, this.serverTelemetryManager);
}
/**
* Helper function to create the token request body
* @param request
*/
async createTokenRequestBody(request) {
const parameters = new Map();
addClientId(parameters, request.embeddedClientId ||
request.extraParameters?.[CLIENT_ID] ||
this.config.authOptions.clientId);
if (request.redirectUri) {
addRedirectUri(parameters, request.redirectUri);
}
addScopes(parameters, request.scopes, request.correlationId, true, this.config.authOptions.authority.options.OIDCOptions?.defaultScopes);
addResource(parameters, request.resource);
addGrantType(parameters, GrantType$1.REFRESH_TOKEN_GRANT);
addClientInfo(parameters);
addLibraryInfo(parameters, this.config.libraryInfo);
addApplicationTelemetry(parameters, this.config.telemetry.application);
addThrottling(parameters);
if (this.serverTelemetryManager && !isOidcProtocolMode(this.config)) {
addServerTelemetry(parameters, this.serverTelemetryManager);
}
addRefreshToken(parameters, request.refreshToken);
if (request.attributeTokens) {
addAttributeTokens(parameters, request.attributeTokens);
}
this.performanceClient?.addFields({
hasAttributeTokens: !!request.attributeTokens?.length,
}, request.correlationId);
if (this.config.clientCredentials.clientSecret) {
addClientSecret(parameters, this.config.clientCredentials.clientSecret);
}
if (this.config.clientCredentials.clientAssertion) {
const clientAssertion = this.config.clientCredentials.clientAssertion;
addClientAssertion(parameters, await getClientAssertion(clientAssertion.assertion, this.config.authOptions.clientId, request.resourceRequestUri));
addClientAssertionType(parameters, clientAssertion.assertionType);
}
if (request.authenticationScheme === AuthenticationScheme.POP) {
const popTokenGenerator = new PopTokenGenerator(this.cryptoUtils, this.config.tokenBindingKeyManager, this.performanceClient);
let reqCnfData;
if (!request.popKid) {
const generatedReqCnfData = await invokeAsync(popTokenGenerator.generateCnf.bind(popTokenGenerator), PopTokenGenerateCnf, this.logger, this.performanceClient, request.correlationId)(request, this.logger);
reqCnfData = generatedReqCnfData.reqCnfString;
}
else {
reqCnfData = this.cryptoUtils.encodeKid(request.popKid);
}
// SPA PoP requires full Base64Url encoded req_cnf string (unhashed)
addPopToken(parameters, reqCnfData);
}
else if (request.authenticationScheme === AuthenticationScheme.SSH) {
if (request.sshJwk) {
addSshJwk(parameters, request.sshJwk);
}
else {
throw createClientConfigurationError(missingSshJwk, request.correlationId);
}
}
if (this.config.systemOptions.preventCorsPreflight &&
request.ccsCredential) {
switch (request.ccsCredential.type) {
case CcsCredentialType.HOME_ACCOUNT_ID:
try {
const clientInfo = buildClientInfoFromHomeAccountId(request.ccsCredential.credential);
addCcsOid(parameters, clientInfo);
}
catch (e) {
this.logger.verbose(`1qhtee ${e}`, request.correlationId);
}
break;
case CcsCredentialType.UPN:
addCcsUpn(parameters, request.ccsCredential.credential);
break;
}
}
if (request.embeddedClientId) {
addBrokerParameters(parameters, this.config.authOptions.clientId, this.config.authOptions.redirectUri);
}
if (request.extraParameters) {
addExtraParameters(parameters, {
...request.extraParameters,
});
}
instrumentBrokerParams(parameters, request.correlationId, this.performanceClient);
addClaims(parameters, request.correlationId, request.claims, this.config.authOptions.clientCapabilities, request.skipBrokerClaims);
return mapToQueryString(parameters);
}
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const skuGroupSeparator = ",";
const skuValueSeparator = "|";
function makeExtraSkuString(params) {
const { skus, libraryName, libraryVersion, extensionName, extensionVersion, } = params;
const skuMap = new Map([
[0, [libraryName, libraryVersion]],
[2, [extensionName, extensionVersion]],
]);
let skuArr = [];
if (skus?.length) {
skuArr = skus.split(skuGroupSeparator);
// Ignore invalid input sku param
if (skuArr.length < 4) {
return skus;
}
}
else {
skuArr = Array.from({ length: 4 }, () => skuValueSeparator);
}
skuMap.forEach((value, key) => {
if (value.length === 2 && value[0]?.length && value[1]?.length) {
setSku({
skuArr,
index: key,
skuName: value[0],
skuVersion: value[1],
});
}
});
return skuArr.join(skuGroupSeparator);
}
function setSku(params) {
const { skuArr, index, skuName, skuVersion } = params;
if (index >= skuArr.length) {
return;
}
skuArr[index] = [skuName, skuVersion].join(skuValueSeparator);
}
/** @internal */
class ServerTelemetryManager {
constructor(telemetryRequest, cacheManager) {
this.cacheOutcome = CacheOutcome.NOT_APPLICABLE;
this.cacheManager = cacheManager;
this.apiId = telemetryRequest.apiId;
this.correlationId = telemetryRequest.correlationId;
this.wrapperSKU = telemetryRequest.wrapperSKU || "";
this.wrapperVer = telemetryRequest.wrapperVer || "";
this.telemetryCacheKey =
SERVER_TELEM_CACHE_KEY +
CACHE_KEY_SEPARATOR$1 +
telemetryRequest.clientId;
}
/**
* API to add MSER Telemetry to request
*/
generateCurrentRequestHeaderValue() {
const request = `${this.apiId}${SERVER_TELEM_VALUE_SEPARATOR}${this.cacheOutcome}`;
const platformFieldsArr = [this.wrapperSKU, this.wrapperVer];
const nativeBrokerErrorCode = this.getNativeBrokerErrorCode();
if (nativeBrokerErrorCode?.length) {
platformFieldsArr.push(`broker_error=${nativeBrokerErrorCode}`);
}
const platformFields = platformFieldsArr.join(SERVER_TELEM_VALUE_SEPARATOR);
const regionDiscoveryFields = this.getRegionDiscoveryFields();
const requestWithRegionDiscoveryFields = [
request,
regionDiscoveryFields,
].join(SERVER_TELEM_VALUE_SEPARATOR);
return [
SERVER_TELEM_SCHEMA_VERSION,
requestWithRegionDiscoveryFields,
platformFields,
].join(SERVER_TELEM_CATEGORY_SEPARATOR);
}
/**
* API to add MSER Telemetry for the last failed request
*/
generateLastRequestHeaderValue() {
const lastRequests = this.getLastRequests();
const maxErrors = ServerTelemetryManager.maxErrorsToSend(lastRequests);
const failedRequests = lastRequests.failedRequests
.slice(0, 2 * maxErrors)
.join(SERVER_TELEM_VALUE_SEPARATOR);
const errors = lastRequests.errors
.slice(0, maxErrors)
.join(SERVER_TELEM_VALUE_SEPARATOR);
const errorCount = lastRequests.errors.length;
// Indicate whether this header contains all data or partial data
const overflow = maxErrors < errorCount
? SERVER_TELEM_OVERFLOW_TRUE
: SERVER_TELEM_OVERFLOW_FALSE;
const platformFields = [errorCount, overflow].join(SERVER_TELEM_VALUE_SEPARATOR);
return [
SERVER_TELEM_SCHEMA_VERSION,
lastRequests.cacheHits,
failedRequests,
errors,
platformFields,
].join(SERVER_TELEM_CATEGORY_SEPARATOR);
}
/**
* API to cache token failures for MSER data capture
* @param error
*/
cacheFailedRequest(error) {
try {
const lastRequests = this.getLastRequests();
if (lastRequests.errors.length >=
SERVER_TELEM_MAX_CACHED_ERRORS) {
// Remove a cached error to make room, first in first out
lastRequests.failedRequests.shift(); // apiId
lastRequests.failedRequests.shift(); // correlationId
lastRequests.errors.shift();
}
lastRequests.failedRequests.push(this.apiId, this.correlationId);
if (error instanceof Error && !!error && error.toString()) {
if (error instanceof AuthError) {
if (error.subError) {
lastRequests.errors.push(error.subError);
}
else if (error.errorCode) {
lastRequests.errors.push(error.errorCode);
}
else {
lastRequests.errors.push(error.toString());
}
}
else {
lastRequests.errors.push(error.toString());
}
}
else {
lastRequests.errors.push(SERVER_TELEM_UNKNOWN_ERROR);
}
this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests, this.correlationId);
}
catch {
// Ignore telemetry cache failures to avoid masking the original auth error path.
}
return;
}
/**
* Update server telemetry cache entry by incrementing cache hit counter
*/
incrementCacheHits() {
const lastRequests = this.getLastRequests();
lastRequests.cacheHits += 1;
this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests, this.correlationId);
return lastRequests.cacheHits;
}
/**
* Get the server telemetry entity from cache or initialize a new one
*/
getLastRequests() {
const initialValue = {
failedRequests: [],
errors: [],
cacheHits: 0,
};
const lastRequests = this.cacheManager.getServerTelemetry(this.telemetryCacheKey, this.correlationId);
return lastRequests || initialValue;
}
/**
* Remove server telemetry cache entry
*/
clearTelemetryCache() {
const lastRequests = this.getLastRequests();
const numErrorsFlushed = ServerTelemetryManager.maxErrorsToSend(lastRequests);
const errorCount = lastRequests.errors.length;
if (numErrorsFlushed === errorCount) {
// All errors were sent on last request, clear Telemetry cache
this.cacheManager.removeItem(this.telemetryCacheKey, this.correlationId);
}
else {
// Partial data was flushed to server, construct a new telemetry cache item with errors that were not flushed
const serverTelemEntity = {
failedRequests: lastRequests.failedRequests.slice(numErrorsFlushed * 2),
errors: lastRequests.errors.slice(numErrorsFlushed),
cacheHits: 0,
};
this.cacheManager.setServerTelemetry(this.telemetryCacheKey, serverTelemEntity, this.correlationId);
}
}
/**
* Returns the maximum number of errors that can be flushed to the server in the next network request
* @param serverTelemetryEntity
*/
static maxErrorsToSend(serverTelemetryEntity) {
let i;
let maxErrors = 0;
let dataSize = 0;
const errorCount = serverTelemetryEntity.errors.length;
for (i = 0; i < errorCount; i++) {
// failedRequests parameter contains pairs of apiId and correlationId, multiply index by 2 to preserve pairs
const apiId = serverTelemetryEntity.failedRequests[2 * i] || "";
const correlationId = serverTelemetryEntity.failedRequests[2 * i + 1] || "";
const errorCode = serverTelemetryEntity.errors[i] || "";
// Count number of characters that would be added to header, each character is 1 byte. Add 3 at the end to account for separators
dataSize +=
apiId.toString().length +
correlationId.toString().length +
errorCode.length +
3;
if (dataSize < SERVER_TELEM_MAX_LAST_HEADER_BYTES) {
// Adding this entry to the header would still keep header size below the limit
maxErrors += 1;
}
else {
break;
}
}
return maxErrors;
}
/**
* Get the region discovery fields
*
* @returns string
*/
getRegionDiscoveryFields() {
const regionDiscoveryFields = [];
regionDiscoveryFields.push(this.regionUsed || "");
regionDiscoveryFields.push(this.regionSource || "");
regionDiscoveryFields.push(this.regionOutcome || "");
return regionDiscoveryFields.join(",");
}
/**
* Update the region discovery metadata
*
* @param regionDiscoveryMetadata
* @returns void
*/
updateRegionDiscoveryMetadata(regionDiscoveryMetadata) {
this.regionUsed = regionDiscoveryMetadata.region_used;
this.regionSource = regionDiscoveryMetadata.region_source;
this.regionOutcome = regionDiscoveryMetadata.region_outcome;
}
/**
* Set cache outcome
*/
setCacheOutcome(cacheOutcome) {
this.cacheOutcome = cacheOutcome;
}
setNativeBrokerErrorCode(errorCode) {
const lastRequests = this.getLastRequests();
lastRequests.nativeBrokerErrorCode = errorCode;
this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests, this.correlationId);
}
getNativeBrokerErrorCode() {
return this.getLastRequests().nativeBrokerErrorCode;
}
clearNativeBrokerErrorCode() {
const lastRequests = this.getLastRequests();
delete lastRequests.nativeBrokerErrorCode;
this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests, this.correlationId);
}
static makeExtraSkuString(params) {
return makeExtraSkuString(params);
}
}
/** @internal */
class StubServerTelemetryManager extends ServerTelemetryManager {
constructor() {
super({ clientId: "", apiId: 0, correlationId: "", forceRefresh: false }, {});
}
generateCurrentRequestHeaderValue() {
return "";
}
generateLastRequestHeaderValue() {
return "";
}
cacheFailedRequest() { }
incrementCacheHits() {
return 0;
}
clearTelemetryCache() { }
getRegionDiscoveryFields() {
return "";
}
updateRegionDiscoveryMetadata() { }
setCacheOutcome() { }
setNativeBrokerErrorCode() { }
getNativeBrokerErrorCode() {
return undefined;
}
clearNativeBrokerErrorCode() { }
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/** @internal */
class SilentFlowClient {
constructor(configuration, performanceClient) {
// Set the configuration
this.config = buildClientConfiguration(configuration);
// Initialize the logger
this.logger = new Logger(this.config.loggerOptions, name$1, version$1);
// Initialize crypto
this.cryptoUtils = this.config.cryptoInterface;
// Initialize storage interface
this.cacheManager = this.config.storageInterface;
// Set the network interface
this.networkClient = this.config.networkInterface;
// Set TelemetryManager
this.serverTelemetryManager = this.config.serverTelemetryManager;
// set Authority
this.authority = this.config.authOptions.authority;
// set performance telemetry client
this.performanceClient = performanceClient;
}
/**
* Retrieves token from cache or throws an error if it must be refreshed.
* @param request
*/
async acquireCachedToken(request) {
let lastCacheOutcome = CacheOutcome.NOT_APPLICABLE;
if (request.forceRefresh || !StringUtils.isEmptyObj(request.claims)) {
// Must refresh due to present force_refresh flag.
this.setCacheOutcome(CacheOutcome.FORCE_REFRESH_OR_CLAIMS, request.correlationId);
throw createClientAuthError(tokenRefreshRequired, request.correlationId);
}
// We currently do not support silent flow for account === null use cases; This will be revisited for confidential flow usecases
if (!request.account) {
throw createClientAuthError(noAccountInSilentRequest, request.correlationId);
}
const requestTenantId = request.account.tenantId ||
getTenantFromAuthorityString(request.authority, request.correlationId);
const tokenKeys = this.cacheManager.getTokenKeys();
const cachedAccessToken = this.cacheManager.getAccessToken(request.account, request, tokenKeys, requestTenantId);
if (!cachedAccessToken) {
// must refresh due to non-existent access_token
this.setCacheOutcome(CacheOutcome.NO_CACHED_ACCESS_TOKEN, request.correlationId);
throw createClientAuthError(tokenRefreshRequired, request.correlationId);
}
else if (wasClockTurnedBack(cachedAccessToken.cachedAt) ||
isTokenExpired(cachedAccessToken.expiresOn, this.config.systemOptions.tokenRenewalOffsetSeconds)) {
// must refresh due to the expires_in value
this.setCacheOutcome(CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED, request.correlationId);
throw createClientAuthError(tokenRefreshRequired, request.correlationId);
}
else if (request.resource) {
// cached access token must have a resource that matches the request resource for MCP scenarios
if (cachedAccessToken.resource !== request.resource) {
this.setCacheOutcome(CacheOutcome.NO_CACHED_ACCESS_TOKEN, request.correlationId);
throw createClientAuthError(tokenRefreshRequired, request.correlationId);
}
}
else if (cachedAccessToken.refreshOn &&
isTokenExpired(cachedAccessToken.refreshOn, 0)) {
// must refresh (in the background) due to the refresh_in value
lastCacheOutcome = CacheOutcome.PROACTIVELY_REFRESHED;
// don't throw ClientAuthError.createRefreshRequiredError(), return cached token instead
}
const cachedAccessTokenType = cachedAccessToken.tokenType?.toLowerCase();
if (cachedAccessTokenType === AuthenticationScheme.DPOP.toLowerCase()) {
if (!cachedAccessToken.keyId) {
this.logger.info("1enswf", request.correlationId);
this.setCacheOutcome(CacheOutcome.NO_CACHED_ACCESS_TOKEN, request.correlationId);
throw createClientAuthError(tokenRefreshRequired, request.correlationId);
}
try {
await this.config.tokenBindingKeyManager.getTokenBindingPublicKeyJwk(cachedAccessToken.keyId, request.correlationId);
}
catch {
this.logger.info("14djth", request.correlationId);
this.setCacheOutcome(CacheOutcome.NO_CACHED_ACCESS_TOKEN, request.correlationId);
throw createClientAuthError(tokenRefreshRequired, request.correlationId);
}
}
const environment = request.authority || this.authority.getPreferredCache();
const cacheRecord = {
account: this.cacheManager.getAccount(this.cacheManager.generateAccountKey(request.account), request.correlationId),
accessToken: cachedAccessToken,
idToken: this.cacheManager.getIdToken(request.account, request.correlationId, tokenKeys, requestTenantId),
refreshToken: null,
appMetadata: this.cacheManager.readAppMetadataFromCache(environment, request.correlationId),
};
this.setCacheOutcome(lastCacheOutcome, request.correlationId);
if (this.config.serverTelemetryManager) {
this.config.serverTelemetryManager.incrementCacheHits();
}
return [
await invokeAsync(this.generateResultFromCacheRecord.bind(this), SilentFlowClientGenerateResultFromCacheRecord, this.logger, this.performanceClient, request.correlationId)(cacheRecord, request),
lastCacheOutcome,
];
}
setCacheOutcome(cacheOutcome, correlationId) {
this.serverTelemetryManager?.setCacheOutcome(cacheOutcome);
this.performanceClient?.addFields({
cacheOutcome: cacheOutcome,
}, correlationId);
if (cacheOutcome !== CacheOutcome.NOT_APPLICABLE) {
this.logger.info(`09ingz ${cacheOutcome}`, correlationId);
}
}
/**
* Helper function to build response object from the CacheRecord
* @param cacheRecord
*/
async generateResultFromCacheRecord(cacheRecord, request) {
let idTokenClaims;
if (cacheRecord.idToken) {
idTokenClaims = extractTokenClaims(cacheRecord.idToken.secret, this.config.cryptoInterface.base64Decode, request.correlationId);
}
return ResponseHandler.generateAuthenticationResult(this.cryptoUtils, this.authority, cacheRecord, true, request, this.performanceClient, {
idTokenClaims,
tokenBindingKeyManager: this.config.tokenBindingKeyManager,
});
}
}
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const StubbedNetworkModule = {
// Module-level singleton: no per-request correlationId available
sendGetRequestAsync: () => {
return Promise.reject(createClientAuthError(methodNotImplemented, ""));
},
sendPostRequestAsync: () => {
return Promise.reject(createClientAuthError(methodNotImplemented, ""));
},
};
/*! @azure/msal-common v16.14.2 2026-10-06 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Helper to enforce resource parameter presence in token requests when isMcp is set in the configuration.
* If resource parameter is set in both the request and in extraQueryParameters or extraParameters, an error will be thrown.
* This is used for MCP flows.
* @param isMcp - Flag indicating if application is an MCP app, from configuration
* @param request - Auth request
*/
function enforceResourceParameter(isMcp, request) {
if (!isMcp) {
return;
}
if (request.resource &&
(containsResourceParam(request.extraParameters) ||
containsResourceParam(request.extraQueryParameters))) {
throw createClientAuthError(misplacedResourceParam, request.correlationId || "");
}
if (!request.resource) {
throw createClientAuthError(resourceParameterRequired, request.correlationId || "");
}
}
function containsResourceParam(params) {
if (!params) {
return false;
}
return Object.prototype.hasOwnProperty.call(params, "resource");
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class CustomAuthError extends Error {
constructor(error, errorDescription, correlationId, errorCodes, subError) {
super(`${error}: ${errorDescription ?? ""}`);
this.error = error;
this.errorDescription = errorDescription;
this.correlationId = correlationId;
this.errorCodes = errorCodes;
this.subError = subError;
Object.setPrototypeOf(this, CustomAuthError.prototype);
this.errorCodes = errorCodes ?? [];
this.subError = subError ?? "";
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class MsalCustomAuthError extends CustomAuthError {
constructor(error, errorDescription, subError, errorCodes, correlationId) {
super(error, errorDescription, correlationId, errorCodes, subError);
Object.setPrototypeOf(this, MsalCustomAuthError.prototype);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class UnexpectedError extends CustomAuthError {
constructor(errorData, correlationId) {
let errorDescription;
if (errorData instanceof Error) {
errorDescription = errorData.message;
}
else if (typeof errorData === "string") {
errorDescription = errorData;
}
else if (typeof errorData === "object" && errorData !== null) {
errorDescription = JSON.stringify(errorData);
}
else {
errorDescription = "An unexpected error occurred.";
}
super("unexpected_error", errorDescription, correlationId);
Object.setPrototypeOf(this, UnexpectedError.prototype);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Base class for a result of an authentication operation.
* @typeParam TState - The type of the auth flow state.
* @typeParam TError - The type of error.
* @typeParam TData - The type of the result data.
*/
class AuthFlowResultBase {
/*
*constructor for ResultBase
* @param state - The state.
* @param data - The result data.
*/
constructor(state, data) {
this.state = state;
this.data = data;
}
/*
* Creates a CustomAuthError with an error.
* @param error - The error that occurred.
* @returns The auth error.
*/
static createErrorData(error) {
if (error instanceof CustomAuthError) {
return error;
}
else if (error instanceof AuthError) {
const errorCodes = [];
if ("errorNo" in error) {
if (typeof error.errorNo === "string") {
const code = Number(error.errorNo);
if (!isNaN(code)) {
errorCodes.push(code);
}
}
else if (typeof error.errorNo === "number") {
errorCodes.push(error.errorNo);
}
}
return new MsalCustomAuthError(error.errorCode, error.errorMessage, error.subError, errorCodes, error.correlationId);
}
else {
return new UnexpectedError(error);
}
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Error when no required authentication method by Microsoft Entra is supported
*/
class RedirectError extends CustomAuthError {
constructor(correlationId, redirectReason) {
super("redirect", redirectReason ||
"Redirect Error, a fallback to the browser-delegated authentication is needed. Use loginPopup instead.", correlationId);
this.redirectReason = redirectReason;
Object.setPrototypeOf(this, RedirectError.prototype);
}
}
/**
* Custom Auth API error.
*/
class CustomAuthApiError extends CustomAuthError {
constructor(error, errorDescription, correlationId, errorCodes, subError, attributes, continuationToken, traceId, timestamp, attributeValidationDetails) {
super(error, errorDescription, correlationId, errorCodes, subError);
this.attributes = attributes;
this.continuationToken = continuationToken;
this.traceId = traceId;
this.timestamp = timestamp;
this.attributeValidationDetails = attributeValidationDetails;
Object.setPrototypeOf(this, CustomAuthApiError.prototype);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class NoCachedAccountFoundError extends CustomAuthError {
constructor(correlationId) {
super("no_cached_account_found", "No account found in the cache", correlationId);
Object.setPrototypeOf(this, NoCachedAccountFoundError.prototype);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class InvalidArgumentError extends CustomAuthError {
constructor(argName, correlationId) {
const errorDescription = `The argument '${argName}' is invalid.`;
super("invalid_argument", errorDescription, correlationId);
Object.setPrototypeOf(this, InvalidArgumentError.prototype);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const CONTINUATION_TOKEN_MISSING$1 = "continuation_token_missing";
const INVALID_RESPONSE_BODY$1 = "invalid_response_body";
const UNSUPPORTED_CHALLENGE_TYPE = "unsupported_challenge_type";
const ACCESS_TOKEN_MISSING = "access_token_missing";
const ID_TOKEN_MISSING = "id_token_missing";
const REFRESH_TOKEN_MISSING = "refresh_token_missing";
const INVALID_EXPIRES_IN = "invalid_expires_in";
const INVALID_TOKEN_TYPE = "invalid_token_type";
const HTTP_REQUEST_FAILED$1 = "http_request_failed";
const INVALID_REQUEST = "invalid_request";
const USER_NOT_FOUND = "user_not_found";
const INVALID_GRANT = "invalid_grant";
const CREDENTIAL_REQUIRED = "credential_required";
const ATTRIBUTES_REQUIRED = "attributes_required";
const USER_ALREADY_EXISTS = "user_already_exists";
const INVALID_POLL_STATUS = "invalid_poll_status";
const PASSWORD_CHANGE_FAILED = "password_change_failed";
const PASSWORD_RESET_TIMEOUT = "password_reset_timeout";
const CLIENT_INFO_MISSING = "client_info_missing";
const EXPIRED_TOKEN = "expired_token";
const ACCESS_DENIED = "access_denied";
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const PASSWORD_TOO_WEAK$1 = "password_too_weak";
const PASSWORD_TOO_SHORT = "password_too_short";
const PASSWORD_TOO_LONG = "password_too_long";
const PASSWORD_RECENTLY_USED = "password_recently_used";
const PASSWORD_BANNED = "password_banned";
const PASSWORD_IS_INVALID = "password_is_invalid";
const INVALID_OOB_VALUE = "invalid_oob_value";
const ATTRIBUTE_VALIATION_FAILED = "attribute_validation_failed";
const REGISTRATION_REQUIRED = "registration_required";
const MFA_REQUIRED = "mfa_required";
const PROVIDER_BLOCKED_BY_REPUTATION = "provider_blocked_by_rep";
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Base class for all auth flow errors.
*/
class AuthFlowErrorBase {
constructor(errorData) {
this.errorData = errorData;
}
isUserNotFoundError() {
return this.errorData.error === USER_NOT_FOUND;
}
isUserInvalidError() {
return ((this.errorData instanceof InvalidArgumentError &&
this.errorData.errorDescription?.includes("username")) ||
(this.errorData instanceof CustomAuthApiError &&
!!this.errorData.errorDescription?.includes("username parameter is empty or not valid") &&
!!this.errorData.errorCodes?.includes(90100)));
}
isUnsupportedChallengeTypeError() {
return ((this.errorData.error === INVALID_REQUEST &&
(this.errorData.errorDescription?.includes("The challenge_type list parameter contains an unsupported challenge type") ??
false)) ||
this.errorData.error ===
UNSUPPORTED_CHALLENGE_TYPE);
}
isPasswordIncorrectError() {
const isIncorrectPassword = this.errorData.error === INVALID_GRANT &&
this.errorData instanceof CustomAuthApiError &&
(this.errorData.errorCodes ?? []).includes(50126);
const isPasswordEmpty = this.errorData instanceof InvalidArgumentError &&
this.errorData.errorDescription?.includes("password") === true;
return isIncorrectPassword || isPasswordEmpty;
}
isInvalidCodeError() {
return ((this.errorData.error === INVALID_GRANT &&
this.errorData instanceof CustomAuthApiError &&
this.errorData.subError ===
INVALID_OOB_VALUE) ||
(this.errorData instanceof InvalidArgumentError &&
(this.errorData.errorDescription?.includes("code") ||
this.errorData.errorDescription?.includes("challenge")) ===
true));
}
isRedirectError() {
return this.errorData instanceof RedirectError;
}
isInvalidNewPasswordError() {
const invalidPasswordSubErrors = new Set([
PASSWORD_BANNED,
PASSWORD_IS_INVALID,
PASSWORD_RECENTLY_USED,
PASSWORD_TOO_LONG,
PASSWORD_TOO_SHORT,
PASSWORD_TOO_WEAK$1,
]);
return (this.errorData instanceof CustomAuthApiError &&
this.errorData.error === INVALID_GRANT &&
invalidPasswordSubErrors.has(this.errorData.subError ?? ""));
}
isUserAlreadyExistsError() {
return (this.errorData instanceof CustomAuthApiError &&
this.errorData.error === USER_ALREADY_EXISTS);
}
isAttributeRequiredError() {
return (this.errorData instanceof CustomAuthApiError &&
this.errorData.error === ATTRIBUTES_REQUIRED);
}
isAttributeValidationFailedError() {
return ((this.errorData instanceof CustomAuthApiError &&
this.errorData.error === INVALID_GRANT &&
this.errorData.subError ===
ATTRIBUTE_VALIATION_FAILED) ||
(this.errorData instanceof InvalidArgumentError &&
this.errorData.errorDescription?.includes("attributes") ===
true));
}
isNoCachedAccountFoundError() {
return this.errorData instanceof NoCachedAccountFoundError;
}
isTokenExpiredError() {
return (this.errorData instanceof CustomAuthApiError &&
this.errorData.error === EXPIRED_TOKEN);
}
/**
* @todo verify the password change required error can be detected once the MFA is in place.
* This error will be raised during signin and refresh tokens when calling /token endpoint.
*/
isPasswordResetRequiredError() {
return (this.errorData instanceof CustomAuthApiError &&
this.errorData.error === INVALID_REQUEST &&
this.errorData.errorCodes?.includes(50142) === true);
}
isInvalidInputError() {
return (this.errorData instanceof CustomAuthApiError &&
this.errorData.error === INVALID_REQUEST &&
this.errorData.errorCodes?.includes(901001) === true);
}
isVerificationContactBlockedError() {
return (this.errorData instanceof CustomAuthApiError &&
this.errorData.error === ACCESS_DENIED &&
this.errorData.subError ===
PROVIDER_BLOCKED_BY_REPUTATION);
}
}
class AuthActionErrorBase extends AuthFlowErrorBase {
/**
* Checks if the error is due to the expired continuation token.
* @returns {boolean} True if the error is due to the expired continuation token, false otherwise.
*/
isTokenExpired() {
return this.isTokenExpiredError();
}
/**
* Check if client app supports the challenge type configured in Entra.
* @returns {boolean} True if client app doesn't support the challenge type configured in Entra, "loginPopup" function is required to continue the operation.
*/
isRedirectRequired() {
return this.isRedirectError();
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* The error class for get account errors.
*/
class GetAccountError extends AuthFlowErrorBase {
/**
* Checks if the error is due to no cached account found.
* @returns true if the error is due to no cached account found, false otherwise.
*/
isCurrentAccountNotFound() {
return this.isNoCachedAccountFoundError();
}
}
/**
* The error class for sign-out errors.
*/
class SignOutError extends AuthFlowErrorBase {
/**
* Checks if the error is due to the user is not signed in.
* @returns true if the error is due to the user is not signed in, false otherwise.
*/
isUserNotSignedIn() {
return this.isNoCachedAccountFoundError();
}
}
/**
* The error class for getting the current account access token errors.
*/
class GetCurrentAccountAccessTokenError extends AuthFlowErrorBase {
/**
* Checks if the error is due to no cached account found.
* @returns true if the error is due to no cached account found, false otherwise.
*/
isCurrentAccountNotFound() {
return this.isNoCachedAccountFoundError();
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
function ensureArgumentIsNotNullOrUndefined(argName, argValue, correlationId) {
if (argValue === null || argValue === undefined) {
throw new InvalidArgumentError(argName, correlationId);
}
}
function ensureArgumentIsNotEmptyString(argName, argValue, correlationId) {
if (!argValue || argValue.trim() === "") {
throw new InvalidArgumentError(argName, correlationId);
}
}
function ensureArgumentIsJSONString(argName, argValue, correlationId) {
try {
const parsed = JSON.parse(argValue);
if (typeof parsed !== "object" ||
parsed === null ||
Array.isArray(parsed)) {
throw new InvalidArgumentError(argName, correlationId);
}
}
catch (e) {
if (e instanceof SyntaxError) {
throw new InvalidArgumentError(argName, correlationId);
}
throw e; // Rethrow unexpected errors
}
}
/* eslint-disable header/header */
const name = "@azure/msal-browser";
const version = "5.25.0";
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const GrantType = {
PASSWORD: "password",
OOB: "oob",
CONTINUATION_TOKEN: "continuation_token",
REDIRECT: "redirect",
ATTRIBUTES: "attributes",
MFA_OOB: "mfa_oob",
};
const ChallengeType = {
PASSWORD: "password",
OOB: "oob",
REDIRECT: "redirect",
PREVERIFIED: "preverified",
};
const DefaultScopes = [
OPENID_SCOPE,
PROFILE_SCOPE,
OFFLINE_ACCESS_SCOPE,
];
const HttpHeaderKeys = {
CONTENT_TYPE: "Content-Type",
X_MS_REQUEST_ID: "x-ms-request-id",
};
const CustomHeaderConstants = {
REQUIRED_PREFIX: "x-",
RESERVED_PREFIXES: [
"x-client-",
"x-ms-",
"x-broker-",
"x-app-",
],
};
const DefaultPackageInfo = {
SKU: "msal.browser",
VERSION: version,
OS: "",
CPU: "",
};
const ResetPasswordPollStatus = {
IN_PROGRESS: "in_progress",
SUCCEEDED: "succeeded",
FAILED: "failed",
NOT_STARTED: "not_started",
};
const DefaultCustomAuthApiCodeLength = -1; // Default value indicating that the code length is not specified
const DefaultCustomAuthApiCodeResendIntervalInSec = 300; // seconds
const PasswordResetPollingTimeoutInMs = 300000; // milliseconds
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Base class for the state of an authentication flow.
*/
class AuthFlowStateBase {
}
/**
* Base class for the action requried state in an authentication flow.
*/
class AuthFlowActionRequiredStateBase extends AuthFlowStateBase {
/**
* Creates a new instance of AuthFlowActionRequiredStateBase.
* @param stateParameters The parameters for the auth state.
*/
constructor(stateParameters) {
ensureArgumentIsNotEmptyString("correlationId", stateParameters.correlationId);
super();
this.stateParameters = stateParameters;
}
ensureCodeIsValid(code, codeLength) {
if (codeLength !== DefaultCustomAuthApiCodeLength &&
(!code || code.length !== codeLength)) {
this.stateParameters.logger.error("0jr92e", this.stateParameters.correlationId);
throw new InvalidArgumentError("code", this.stateParameters.correlationId);
}
}
ensurePasswordIsNotEmpty(password) {
if (!password) {
this.stateParameters.logger.error("140ijv", this.stateParameters.correlationId);
throw new InvalidArgumentError("password", this.stateParameters.correlationId);
}
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
// Sign in state types
const SIGN_IN_CODE_REQUIRED_STATE_TYPE = "SignInCodeRequiredState";
const SIGN_IN_PASSWORD_REQUIRED_STATE_TYPE = "SignInPasswordRequiredState";
const SIGN_IN_CONTINUATION_STATE_TYPE = "SignInContinuationState";
const SIGN_IN_COMPLETED_STATE_TYPE = "SignInCompletedState";
const SIGN_IN_FAILED_STATE_TYPE = "SignInFailedState";
// Sign up state types
const SIGN_UP_CODE_REQUIRED_STATE_TYPE = "SignUpCodeRequiredState";
const SIGN_UP_PASSWORD_REQUIRED_STATE_TYPE = "SignUpPasswordRequiredState";
const SIGN_UP_ATTRIBUTES_REQUIRED_STATE_TYPE = "SignUpAttributesRequiredState";
const SIGN_UP_COMPLETED_STATE_TYPE = "SignUpCompletedState";
const SIGN_UP_FAILED_STATE_TYPE = "SignUpFailedState";
// Reset password state types
const RESET_PASSWORD_CODE_REQUIRED_STATE_TYPE = "ResetPasswordCodeRequiredState";
const RESET_PASSWORD_PASSWORD_REQUIRED_STATE_TYPE = "ResetPasswordPasswordRequiredState";
const RESET_PASSWORD_COMPLETED_STATE_TYPE = "ResetPasswordCompletedState";
const RESET_PASSWORD_FAILED_STATE_TYPE = "ResetPasswordFailedState";
// Get account state types
const GET_ACCOUNT_COMPLETED_STATE_TYPE = "GetAccountCompletedState";
const GET_ACCOUNT_FAILED_STATE_TYPE = "GetAccountFailedState";
// Get access token state types
const GET_ACCESS_TOKEN_COMPLETED_STATE_TYPE = "GetAccessTokenCompletedState";
const GET_ACCESS_TOKEN_FAILED_STATE_TYPE = "GetAccessTokenFailedState";
// Sign out state types
const SIGN_OUT_COMPLETED_STATE_TYPE = "SignOutCompletedState";
const SIGN_OUT_FAILED_STATE_TYPE = "SignOutFailedState";
// MFA state types
const MFA_AWAITING_STATE_TYPE = "MfaAwaitingState";
const MFA_VERIFICATION_REQUIRED_STATE_TYPE = "MfaVerificationRequiredState";
const MFA_COMPLETED_STATE_TYPE = "MfaCompletedState";
const MFA_FAILED_STATE_TYPE = "MfaFailedState";
// Auth method registration (JIT) state types
const AUTH_METHOD_REGISTRATION_REQUIRED_STATE_TYPE = "AuthMethodRegistrationRequiredState";
const AUTH_METHOD_VERIFICATION_REQUIRED_STATE_TYPE = "AuthMethodVerificationRequiredState";
const AUTH_METHOD_REGISTRATION_COMPLETED_STATE_TYPE = "AuthMethodRegistrationCompletedState";
const AUTH_METHOD_REGISTRATION_FAILED_STATE_TYPE = "AuthMethodRegistrationFailedState";
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* The completed state of the get account flow.
*/
class GetAccountCompletedState extends AuthFlowStateBase {
constructor() {
super(...arguments);
/**
* The type of the state.
*/
this.stateType = GET_ACCOUNT_COMPLETED_STATE_TYPE;
}
}
/**
* The failed state of the get account flow.
*/
class GetAccountFailedState extends AuthFlowStateBase {
constructor() {
super(...arguments);
/**
* The type of the state.
*/
this.stateType = GET_ACCOUNT_FAILED_STATE_TYPE;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Result of getting an account.
*/
class GetAccountResult extends AuthFlowResultBase {
/**
* Creates a new instance of GetAccountResult.
* @param resultData The result data.
*/
constructor(resultData) {
super(new GetAccountCompletedState(), resultData);
}
/**
* Creates a new instance of GetAccountResult with an error.
* @param error The error data.
*/
static createWithError(error) {
const result = new GetAccountResult();
result.error = new GetAccountError(GetAccountResult.createErrorData(error));
result.state = new GetAccountFailedState();
return result;
}
/**
* Checks if the result is in a completed state.
*/
isCompleted() {
return this.state.stateType === GET_ACCOUNT_COMPLETED_STATE_TYPE;
}
/**
* Checks if the result is in a failed state.
*/
isFailed() {
return this.state.stateType === GET_ACCOUNT_FAILED_STATE_TYPE;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class SignInError extends AuthActionErrorBase {
/**
* Checks if the error is due to the user not being found.
* @returns true if the error is due to the user not being found, false otherwise.
*/
isUserNotFound() {
return this.errorData.error === USER_NOT_FOUND;
}
/**
* Checks if the error is due to the username being invalid.
* @returns true if the error is due to the username being invalid, false otherwise.
*/
isInvalidUsername() {
return this.isUserInvalidError();
}
/**
* Checks if the error is due to the provided password being incorrect.
* @returns true if the error is due to the provided password being incorrect, false otherwise.
*/
isPasswordIncorrect() {
return this.isPasswordIncorrectError();
}
/**
* Checks if the error is due to password reset being required.
* @returns true if the error is due to password reset being required, false otherwise.
*/
isPasswordResetRequired() {
return this.isPasswordResetRequiredError();
}
/**
* Checks if the error is due to the provided challenge type is not supported.
* @returns {boolean} True if the error is due to the provided challenge type is not supported, false otherwise.
*/
isUnsupportedChallengeType() {
return this.isUnsupportedChallengeTypeError();
}
}
class SignInSubmitPasswordError extends AuthActionErrorBase {
/**
* Checks if the password submitted during sign-in is incorrect.
* @returns {boolean} True if the error is due to the password being invalid, false otherwise.
*/
isInvalidPassword() {
return this.isPasswordIncorrectError();
}
}
class SignInSubmitCodeError extends AuthActionErrorBase {
/**
* Checks if the code submitted during sign-in is invalid.
* @returns {boolean} True if the error is due to the code being invalid, false otherwise.
*/
isInvalidCode() {
return this.isInvalidCodeError();
}
}
class SignInResendCodeError extends AuthActionErrorBase {
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Represents the state of a sign-in operation that has been failed.
*/
class SignInFailedState extends AuthFlowStateBase {
constructor() {
super(...arguments);
/**
* The type of the state.
*/
this.stateType = SIGN_IN_FAILED_STATE_TYPE;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Result of a sign-in operation.
*/
class SignInResult extends AuthFlowResultBase {
/**
* Creates a new instance of SignInResultState.
* @param state The state of the result.
*/
constructor(state, resultData) {
super(state, resultData);
}
/**
* Creates a new instance of SignInResult with an error.
* @param error The error that occurred.
* @returns {SignInResult} A new instance of SignInResult with the error set.
*/
static createWithError(error) {
const result = new SignInResult(new SignInFailedState());
result.error = new SignInError(SignInResult.createErrorData(error));
return result;
}
/**
* Checks if the result is in a failed state.
*/
isFailed() {
return this.state.stateType === SIGN_IN_FAILED_STATE_TYPE;
}
/**
* Checks if the result is in a code required state.
*/
isCodeRequired() {
return this.state.stateType === SIGN_IN_CODE_REQUIRED_STATE_TYPE;
}
/**
* Checks if the result is in a password required state.
*/
isPasswordRequired() {
return this.state.stateType === SIGN_IN_PASSWORD_REQUIRED_STATE_TYPE;
}
/**
* Checks if the result is in a completed state.
*/
isCompleted() {
return this.state.stateType === SIGN_IN_COMPLETED_STATE_TYPE;
}
/**
* Checks if the result requires authentication method registration.
* @warning This API is experimental. It may be changed in the future without notice. Do not use in production applications.
*/
isAuthMethodRegistrationRequired() {
return (this.state.stateType ===
AUTH_METHOD_REGISTRATION_REQUIRED_STATE_TYPE);
}
/**
* Checks if the result requires MFA.
* @warning This API is experimental. It may be changed in the future without notice. Do not use in production applications.
*/
isMfaRequired() {
return this.state.stateType === MFA_AWAITING_STATE_TYPE;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class SignUpError extends AuthActionErrorBase {
/**
* Checks if the error is due to the user already exists.
* @returns {boolean} True if the error is due to the user already exists, false otherwise.
*/
isUserAlreadyExists() {
return this.isUserAlreadyExistsError();
}
/**
* Checks if the error is due to the username is invalid.
* @returns {boolean} True if the error is due to the user is invalid, false otherwise.
*/
isInvalidUsername() {
return this.isUserInvalidError();
}
/**
* Checks if the error is due to the password being invalid or incorrect.
* @returns {boolean} True if the error is due to the password being invalid, false otherwise.
*/
isInvalidPassword() {
return this.isInvalidNewPasswordError();
}
/**
* Checks if the error is due to the required attributes are missing.
* @returns {boolean} True if the error is due to the required attributes are missing, false otherwise.
*/
isMissingRequiredAttributes() {
return this.isAttributeRequiredError();
}
/**
* Checks if the error is due to the attributes validation failed.
* @returns {boolean} True if the error is due to the attributes validation failed, false otherwise.
*/
isAttributesValidationFailed() {
return this.isAttributeValidationFailedError();
}
/**
* Checks if the error is due to the provided challenge type is not supported.
* @returns {boolean} True if the error is due to the provided challenge type is not supported, false otherwise.
*/
isUnsupportedChallengeType() {
return this.isUnsupportedChallengeTypeError();
}
}
class SignUpSubmitPasswordError extends AuthActionErrorBase {
/**
* Checks if the error is due to the password being invalid or incorrect.
* @returns {boolean} True if the error is due to the password being invalid, false otherwise.
*/
isInvalidPassword() {
return (this.isPasswordIncorrectError() || this.isInvalidNewPasswordError());
}
}
class SignUpSubmitCodeError extends AuthActionErrorBase {
/**
* Checks if the provided code is invalid.
* @returns {boolean} True if the provided code is invalid, false otherwise.
*/
isInvalidCode() {
return this.isInvalidCodeError();
}
}
class SignUpSubmitAttributesError extends AuthActionErrorBase {
/**
* Checks if the error is due to the required attributes are missing.
* @returns {boolean} True if the error is due to the required attributes are missing, false otherwise.
*/
isMissingRequiredAttributes() {
return this.isAttributeRequiredError();
}
/**
* Checks if the error is due to the attributes validation failed.
* @returns {boolean} True if the error is due to the attributes validation failed, false otherwise.
*/
isAttributesValidationFailed() {
return this.isAttributeValidationFailedError();
}
}
class SignUpResendCodeError extends AuthActionErrorBase {
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Represents the state of a sign-up operation that has failed.
*/
class SignUpFailedState extends AuthFlowStateBase {
constructor() {
super(...arguments);
/**
* The type of the state.
*/
this.stateType = SIGN_UP_FAILED_STATE_TYPE;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Result of a sign-up operation.
*/
class SignUpResult extends AuthFlowResultBase {
/**
* Creates a new instance of SignUpResult.
* @param state The state of the result.
*/
constructor(state) {
super(state);
}
/**
* Creates a new instance of SignUpResult with an error.
* @param error The error that occurred.
* @returns {SignUpResult} A new instance of SignUpResult with the error set.
*/
static createWithError(error) {
const result = new SignUpResult(new SignUpFailedState());
result.error = new SignUpError(SignUpResult.createErrorData(error));
return result;
}
/**
* Checks if the result is in a failed state.
*/
isFailed() {
return this.state.stateType === SIGN_UP_FAILED_STATE_TYPE;
}
/**
* Checks if the result is in a code required state.
*/
isCodeRequired() {
return this.state.stateType === SIGN_UP_CODE_REQUIRED_STATE_TYPE;
}
/**
* Checks if the result is in a password required state.
*/
isPasswordRequired() {
return this.state.stateType === SIGN_UP_PASSWORD_REQUIRED_STATE_TYPE;
}
/**
* Checks if the result is in an attributes required state.
*/
isAttributesRequired() {
return this.state.stateType === SIGN_UP_ATTRIBUTES_REQUIRED_STATE_TYPE;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class MethodNotImplementedError extends CustomAuthError {
constructor(method, correlationId) {
const errorDescription = `The method '${method}' is not implemented, please do not use.`;
super("method_not_implemented", errorDescription, correlationId);
Object.setPrototypeOf(this, MethodNotImplementedError.prototype);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* acquireTokenFromCache (msal-browser).
* Internal API for acquiring token from cache
*/
const AcquireTokenFromCache = "acquireTokenFromCache";
/**
* acquireTokenByRefreshToken API (msal-browser and msal-node).
* Used to renew an access token using a refresh token against the token endpoint.
*/
const AcquireTokenByRefreshToken = "acquireTokenByRefreshToken";
/**
* acquireTokenSilentAsync (msal-browser).
* Internal API for acquireTokenSilent.
*/
const AcquireTokenSilentAsync = "acquireTokenSilentAsync";
/**
* provisionTokenBindingKey API in TokenBindingKeyManager class (msal-browser).
* Used to provision token-binding key material and return a key identifier.
*/
const CryptoOptsGetPublicKeyThumbprint = "cryptoOptsGetPublicKeyThumbprint";
/**
* signTokenBindingJwt API in CryptoOpts class (msal-browser).
* Used to sign token-binding JWTs.
*/
const CryptoOptsSignJwt = "cryptoOptsSignJwt";
/**
* acquireToken API in the SilentCacheClient class (msal-browser).
* Used to read access tokens from the cache.
*/
const SilentCacheClientAcquireToken = "silentCacheClientAcquireToken";
/**
* acquireToken API in the SilentIframeClient class (msal-browser).
* Used to acquire a new set of tokens from the authorize endpoint in a hidden iframe.
*/
const SilentIframeClientAcquireToken = "silentIframeClientAcquireToken";
const AwaitConcurrentIframe = "awaitConcurrentIframe"; // Time spent waiting for a concurrent iframe to complete
/**
* acquireToken API in SilentRereshClient (msal-browser).
* Used to acquire a new set of tokens from the token endpoint using a refresh token.
*/
const SilentRefreshClientAcquireToken = "silentRefreshClientAcquireToken";
/**
* getDiscoveredAuthority API in StandardInteractionClient class (msal-browser).
* Used to load authority metadata for a request.
*/
const StandardInteractionClientGetDiscoveredAuthority = "standardInteractionClientGetDiscoveredAuthority";
/**
* acquireToken API in NativeInteractionClient class (msal-browser).
* Used to acquire a token from Native component when native brokering is enabled.
*/
const NativeInteractionClientAcquireToken = "nativeInteractionClientAcquireToken";
const NativeInteractionClientAcquireTokenRedirect = "nativeInteractionClientAcquireToken";
/**
* acquireTokenByRefreshToken API in RefreshTokenClient (msal-common).
*/
const RefreshTokenClientAcquireTokenByRefreshToken = "refreshTokenClientAcquireTokenByRefreshToken";
/**
* acquireTokenBySilentIframe (msal-browser).
* Internal API for acquiring token by silent Iframe
*/
const AcquireTokenBySilentIframe = "acquireTokenBySilentIframe";
/**
* Internal API for initializing base request in BaseInteractionClient (msal-browser)
*/
const InitializeBaseRequest = "initializeBaseRequest";
/**
* Internal API for initializing silent request in SilentCacheClient (msal-browser)
*/
const InitializeSilentRequest = "initializeSilentRequest";
const InitializeCache = "initializeCache";
/**
* Helper function in SilentIframeClient class (msal-browser).
*/
const SilentIframeClientTokenHelper = "silentIframeClientTokenHelper";
/**
* SilentHandler
*/
const SilentHandlerInitiateAuthRequest = "silentHandlerInitiateAuthRequest";
const SilentHandlerMonitorIframeForHash = "silentHandlerMonitorIframeForHash";
/**
* Helper functions in StandardInteractionClient class (msal-browser)
*/
const StandardInteractionClientCreateAuthCodeClient = "standardInteractionClientCreateAuthCodeClient";
const StandardInteractionClientGetClientConfiguration = "standardInteractionClientGetClientConfiguration";
const StandardInteractionClientInitializeAuthorizationRequest = "standardInteractionClientInitializeAuthorizationRequest";
const SilentFlowClientAcquireCachedToken = "silentFlowClientAcquireCachedToken";
const GetStandardParams = "getStandardParams";
const HandleCodeResponse = "handleCodeResponse";
const HandleResponseEar = "handleResponseEar";
const HandleResponsePlatformBroker = "handleResponsePlatformBroker";
const HandleResponseCode = "handleResponseCode";
const AuthClientAcquireToken = "authClientAcquireToken";
const DeserializeResponse = "deserializeResponse";
const AuthorityFactoryCreateDiscoveredInstance = "authorityFactoryCreateDiscoveredInstance";
const AcquireTokenByCodeAsync = "acquireTokenByCodeAsync";
const HandleRedirectPromiseMeasurement = "handleRedirectPromise";
const HandleNativeRedirectPromiseMeasurement = "handleNativeRedirectPromise";
const NativeMessageHandlerHandshake = "nativeMessageHandlerHandshake";
const NativeGenerateAuthResult = "nativeGenerateAuthResult";
const PlatformAuthProviderDiscovery = "platformAuthProviderDiscovery";
const PlatformAuthDOMCreateProvider = "platformAuthDOMCreateProvider";
const PlatformAuthDOMGetSupportedContracts = "platformAuthDOMGetSupportedContracts";
const PlatformAuthDOMInitializeRequest = "platformAuthDOMInitializeRequest";
const PlatformAuthDOMGetToken = "platformAuthDOMGetToken";
const PlatformAuthDOMValidateResponse = "platformAuthDOMValidateResponse";
const PlatformAuthExtensionCreateProvider = "platformAuthExtensionCreateProvider";
const PlatformAuthExtensionGetToken = "platformAuthExtensionGetToken";
const PlatformAuthExtensionValidateResponse = "platformAuthExtensionValidateResponse";
const PlatformAuthInteractionClientInitializeRequest = "platformAuthInteractionClientInitializeRequest";
const PlatformAuthHandleNativeResponse = "platformAuthHandleNativeResponse";
const PlatformAuthCacheAccount = "platformAuthCacheAccount";
const PlatformAuthCacheNativeTokens = "platformAuthCacheNativeTokens";
const RemoveHiddenIframe = "removeHiddenIframe";
const ImportExistingCache = "importExistingCache";
/**
* Crypto Operations
*/
const GeneratePkceCodes = "generatePkceCodes";
const GenerateCodeVerifier = "generateCodeVerifier";
const GenerateCodeChallengeFromVerifier = "generateCodeChallengeFromVerifier";
const Sha256Digest = "sha256Digest";
const GetRandomValues = "getRandomValues";
const GenerateHKDF = "generateHKDF";
const GenerateBaseKey = "generateBaseKey";
const Base64Decode = "base64Decode";
const UrlEncodeArr = "urlEncodeArr";
const Encrypt = "encrypt";
const Decrypt = "decrypt";
const GenerateEarKey = "generateEarKey";
const DecryptEarResponse = "decryptEarResponse";
/**
* Background telemetry measurement that tracks whether a late bridge response
* arrives after the iframe timeout has already fired.
*/
const WaitForBridgeLateResponse = "waitForBridgeLateResponse";
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const pkceNotCreated = "pkce_not_created";
const earJwkEmpty = "ear_jwk_empty";
const earJweEmpty = "ear_jwe_empty";
const cryptoNonExistent = "crypto_nonexistent";
const emptyNavigateUri = "empty_navigate_uri";
const hashEmptyError = "hash_empty_error";
const noStateInHash = "no_state_in_hash";
const hashDoesNotContainKnownProperties = "hash_does_not_contain_known_properties";
const unableToParseState = "unable_to_parse_state";
const stateInteractionTypeMismatch = "state_interaction_type_mismatch";
const interactionInProgress = "interaction_in_progress";
const interactionInProgressCancelled = "interaction_in_progress_cancelled";
const popupWindowError = "popup_window_error";
const emptyWindowError = "empty_window_error";
const userCancelled = "user_cancelled";
const redirectBridgeEmptyResponse = "redirect_bridge_empty_response";
const redirectInIframe = "redirect_in_iframe";
const blockIframeReload = "block_iframe_reload";
const blockNestedPopups = "block_nested_popups";
const popupRelayUnsupportedFlow = "popup_relay_unsupported_flow";
const silentLogoutUnsupported = "silent_logout_unsupported";
const noAccountError = "no_account_error";
const noTokenRequestCacheError = "no_token_request_cache_error";
const unableToParseTokenRequestCacheError = "unable_to_parse_token_request_cache_error";
const nonBrowserEnvironment = "non_browser_environment";
const databaseNotOpen = "database_not_open";
const noNetworkConnectivity = "no_network_connectivity";
const postRequestFailed = "post_request_failed";
const getRequestFailed = "get_request_failed";
const failedToParseResponse = "failed_to_parse_response";
const cryptoKeyNotFound = "crypto_key_not_found";
const invalidPublicJwk = "invalid_public_jwk";
const authCodeRequired = "auth_code_required";
const authCodeOrNativeAccountIdRequired = "auth_code_or_nativeAccountId_required";
const spaCodeAndNativeAccountIdPresent = "spa_code_and_nativeAccountId_present";
const databaseUnavailable = "database_unavailable";
const unableToAcquireTokenFromNativePlatform = "unable_to_acquire_token_from_native_platform";
const nativeHandshakeTimeout = "native_handshake_timeout";
const nativeExtensionNotInstalled = "native_extension_not_installed";
const nativeConnectionNotEstablished = "native_connection_not_established";
const uninitializedPublicClientApplication = "uninitialized_public_client_application";
const nativePromptNotSupported = "native_prompt_not_supported";
const invalidBase64String = "invalid_base64_string";
const invalidPopTokenRequest = "invalid_pop_token_request";
const unsupportedTokenBindingAlgorithm = "unsupported_token_binding_algorithm";
const tokenBindingKeyAlgorithmMismatch = "token_binding_key_algorithm_mismatch";
const tokenBindingKeyJwkThumbprintMismatch = "token_binding_key_jwk_thumbprint_mismatch";
const failedToBuildHeaders = "failed_to_build_headers";
const failedToParseHeaders = "failed_to_parse_headers";
const failedToDecryptEarResponse = "failed_to_decrypt_ear_response";
const timedOut = "timed_out";
const emptyResponse = "empty_response";
/*
* 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`;
}
/**
* Browser library error class thrown by the MSAL.js library for SPAs
*/
class BrowserAuthError extends AuthError {
constructor(errorCode, correlationId, subError) {
super(errorCode, correlationId, getDefaultErrorMessage(errorCode), subError);
Object.setPrototypeOf(this, BrowserAuthError.prototype);
this.name = "BrowserAuthError";
}
}
function createBrowserAuthError(errorCode, correlationId, subError) {
return new BrowserAuthError(errorCode, correlationId, subError);
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Class which exposes APIs to decode base64 strings to plaintext. See here for implementation details:
* https://developer.mozilla.org/en-US/docs/Glossary/Base64#the_unicode_problem
*/
/**
* Returns a URL-safe plaintext decoded string from b64 encoded input.
* @param input
*/
function base64Decode(input) {
return new TextDecoder().decode(base64DecToArr(input));
}
/**
* Decodes base64 into Uint8Array
* @param base64String
*/
function base64DecToArr(base64String) {
let encodedString = base64String.replace(/-/g, "+").replace(/_/g, "/");
switch (encodedString.length % 4) {
case 0:
break;
case 2:
encodedString += "==";
break;
case 3:
encodedString += "=";
break;
default:
throw createBrowserAuthError(invalidBase64String, "");
}
const binString = atob(encodedString);
return Uint8Array.from(binString, (m) => m.codePointAt(0) || 0);
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Constants
*/
const BrowserConstants = {
/**
* Invalid grant error code
*/
INVALID_GRANT_ERROR: "invalid_grant",
/**
* Default popup window width
*/
POPUP_WIDTH: 483,
/**
* Default popup window height
*/
POPUP_HEIGHT: 600,
/**
* Name of the popup window starts with
*/
POPUP_NAME_PREFIX: "msal",
/**
* Msal-browser SKU
*/
MSAL_SKU: "msal.js.browser",
};
const PlatformAuthConstants = {
CHANNEL_ID: "53ee284d-920a-4b59-9d30-a60315b26836",
PREFERRED_EXTENSION_ID: "ppnbnpeolgkicgegkbkbjmhlideopiji",
MATS_TELEMETRY: "MATS",
MICROSOFT_ENTRA_BROKERID: "MicrosoftEntra",
DOM_API_NAME: "DOM API",
PLATFORM_DOM_APIS: "get-token-and-sign-out",
PLATFORM_DOM_PROVIDER: "PlatformAuthDOMHandler",
PLATFORM_EXTENSION_PROVIDER: "PlatformAuthExtensionHandler",
};
const NativeExtensionMethod = {
HandshakeRequest: "Handshake",
HandshakeResponse: "HandshakeResponse",
GetToken: "GetToken",
Response: "Response",
};
const BrowserCacheLocation = {
LocalStorage: "localStorage",
SessionStorage: "sessionStorage",
MemoryStorage: "memoryStorage",
};
/**
* HTTP Request types supported by MSAL.
*/
const HTTP_REQUEST_TYPE = {
GET: "GET",
POST: "POST",
};
const INTERACTION_TYPE = {
SIGNIN: "signin",
SIGNOUT: "signout",
};
/**
* Temporary cache keys for MSAL, deleted after any request.
*/
const TemporaryCacheKeys = {
ORIGIN_URI: "request.origin",
URL_HASH: "urlHash",
REQUEST_PARAMS: "request.params",
VERIFIER: "code.verifier",
INTERACTION_STATUS_KEY: "interaction.status",
NATIVE_REQUEST: "request.native",
};
/**
* Cache keys stored in-memory
*/
const InMemoryCacheKeys = {
WRAPPER_SKU: "wrapper.sku",
WRAPPER_VER: "wrapper.version",
};
/**
* API Codes for Telemetry purposes.
* Before adding a new code you must claim it in the MSAL Telemetry tracker as these number spaces are shared across all MSALs
* 0-99 Silent Flow
* 800-899 Auth Code Flow
* 900-999 Misc
*/
const ApiId = {
acquireTokenRedirect: 861,
acquireTokenPopup: 862,
ssoSilent: 863,
acquireTokenSilent_authCode: 864,
handleRedirectPromise: 865,
acquireTokenByCode: 866,
acquireTokenSilent_silentFlow: 61,
logout: 961,
logoutPopup: 962,
hydrateCache: 963,
loadExternalTokens: 964,
};
/**
* API Names for Telemetry purposes.
*/
const ApiName = {
861: "acquireTokenRedirect",
862: "acquireTokenPopup",
863: "ssoSilent",
864: "acquireTokenSilent_authCode",
865: "handleRedirectPromise",
866: "acquireTokenByCode",
61: "acquireTokenSilent_silentFlow",
961: "logout",
962: "logoutPopup",
963: "hydrateCache",
964: "loadExternalTokens",
};
const apiIdToName = (id) => {
if (typeof id === "number" && id in ApiName) {
return ApiName[id];
}
return "unknown";
};
/*
* Interaction type of the API - used for state and telemetry
*/
var InteractionType;
(function (InteractionType) {
InteractionType["Redirect"] = "redirect";
InteractionType["Popup"] = "popup";
InteractionType["Silent"] = "silent";
InteractionType["None"] = "none";
})(InteractionType || (InteractionType = {}));
const DEFAULT_REQUEST = {
scopes: OIDC_DEFAULT_SCOPES,
};
/**
* JWK Key Format string (Type MUST be defined for window crypto APIs)
*/
const KEY_FORMAT_JWK = "jwk";
// DatabaseStorage Constants
const DB_NAME = "msal.db";
const DB_VERSION = 1;
const DB_TABLE_NAME = `${DB_NAME}.keys`;
const CacheLookupPolicy = {
/*
* acquireTokenSilent will attempt to retrieve an access token from the cache. If the access token is expired
* or cannot be found the refresh token will be used to acquire a new one. Finally, if the refresh token
* is expired acquireTokenSilent will attempt to acquire new access and refresh tokens.
*/
Default: 0,
/*
* acquireTokenSilent will only look for access tokens in the cache. It will not attempt to renew access or
* refresh tokens.
*/
AccessToken: 1,
/*
* acquireTokenSilent will attempt to retrieve an access token from the cache. If the access token is expired or
* cannot be found, the refresh token will be used to acquire a new one. If the refresh token is expired, it
* will not be renewed and acquireTokenSilent will fail.
*/
AccessTokenAndRefreshToken: 2,
/*
* acquireTokenSilent will not attempt to retrieve access tokens from the cache and will instead attempt to
* exchange the cached refresh token for a new access token. If the refresh token is expired, it will not be
* renewed and acquireTokenSilent will fail.
*/
RefreshToken: 3,
/*
* acquireTokenSilent will not look in the cache for the access token. It will go directly to network with the
* cached refresh token. If the refresh token is expired an attempt will be made to renew it. This is equivalent to
* setting "forceRefresh: true".
*/
RefreshTokenAndNetwork: 4,
/*
* acquireTokenSilent will attempt to renew both access and refresh tokens. It will not look in the cache. This will
* always fail if 3rd party cookies are blocked by the browser.
*/
Skip: 5,
};
const iFrameRenewalPolicies = [
CacheLookupPolicy.Default,
CacheLookupPolicy.Skip,
CacheLookupPolicy.RefreshTokenAndNetwork,
];
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Class which exposes APIs to encode plaintext to base64 encoded string. See here for implementation details:
* https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#Solution_2_%E2%80%93_JavaScript's_UTF-16_%3E_UTF-8_%3E_base64
*/
/**
* Returns URL Safe b64 encoded string from a plaintext string.
* @param input
*/
function urlEncode(input) {
return encodeURIComponent(base64Encode(input)
.replace(/=/g, "")
.replace(/\+/g, "-")
.replace(/\//g, "_"));
}
/**
* Returns URL Safe b64 encoded string from an int8Array.
* @param inputArr
*/
function urlEncodeArr(inputArr) {
return base64EncArr(inputArr)
.replace(/=/g, "")
.replace(/\+/g, "-")
.replace(/\//g, "_");
}
/**
* Returns b64 encoded string from plaintext string.
* @param input
*/
function base64Encode(input) {
return base64EncArr(new TextEncoder().encode(input));
}
/**
* Base64 encode byte array
* @param aBytes
*/
function base64EncArr(aBytes) {
const binString = Array.from(aBytes, (x) => String.fromCodePoint(x)).join("");
return btoa(binString);
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* This file defines functions used by the browser library to perform cryptography operations such as
* hashing and encoding. It also has helper functions to validate the availability of specific APIs.
*/
/**
* See here for more info on RsaHashedKeyGenParams: https://developer.mozilla.org/en-US/docs/Web/API/RsaHashedKeyGenParams
*/
// Algorithms
const PKCS1_V15_KEYGEN_ALG = "RSASSA-PKCS1-v1_5";
const AES_GCM = "AES-GCM";
const HKDF = "HKDF";
// SHA-256 hashing algorithm
const S256_HASH_ALG = "SHA-256";
// JWK values used by browser-internal WebCrypto helpers.
const JSON_WEB_KEY_CURVE_P256 = "P-256";
const JSON_WEB_KEY_TYPE_EC = "EC";
const JSON_WEB_KEY_TYPE_RSA = "RSA";
const MISSING_JWK_KTY_SUBERROR = "missing_jwk_kty";
const UNSUPPORTED_JWK_KTY_SUBERROR = "unsupported_jwk_kty";
const MISSING_JWK_MEMBER_SUBERROR = "missing_jwk_member";
const EMPTY_JWK_MEMBER_SUBERROR = "empty_jwk_member";
// MOD length for PoP tokens
const MODULUS_LENGTH = 2048;
// Public Exponent
const PUBLIC_EXPONENT = new Uint8Array([0x01, 0x00, 0x01]);
// UUID hex digits
const UUID_CHARS = "0123456789abcdef";
// Array to store UINT32 random value
const UINT32_ARR = new Uint32Array(1);
// Key Format
const RAW = "raw";
// Key Usages
const ENCRYPT = "encrypt";
const DECRYPT = "decrypt";
const DERIVE_KEY = "deriveKey";
// Suberror
const SUBTLE_SUBERROR = "crypto_subtle_undefined";
const RSA_KEYGEN_ALGORITHM_OPTIONS = {
name: PKCS1_V15_KEYGEN_ALG,
hash: S256_HASH_ALG,
modulusLength: MODULUS_LENGTH,
publicExponent: PUBLIC_EXPONENT,
};
const RSA_SIGN_ALGORITHM_OPTIONS = {
name: PKCS1_V15_KEYGEN_ALG,
};
const ECDSA_P256_KEYGEN_ALGORITHM_OPTIONS = {
name: "ECDSA",
namedCurve: JSON_WEB_KEY_CURVE_P256,
};
const ECDSA_SHA256_SIGN_ALGORITHM_OPTIONS = {
name: "ECDSA",
hash: { name: S256_HASH_ALG },
};
/**
* Check whether browser crypto is available.
*/
function validateCryptoAvailable(skipValidateSubtleCrypto) {
if (!window) {
throw createBrowserAuthError(nonBrowserEnvironment, "");
}
if (!window.crypto) {
throw createBrowserAuthError(cryptoNonExistent, "");
}
if (!skipValidateSubtleCrypto && !window.crypto.subtle) {
throw createBrowserAuthError(cryptoNonExistent, "", SUBTLE_SUBERROR);
}
}
/**
* Returns a sha-256 hash of the given dataString as an ArrayBuffer.
* @param dataString {string} data string
* @param performanceClient {?IPerformanceClient}
* @param correlationId {?string} correlation id
*/
async function sha256Digest(dataString) {
const encoder = new TextEncoder();
const data = encoder.encode(dataString);
return window.crypto.subtle.digest(S256_HASH_ALG, data);
}
/**
* Populates buffer with cryptographically random values.
* @param dataBuffer
*/
function getRandomValues(dataBuffer) {
return window.crypto.getRandomValues(dataBuffer);
}
/**
* Returns random Uint32 value.
* @returns {number}
*/
function getRandomUint32() {
window.crypto.getRandomValues(UINT32_ARR);
return UINT32_ARR[0];
}
/**
* Creates a UUID v7 from the current timestamp.
* Implementation relies on the system clock to guarantee increasing order of generated identifiers.
* @returns {number}
*/
function createNewGuid() {
const currentTimestamp = Date.now();
const baseRand = getRandomUint32() * 0x400 + (getRandomUint32() & 0x3ff);
// Result byte array
const bytes = new Uint8Array(16);
// A 12-bit `rand_a` field value
const randA = Math.trunc(baseRand / 2 ** 30);
// The higher 30 bits of 62-bit `rand_b` field value
const randBHi = baseRand & (2 ** 30 - 1);
// The lower 32 bits of 62-bit `rand_b` field value
const randBLo = getRandomUint32();
bytes[0] = currentTimestamp / 2 ** 40;
bytes[1] = currentTimestamp / 2 ** 32;
bytes[2] = currentTimestamp / 2 ** 24;
bytes[3] = currentTimestamp / 2 ** 16;
bytes[4] = currentTimestamp / 2 ** 8;
bytes[5] = currentTimestamp;
bytes[6] = 0x70 | (randA >>> 8);
bytes[7] = randA;
bytes[8] = 0x80 | (randBHi >>> 24);
bytes[9] = randBHi >>> 16;
bytes[10] = randBHi >>> 8;
bytes[11] = randBHi;
bytes[12] = randBLo >>> 24;
bytes[13] = randBLo >>> 16;
bytes[14] = randBLo >>> 8;
bytes[15] = randBLo;
let text = "";
for (let i = 0; i < bytes.length; i++) {
text += UUID_CHARS.charAt(bytes[i] >>> 4);
text += UUID_CHARS.charAt(bytes[i] & 0xf);
if (i === 3 || i === 5 || i === 7 || i === 9) {
text += "-";
}
}
return text;
}
/**
* Generates a keypair based on the provided algorithm config.
* @param extractable
* @param usages
* @param algorithm
*/
async function generateKeyPair(extractable, usages, algorithm) {
return window.crypto.subtle.generateKey(algorithm, extractable, usages);
}
/**
* Export key as Json Web Key (JWK)
* @param key
*/
async function exportJwk(key) {
return window.crypto.subtle.exportKey(KEY_FORMAT_JWK, key);
}
/**
* Signs given data with given key.
* @param key
* @param data
* @param algorithm
*/
async function sign(key, data, algorithm) {
return window.crypto.subtle.sign(algorithm, key, data);
}
/**
* Generates Base64 encoded jwk used in the Encrypted Authorize Response (EAR) flow
*/
async function generateEarKey() {
const key = await generateBaseKey();
const keyStr = urlEncodeArr(new Uint8Array(key));
const jwk = {
alg: "dir",
kty: "oct",
k: keyStr,
};
return base64Encode(JSON.stringify(jwk));
}
/**
* Parses earJwk for encryption key and returns CryptoKey object
* @param earJwk
* @returns
*/
async function importEarKey(earJwk) {
const b64DecodedJwk = base64Decode(earJwk);
const jwkJson = JSON.parse(b64DecodedJwk);
const rawKey = jwkJson.k;
const keyBuffer = base64DecToArr(rawKey);
return window.crypto.subtle.importKey(RAW, keyBuffer, AES_GCM, false, [
DECRYPT,
]);
}
/**
* Decrypt ear_jwe response returned in the Encrypted Authorize Response (EAR) flow
* @param earJwk
* @param earJwe
* @returns
*/
async function decryptEarResponse(earJwk, earJwe) {
const earJweParts = earJwe.split(".");
if (earJweParts.length !== 5) {
throw createBrowserAuthError(failedToDecryptEarResponse, "", "jwe_length");
}
const key = await importEarKey(earJwk).catch(() => {
throw createBrowserAuthError(failedToDecryptEarResponse, "", "import_key");
});
try {
const header = new TextEncoder().encode(earJweParts[0]);
const iv = base64DecToArr(earJweParts[2]);
const ciphertext = base64DecToArr(earJweParts[3]);
const tag = base64DecToArr(earJweParts[4]);
const tagLengthBits = tag.byteLength * 8;
// Concat ciphertext and tag
const encryptedData = new Uint8Array(ciphertext.length + tag.length);
encryptedData.set(ciphertext);
encryptedData.set(tag, ciphertext.length);
const decryptedData = await window.crypto.subtle.decrypt({
name: AES_GCM,
iv: iv,
tagLength: tagLengthBits,
additionalData: header,
}, key, encryptedData);
return new TextDecoder().decode(decryptedData);
}
catch (e) {
throw createBrowserAuthError(failedToDecryptEarResponse, "", "decrypt");
}
}
/**
* Generates symmetric base encryption key. This may be stored as all encryption/decryption keys will be derived from this one.
*/
async function generateBaseKey() {
const key = await window.crypto.subtle.generateKey({
name: AES_GCM,
length: 256,
}, true, [ENCRYPT, DECRYPT]);
return window.crypto.subtle.exportKey(RAW, key);
}
/**
* Returns the raw key to be passed into the key derivation function
* @param baseKey
* @returns
*/
async function generateHKDF(baseKey) {
return window.crypto.subtle.importKey(RAW, baseKey, HKDF, false, [
DERIVE_KEY,
]);
}
/**
* Given a base key and a nonce generates a derived key to be used in encryption and decryption.
* Note: every time we encrypt a new key is derived
* @param baseKey
* @param nonce
* @returns
*/
async function deriveKey(baseKey, nonce, context) {
return window.crypto.subtle.deriveKey({
name: HKDF,
salt: nonce,
hash: S256_HASH_ALG,
info: new TextEncoder().encode(context),
}, baseKey, { name: AES_GCM, length: 256 }, false, [ENCRYPT, DECRYPT]);
}
/**
* Encrypt the given data given a base key. Returns encrypted data and a nonce that must be provided during decryption
* @param key
* @param rawData
*/
async function encrypt(baseKey, rawData, context) {
const encodedData = new TextEncoder().encode(rawData);
// The nonce must never be reused with a given key.
const nonce = window.crypto.getRandomValues(new Uint8Array(16));
const derivedKey = await deriveKey(baseKey, nonce, context);
const encryptedData = await window.crypto.subtle.encrypt({
name: AES_GCM,
iv: new Uint8Array(12), // New key is derived for every encrypt so we don't need a new nonce
}, derivedKey, encodedData);
return {
data: urlEncodeArr(new Uint8Array(encryptedData)),
nonce: urlEncodeArr(nonce),
};
}
/**
* Decrypt data with the given key and nonce
* @param key
* @param nonce
* @param encryptedData
* @returns
*/
async function decrypt(baseKey, nonce, context, encryptedData) {
const encodedData = base64DecToArr(encryptedData);
const derivedKey = await deriveKey(baseKey, base64DecToArr(nonce), context);
const decryptedData = await window.crypto.subtle.decrypt({
name: AES_GCM,
iv: new Uint8Array(12), // New key is derived for every encrypt so we don't need a new nonce
}, derivedKey, encodedData);
return new TextDecoder().decode(decryptedData);
}
/**
* Returns the SHA-256 hash of an input string
* @param plainText
*/
async function hashString(plainText) {
const hashBuffer = await sha256Digest(plainText);
const hashBytes = new Uint8Array(hashBuffer);
return urlEncodeArr(hashBytes);
}
const JWK_THUMBPRINT_REQUIRED_MEMBERS = {
[JSON_WEB_KEY_TYPE_EC]: ["crv", "kty", "x", "y"],
[JSON_WEB_KEY_TYPE_RSA]: ["e", "kty", "n"],
};
function getJwkThumbprintMembers(publicJwk, correlationId) {
const kty = publicJwk.kty;
if (typeof kty !== "string" || kty.length === 0) {
throw createBrowserAuthError(invalidPublicJwk, correlationId, MISSING_JWK_KTY_SUBERROR);
}
const requiredMembers = JWK_THUMBPRINT_REQUIRED_MEMBERS[kty];
if (!requiredMembers) {
throw createBrowserAuthError(invalidPublicJwk, correlationId, UNSUPPORTED_JWK_KTY_SUBERROR);
}
return requiredMembers.reduce((thumbprintMembers, memberName) => {
const memberValue = publicJwk[memberName];
if (typeof memberValue !== "string") {
throw createBrowserAuthError(invalidPublicJwk, correlationId, MISSING_JWK_MEMBER_SUBERROR);
}
if (memberValue.length === 0) {
throw createBrowserAuthError(invalidPublicJwk, correlationId, EMPTY_JWK_MEMBER_SUBERROR);
}
thumbprintMembers[memberName] = memberValue;
return thumbprintMembers;
}, {});
}
/**
* Computes an RFC 7638 JWK thumbprint for a public key.
* The required members for the JWK key type are serialised in lexicographic order
* and the SHA-256 digest is returned as a base64url string.
* @internal
*/
async function computeJwkThumbprint(publicJwk, correlationId) {
const thumbprintMembers = getJwkThumbprintMembers(publicJwk, correlationId);
// RFC 7638 §3.3: use only required members, sorted lexicographically
const thumbprintJson = JSON.stringify(thumbprintMembers, Object.keys(thumbprintMembers).sort());
return hashString(thumbprintJson);
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const storageNotSupported = "storage_not_supported";
const inMemRedirectUnavailable = "in_mem_redirect_unavailable";
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Browser library error class thrown by the MSAL.js library for SPAs
*/
class BrowserConfigurationAuthError extends AuthError {
constructor(errorCode, correlationId, errorMessage) {
super(errorCode, correlationId, errorMessage);
this.name = "BrowserConfigurationAuthError";
Object.setPrototypeOf(this, BrowserConfigurationAuthError.prototype);
}
}
function createBrowserConfigurationAuthError(errorCode, correlationId) {
return new BrowserConfigurationAuthError(errorCode, correlationId, getDefaultErrorMessage(errorCode));
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Extracts and parses the authentication response from URL (hash and/or query string).
* This is a shared utility used across multiple components in msal-browser.
*
* @returns {Object} An object containing the parsed state information and URL parameters.
* @returns {URLSearchParams} params - The parsed URL parameters from the payload.
* @returns {string} payload - The combined query string and hash content.
* @returns {string} urlHash - The original URL hash.
* @returns {string} urlQuery - The original URL query string.
* @returns {LibraryStateObject} libraryState - The decoded library state from the state parameter.
*
* @throws {AuthError} If no authentication payload is found in the URL.
* @throws {AuthError} If the state parameter is missing.
* @throws {AuthError} If the state is missing required 'id' or 'meta' attributes.
*/
function parseAuthResponseFromUrl() {
// Extract both hash and query string to support hybrid response format
const urlHash = window.location.hash;
const urlQuery = window.location.search;
// Determine which part contains the auth response by checking for 'state' parameter
let hasResponseInHash = false;
let hasResponseInQuery = false;
let payload = "";
let params = undefined;
if (urlHash && urlHash.length > 1) {
const hashContent = urlHash.charAt(0) === "#" ? urlHash.substring(1) : urlHash;
const hashParams = new URLSearchParams(hashContent);
if (hashParams.has("state")) {
hasResponseInHash = true;
payload = hashContent;
params = hashParams;
}
}
if (urlQuery && urlQuery.length > 1) {
const queryContent = urlQuery.charAt(0) === "?" ? urlQuery.substring(1) : urlQuery;
const queryParams = new URLSearchParams(queryContent);
if (queryParams.has("state")) {
hasResponseInQuery = true;
payload = queryContent;
params = queryParams;
}
}
// If response is in both, combine them (hybrid format)
if (hasResponseInHash && hasResponseInQuery) {
const queryContent = urlQuery.charAt(0) === "?" ? urlQuery.substring(1) : urlQuery;
const hashContent = urlHash.charAt(0) === "#" ? urlHash.substring(1) : urlHash;
payload = `${queryContent}${hashContent}`;
params = new URLSearchParams(payload);
}
/*
* Called by the redirect-bridge entry point before any request context exists,
* so correlationId is intentionally empty for the throws below.
*/
if (!payload || !params) {
throw createBrowserAuthError(emptyResponse, "");
}
const state = params.get("state");
if (!state) {
throw createBrowserAuthError(noStateInHash, "");
}
const { libraryState } = parseRequestState(base64Decode, state, "");
const { id, meta } = libraryState;
if (!id || !meta) {
throw createBrowserAuthError(unableToParseState, "", "missing_library_state");
}
return {
params,
payload,
urlHash,
urlQuery,
hasResponseInHash,
hasResponseInQuery,
libraryState: {
id,
meta,
},
};
}
/**
* Clears hash from window url.
*/
function clearHash(contentWindow) {
// Office.js sets history.replaceState to null
contentWindow.location.hash = "";
if (typeof contentWindow.history.replaceState === "function") {
// Full removes "#" from url
contentWindow.history.replaceState(null, "", `${contentWindow.location.origin}${contentWindow.location.pathname}${contentWindow.location.search}`);
}
}
/**
* Replaces current hash with hash from provided url
*/
function replaceHash(url) {
const urlParts = url.split("#");
urlParts.shift(); // Remove part before the hash
window.location.hash = urlParts.length > 0 ? urlParts.join("#") : "";
}
/**
* Returns boolean of whether the current window is in an iframe or not.
*/
function isInIframe() {
return window.parent !== window;
}
/**
* Returns boolean of whether or not the current window is a popup opened by msal
*/
function isInPopup() {
if (isInIframe()) {
return false;
}
try {
const { libraryState } = parseAuthResponseFromUrl();
const { meta } = libraryState;
return meta["interactionType"] === InteractionType.Popup;
}
catch (e) {
// If parsing fails (no state, invalid URL, etc.), we're not in a popup
return false;
}
}
/**
* Await a response from a redirect bridge using BroadcastChannel.
* This unified function works for both popup and iframe scenarios by listening on a
* BroadcastChannel for the server payload.
*
* @param timeoutMs - Timeout in milliseconds.
* @param logger - Logger instance for logging monitoring events.
* @param browserCrypto - Browser crypto instance for decoding state.
* @param request - The authorization or end session request.
* @returns Promise<string> - Resolves with the response string (query or hash) from the window.
*/
// Track the active bridge monitor to allow cancellation when overriding interactions
let activeBridgeMonitor = null;
/**
* Cancels the pending bridge response monitor if one exists.
* This is called when overrideInteractionInProgress is used to cancel
* any pending popup interaction before starting a new one.
*/
function cancelPendingBridgeResponse(logger, correlationId) {
if (activeBridgeMonitor) {
logger.verbose("18y01k", correlationId);
clearTimeout(activeBridgeMonitor.timeoutId);
activeBridgeMonitor.channel.close();
activeBridgeMonitor.reject(createBrowserAuthError(interactionInProgressCancelled, ""));
activeBridgeMonitor = null;
}
}
/** @internal */
async function waitForBridgeResponse(timeoutMs, logger, request, performanceClient, experimentalConfig) {
return new Promise((resolve, reject) => {
logger.verbose("1rf6em", request.correlationId);
const correlationId = request.correlationId;
performanceClient.addFields({
redirectBridgeTimeoutMs: timeoutMs,
lateResponseExperimentEnabled: experimentalConfig?.iframeTimeoutTelemetry || false,
}, correlationId);
const { libraryState } = parseRequestState(base64Decode, request.state || "", request.correlationId);
const channel = new BroadcastChannel(libraryState.id);
let responseString = undefined;
let timedOut$1 = false;
let lateTimeoutId;
let lateMeasurement;
const timeoutId = window.setTimeout(() => {
// Clear the active monitor
activeBridgeMonitor = null;
if (experimentalConfig?.iframeTimeoutTelemetry) {
lateMeasurement = performanceClient.startMeasurement(WaitForBridgeLateResponse, correlationId);
timedOut$1 = true;
lateTimeoutId = window.setTimeout(() => {
lateMeasurement?.end({ success: false });
clearTimeout(lateTimeoutId);
channel.close();
}, 60000); // 60s late response timeout to allow for telemetry of late responses
}
else {
channel.close();
}
reject(createBrowserAuthError(timedOut, "", "redirect_bridge_timeout"));
}, timeoutMs);
// Track this monitor so it can be cancelled if needed
activeBridgeMonitor = {
timeoutId,
channel,
reject,
};
channel.onmessage = (event) => {
responseString = event.data.payload;
const messageVersion = event?.data && typeof event.data.v === "number"
? event.data.v
: undefined;
if (timedOut$1) {
lateMeasurement?.end({
success: responseString ? true : false,
});
clearTimeout(lateTimeoutId);
channel.close();
return;
}
performanceClient.addFields({
redirectBridgeMessageVersion: messageVersion,
}, correlationId);
// Clear the active monitor
activeBridgeMonitor = null;
clearTimeout(timeoutId);
channel.close();
if (responseString) {
resolve(responseString);
}
else {
reject(createBrowserAuthError(redirectBridgeEmptyResponse, correlationId));
}
};
});
}
// #endregion
/**
* Returns current window URL as redirect uri
*/
function getCurrentUri() {
return typeof window !== "undefined" && window.location
? window.location.href.split("?")[0].split("#")[0]
: "";
}
/**
* Gets the homepage url for the current window location.
*/
function getHomepage(correlationId) {
const currentUrl = new UrlString(window.location.href, correlationId || "");
const urlComponents = currentUrl.getUrlComponents();
return `${urlComponents.Protocol}//${urlComponents.HostNameAndPort}/`;
}
/**
* Throws error if we have completed an auth and are
* attempting another auth request inside an iframe.
*/
function blockReloadInHiddenIframes() {
const isResponseHash = getDeserializedResponse(window.location.hash);
// return an error if called from the hidden iframe created by the msal js silent calls
if (isResponseHash && isInIframe()) {
throw createBrowserAuthError(blockIframeReload, "");
}
}
/**
* Block redirect operations in iframes unless explicitly allowed
* @param interactionType Interaction type for the request
* @param allowRedirectInIframe Config value to allow redirects when app is inside an iframe
*/
function blockRedirectInIframe(allowRedirectInIframe) {
if (isInIframe() && !allowRedirectInIframe) {
// If we are not in top frame, we shouldn't redirect. This is also handled by the service.
throw createBrowserAuthError(redirectInIframe, "");
}
}
/**
* Block redirectUri loaded in popup from calling AcquireToken APIs
*/
function blockAcquireTokenInPopups() {
// Popups opened by msal popup APIs are given a name that starts with "msal."
if (isInPopup()) {
throw createBrowserAuthError(blockNestedPopups, "");
}
}
/**
* Throws error if token requests are made in non-browser environment
* @param isBrowserEnvironment Flag indicating if environment is a browser.
*/
function blockNonBrowserEnvironment() {
if (typeof window === "undefined") {
throw createBrowserAuthError(nonBrowserEnvironment, "");
}
}
/**
* Throws error if initialize hasn't been called
* @param initialized
*/
function blockAPICallsBeforeInitialize(initialized) {
if (!initialized) {
throw createBrowserAuthError(uninitializedPublicClientApplication, "");
}
}
/**
* Helper to validate app environment before making an auth request
* @param initialized
*/
function preflightCheck$1(initialized) {
// Block request if not in browser environment
blockNonBrowserEnvironment();
// Block auth requests inside a hidden iframe
blockReloadInHiddenIframes();
// Block redirectUri opened in a popup from calling MSAL APIs
blockAcquireTokenInPopups();
// Block token acquisition before initialize has been called
blockAPICallsBeforeInitialize(initialized);
}
/**
* Helper to validate app environment before making redirect request
* @param initialized
* @param config
* @internal
*/
function redirectPreflightCheck(initialized, config) {
preflightCheck$1(initialized);
blockRedirectInIframe(config.system.allowRedirectInIframe);
// Block redirects if memory storage is enabled
if (config.cache.cacheLocation === BrowserCacheLocation.MemoryStorage) {
throw createBrowserConfigurationAuthError(inMemRedirectUnavailable, "");
}
}
/**
* Adds a preconnect link element to the header which begins DNS resolution and SSL connection in anticipation of the /token request
* @param loginDomain Authority domain, including https protocol e.g. https://login.microsoftonline.com
* @returns
*/
function preconnect(authority) {
const link = document.createElement("link");
link.rel = "preconnect";
link.href = new URL(authority).origin;
link.crossOrigin = "anonymous";
document.head.appendChild(link);
// The browser will close connection if not used within a few seconds, remove element from the header after 10s
window.setTimeout(() => {
try {
document.head.removeChild(link);
}
catch { }
}, 10000); // 10s Timeout
}
/**
* Wrapper function that creates a UUID v7 from the current timestamp.
* @returns {string}
*/
function createGuid() {
return createNewGuid();
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Storage wrapper for IndexedDB storage in browsers: https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
*/
class DatabaseStorage {
constructor() {
this.dbName = DB_NAME;
this.version = DB_VERSION;
this.tableName = DB_TABLE_NAME;
this.dbOpen = false;
}
/**
* Opens IndexedDB instance.
*/
async open() {
return new Promise((resolve, reject) => {
const openDB = window.indexedDB.open(this.dbName, this.version);
openDB.addEventListener("upgradeneeded", (e) => {
const event = e;
event.target.result.createObjectStore(this.tableName);
});
openDB.addEventListener("success", (e) => {
const event = e;
this.db = event.target.result;
this.dbOpen = true;
resolve();
});
openDB.addEventListener("error", () => reject(createBrowserAuthError(databaseUnavailable, "")));
});
}
/**
* Closes the connection to IndexedDB database when all pending transactions
* complete.
*/
closeConnection() {
const db = this.db;
if (db && this.dbOpen) {
db.close();
this.dbOpen = false;
}
}
/**
* Opens database if it's not already open
*/
async validateDbIsOpen() {
if (!this.dbOpen) {
return this.open();
}
}
/**
* Retrieves item from IndexedDB instance.
* @param key
*/
async getItem(key) {
await this.validateDbIsOpen();
return new Promise((resolve, reject) => {
// TODO: Add timeouts?
if (!this.db) {
return reject(createBrowserAuthError(databaseNotOpen, ""));
}
const transaction = this.db.transaction([this.tableName], "readonly");
const objectStore = transaction.objectStore(this.tableName);
const dbGet = objectStore.get(key);
dbGet.addEventListener("success", (e) => {
const event = e;
this.closeConnection();
resolve(event.target.result);
});
dbGet.addEventListener("error", (e) => {
this.closeConnection();
reject(e);
});
});
}
/**
* Adds item to IndexedDB under given key
* @param key
* @param payload
*/
async setItem(key, payload) {
await this.validateDbIsOpen();
return new Promise((resolve, reject) => {
// TODO: Add timeouts?
if (!this.db) {
return reject(createBrowserAuthError(databaseNotOpen, ""));
}
const transaction = this.db.transaction([this.tableName], "readwrite");
const objectStore = transaction.objectStore(this.tableName);
const dbPut = objectStore.put(payload, key);
dbPut.addEventListener("success", () => {
this.closeConnection();
resolve();
});
dbPut.addEventListener("error", (e) => {
this.closeConnection();
reject(e);
});
});
}
/**
* Removes item from IndexedDB under given key
* @param key
*/
async removeItem(key) {
await this.validateDbIsOpen();
return new Promise((resolve, reject) => {
if (!this.db) {
return reject(createBrowserAuthError(databaseNotOpen, ""));
}
const transaction = this.db.transaction([this.tableName], "readwrite");
const objectStore = transaction.objectStore(this.tableName);
const dbDelete = objectStore.delete(key);
dbDelete.addEventListener("success", () => {
this.closeConnection();
resolve();
});
dbDelete.addEventListener("error", (e) => {
this.closeConnection();
reject(e);
});
});
}
/**
* Get all the keys from the storage object as an iterable array of strings.
*/
async getKeys() {
await this.validateDbIsOpen();
return new Promise((resolve, reject) => {
if (!this.db) {
return reject(createBrowserAuthError(databaseNotOpen, ""));
}
const transaction = this.db.transaction([this.tableName], "readonly");
const objectStore = transaction.objectStore(this.tableName);
const dbGetKeys = objectStore.getAllKeys();
dbGetKeys.addEventListener("success", (e) => {
const event = e;
this.closeConnection();
resolve(event.target.result);
});
dbGetKeys.addEventListener("error", (e) => {
this.closeConnection();
reject(e);
});
});
}
/**
*
* Checks whether there is an object under the search key in the object store
*/
async containsKey(key) {
await this.validateDbIsOpen();
return new Promise((resolve, reject) => {
if (!this.db) {
return reject(createBrowserAuthError(databaseNotOpen, ""));
}
const transaction = this.db.transaction([this.tableName], "readonly");
const objectStore = transaction.objectStore(this.tableName);
const dbContainsKey = objectStore.count(key);
dbContainsKey.addEventListener("success", (e) => {
const event = e;
this.closeConnection();
resolve(event.target.result === 1);
});
dbContainsKey.addEventListener("error", (e) => {
this.closeConnection();
reject(e);
});
});
}
/**
* Deletes the MSAL database. The database is deleted rather than cleared to make it possible
* for client applications to downgrade to a previous MSAL version without worrying about forward compatibility issues
* with IndexedDB database versions.
*/
async deleteDatabase() {
// Check if database being deleted exists
if (this.db && this.dbOpen) {
this.closeConnection();
}
return new Promise((resolve, reject) => {
const deleteDbRequest = window.indexedDB.deleteDatabase(DB_NAME);
const id = setTimeout(() => reject(false), 200); // Reject if events aren't raised within 200ms
deleteDbRequest.addEventListener("success", () => {
clearTimeout(id);
return resolve(true);
});
deleteDbRequest.addEventListener("blocked", () => {
clearTimeout(id);
return resolve(true);
});
deleteDbRequest.addEventListener("error", () => {
clearTimeout(id);
return reject(false);
});
});
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class MemoryStorage {
constructor() {
this.cache = new Map();
}
async initialize() {
// Memory storage does not require initialization
}
getItem(key) {
return this.cache.get(key) || null;
}
getUserData(key) {
return this.getItem(key);
}
setItem(key, value) {
this.cache.set(key, value);
}
async setUserData(key, value) {
this.setItem(key, value);
}
removeItem(key) {
this.cache.delete(key);
}
getKeys() {
const cacheKeys = [];
this.cache.forEach((value, key) => {
cacheKeys.push(key);
});
return cacheKeys;
}
containsKey(key) {
return this.cache.has(key);
}
clear() {
this.cache.clear();
}
decryptData() {
// Memory storage does not support encryption, so this method is a no-op
return Promise.resolve(null);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* This class allows MSAL to store artifacts asynchronously using the DatabaseStorage IndexedDB wrapper,
* backed up with the more volatile MemoryStorage object for cases in which IndexedDB may be unavailable.
*/
class AsyncMemoryStorage {
constructor(logger) {
this.inMemoryCache = new MemoryStorage();
this.indexedDBCache = new DatabaseStorage();
this.logger = logger;
}
handleDatabaseAccessError(error, correlationId) {
if (error instanceof BrowserAuthError &&
error.errorCode === databaseUnavailable) {
this.logger.error("1wx7zz", correlationId);
}
else {
throw error;
}
}
/**
* Get the item matching the given key. Tries in-memory cache first, then in the asynchronous
* storage object if item isn't found in-memory.
* @param key
* @param correlationId
*/
async getItem(key, correlationId) {
const item = this.inMemoryCache.getItem(key);
if (!item) {
try {
this.logger.verbose("0naxpl", correlationId);
return await this.indexedDBCache.getItem(key);
}
catch (e) {
this.handleDatabaseAccessError(e, correlationId);
}
}
return item;
}
/**
* Sets the item in the in-memory cache and then tries to set it in the asynchronous
* storage object with the given key.
* @param key
* @param value
* @param correlationId
*/
async setItem(key, value, correlationId) {
this.inMemoryCache.setItem(key, value);
try {
await this.indexedDBCache.setItem(key, value);
}
catch (e) {
this.handleDatabaseAccessError(e, correlationId);
}
}
/**
* Removes the item matching the key from the in-memory cache, then tries to remove it from the asynchronous storage object.
* @param key
* @param correlationId
*/
async removeItem(key, correlationId) {
this.inMemoryCache.removeItem(key);
try {
await this.indexedDBCache.removeItem(key);
}
catch (e) {
this.handleDatabaseAccessError(e, correlationId);
}
}
/**
* Get all keys from both in-memory and persistent storage.
* @param correlationId
*/
async getKeys(correlationId) {
const cacheKeys = this.inMemoryCache.getKeys();
try {
const persistentCacheKeys = await this.indexedDBCache.getKeys();
return Array.from(new Set([...cacheKeys, ...persistentCacheKeys]));
}
catch (e) {
this.handleDatabaseAccessError(e, correlationId);
return cacheKeys;
}
}
/**
* Returns true or false if the given key is present in the cache.
* @param key
* @param correlationId
*/
async containsKey(key, correlationId) {
const containsKey = this.inMemoryCache.containsKey(key);
if (!containsKey) {
try {
this.logger.verbose("03zl2j", correlationId);
return await this.indexedDBCache.containsKey(key);
}
catch (e) {
this.handleDatabaseAccessError(e, correlationId);
}
}
return containsKey;
}
/**
* Clears in-memory Map
* @param correlationId
*/
clearInMemory(correlationId) {
// InMemory cache is a Map instance, clear is straightforward
this.logger.verbose("03r21p", correlationId);
this.inMemoryCache.clear();
this.logger.verbose("0uksk1", correlationId);
}
/**
* Tries to delete the IndexedDB database
* @param correlationId
* @returns
*/
async clearPersistent(correlationId) {
try {
this.logger.verbose("0rdqut", correlationId);
const dbDeleted = await this.indexedDBCache.deleteDatabase();
if (dbDeleted) {
this.logger.verbose("149ouc", correlationId);
}
return dbDeleted;
}
catch (e) {
this.handleDatabaseAccessError(e, correlationId);
return false;
}
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Owns browser token-binding key lifecycle and storage lookup.
* @internal
*/
class TokenBindingKeyManager {
constructor(logger, performanceClient) {
this.logger = logger;
this.cache = TokenBindingKeyManager.getTokenBindingKeyStorage(this.logger);
this.performanceClient = performanceClient;
}
static getTokenBindingKeyStorage(logger) {
if (!TokenBindingKeyManager.tokenBindingKeyStorage) {
TokenBindingKeyManager.tokenBindingKeyStorage =
new AsyncMemoryStorage(logger);
}
return TokenBindingKeyManager.tokenBindingKeyStorage;
}
/**
* Provisions a browser token-binding key and returns its key identifier.
* @param request - Key provisioning policy.
*/
async provisionTokenBindingKey(request) {
const publicKeyThumbMeasurement = this.performanceClient?.startMeasurement(CryptoOptsGetPublicKeyThumbprint, request.correlationId);
try {
const activeKeyPair = await this.createTokenBindingKey(request);
publicKeyThumbMeasurement?.end({
success: true,
...this.getTokenBindingKeyTelemetry(activeKeyPair),
});
return activeKeyPair.keyId;
}
catch (e) {
publicKeyThumbMeasurement?.end({
success: false,
tokenBindingKeyType: request.tokenBindingKeyType,
tokenBindingKeyAlgorithm: request.tokenBindingKeyAlgorithm,
});
throw e;
}
}
/**
* Removes a browser token-binding key by identifier.
* @param kid - Token-binding key identifier.
* @param correlationId - Request correlation identifier.
*/
async removeTokenBindingKey(kid, correlationId) {
await this.cache.removeItem(kid, correlationId);
const keyFound = await this.cache.containsKey(kid, correlationId);
if (keyFound) {
throw createClientAuthError(bindingKeyNotRemoved, correlationId);
}
}
/**
* Clears browser token-binding keys from memory and persistent storage.
* @param correlationId - Request correlation identifier.
*/
async clearKeystore(correlationId) {
this.cache.clearInMemory(correlationId);
try {
await this.cache.clearPersistent(correlationId);
return true;
}
catch (e) {
if (e instanceof Error) {
this.logger.error(`1owpn8 ${e.message}`, correlationId);
}
else {
this.logger.error("0yrmwo", correlationId);
}
return false;
}
}
/**
* Gets a token-binding public key as a JWK by identifier.
* @param keyId - Token-binding key identifier.
* @param correlationId - Request correlation identifier.
*/
async getTokenBindingPublicKeyJwk(keyId, correlationId) {
const cachedKeyPair = await this.getTokenBindingKeyPair(keyId, correlationId);
return exportJwk(cachedKeyPair.publicKey);
}
async createTokenBindingKey(request) {
const keyGenAlgorithm = this.getTokenBindingKeyGenAlgorithmOptions(request.tokenBindingKeyAlgorithm, request.correlationId);
const generatedKeyPair = await this.generateKeyPairAndThumbprint(TokenBindingKeyManager.TOKEN_BINDING_KEY_USAGES, keyGenAlgorithm, request.correlationId);
await this.cache.setItem(generatedKeyPair.keyId, {
...generatedKeyPair,
tokenBindingKeyType: request.tokenBindingKeyType,
tokenBindingKeyAlgorithm: request.tokenBindingKeyAlgorithm,
}, request.correlationId);
return {
...generatedKeyPair,
tokenBindingKeyType: request.tokenBindingKeyType,
tokenBindingKeyAlgorithm: request.tokenBindingKeyAlgorithm,
};
}
async generateKeyPairAndThumbprint(usages, keyGenAlgorithm, correlationId) {
const keyPair = await generateKeyPair(false, usages, keyGenAlgorithm);
const publicJwk = await exportJwk(keyPair.publicKey);
const keyId = await computeJwkThumbprint(publicJwk, correlationId);
return {
publicKey: keyPair.publicKey,
privateKey: keyPair.privateKey,
keyId,
};
}
/** @internal */
async getTokenBindingKeyPair(keyId, correlationId) {
const cachedKeyPair = await this.cache.getItem(keyId, correlationId);
if (!cachedKeyPair) {
throw createBrowserAuthError(cryptoKeyNotFound, correlationId);
}
return cachedKeyPair;
}
/** @internal */
getTokenBindingKeyTelemetry(cachedKeyPair, fallbackAlgorithm) {
return {
...(cachedKeyPair.tokenBindingKeyType && {
tokenBindingKeyType: cachedKeyPair.tokenBindingKeyType,
}),
...(cachedKeyPair.tokenBindingKeyAlgorithm || fallbackAlgorithm
? {
tokenBindingKeyAlgorithm: cachedKeyPair.tokenBindingKeyAlgorithm ||
fallbackAlgorithm,
}
: {}),
};
}
getTokenBindingKeyGenAlgorithmOptions(tokenBindingKeyAlgorithm, correlationId) {
if (tokenBindingKeyAlgorithm === JsonWebTokenAlgorithms.RS256) {
return RSA_KEYGEN_ALGORITHM_OPTIONS;
}
if (tokenBindingKeyAlgorithm === JsonWebTokenAlgorithms.ES256) {
return ECDSA_P256_KEYGEN_ALGORITHM_OPTIONS;
}
throw createBrowserAuthError(unsupportedTokenBindingAlgorithm, correlationId);
}
}
TokenBindingKeyManager.TOKEN_BINDING_KEY_USAGES = [
"sign",
"verify",
];
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class BaseInteractionClient {
constructor(config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, performanceClient, correlationId, platformAuthProvider, tokenBindingKeyManager) {
this.config = config;
this.browserStorage = storageImpl;
this.browserCrypto = browserCrypto;
this.networkClient = this.config.system.networkClient;
this.eventHandler = eventHandler;
this.navigationClient = navigationClient;
this.platformAuthProvider = platformAuthProvider;
this.correlationId = correlationId;
this.logger = logger.clone(name, version);
this.performanceClient = performanceClient;
this.tokenBindingKeyManager =
tokenBindingKeyManager ||
new TokenBindingKeyManager(this.logger, this.performanceClient);
}
}
/**
* Use to get the redirect URI configured in MSAL or construct one from the current page.
* @param requestRedirectUri - Redirect URI from the request or undefined if not configured
* @param clientConfigRedirectUri - Redirect URI from the client configuration or undefined if not configured
* @param logger - Logger instance from the calling client
* @param correlationId
* @returns Absolute redirect URL constructed from the provided URI, config, or current page
*/
function getRedirectUri(requestRedirectUri, clientConfigRedirectUri, logger, correlationId) {
logger.verbose("0bd1la", correlationId);
const redirectUri = requestRedirectUri || clientConfigRedirectUri || "";
return UrlString.getAbsoluteUrl(redirectUri, getCurrentUri(), correlationId);
}
/**
* Initializes and returns a ServerTelemetryManager with the provided telemetry configuration.
* @param apiId - The API identifier for telemetry tracking
* @param clientId - The client application identifier
* @param correlationId - Unique identifier for correlating requests
* @param browserStorage - Browser cache manager instance for storing telemetry data
* @param logger - Optional logger instance for verbose logging
* @param forceRefresh - Optional flag to force refresh of telemetry data
* @param enabled - Optional flag to enable or disable server telemetry (default: true for custom_auth flows, false for standard flows)
* @returns Configured ServerTelemetryManager instance
*/
function initializeServerTelemetryManager(apiId, clientId, correlationId, browserStorage, logger, forceRefresh, enabled = true) {
logger.verbose("1p12tq", correlationId);
if (!enabled) {
logger.verbose("0tajnr", correlationId);
return new StubServerTelemetryManager();
}
const telemetryPayload = {
clientId: clientId,
correlationId: correlationId,
apiId: apiId,
forceRefresh: forceRefresh || false,
wrapperSKU: browserStorage.getWrapperMetadata()[0],
wrapperVer: browserStorage.getWrapperMetadata()[1],
};
return new ServerTelemetryManager(telemetryPayload, browserStorage);
}
/**
* Used to get a discovered version of the default authority.
* @param params - Configuration object containing authority and cloud options
* @param params.requestAuthority - Optional specific authority URL to use
* @param params.requestAzureCloudOptions - Optional Azure cloud configuration options
* @param params.requestExtraQueryParameters - Optional additional query parameters
* @param params.account - Optional account info for instance-aware scenarios
* @param config - Browser configuration containing auth settings
* @param correlationId - Unique identifier for correlating requests
* @param performanceClient - Performance monitoring client instance
* @param browserStorage - Browser cache manager instance
* @param logger - Logger instance for tracking operations
* @returns Promise that resolves to a discovered Authority instance
*/
async function getDiscoveredAuthority(config, correlationId, performanceClient, browserStorage, logger, requestAuthority, requestAzureCloudOptions, requestExtraQueryParameters, account) {
const instanceAwareEQ = requestExtraQueryParameters &&
requestExtraQueryParameters.hasOwnProperty("instance_aware")
? requestExtraQueryParameters["instance_aware"]
: undefined;
const authorityOptions = {
protocolMode: config.system.protocolMode,
OIDCOptions: config.auth.OIDCOptions,
knownAuthorities: config.auth.knownAuthorities,
cloudDiscoveryMetadata: config.auth.cloudDiscoveryMetadata,
authorityMetadata: config.auth.authorityMetadata,
};
// build authority string based on auth params, precedence - azureCloudInstance + tenant >> authority
const resolvedAuthority = requestAuthority || config.auth.authority;
const resolvedInstanceAware = instanceAwareEQ?.length
? instanceAwareEQ === "true"
: config.auth.instanceAware;
const userAuthority = account && resolvedInstanceAware
? config.auth.authority.replace(UrlString.getDomainFromUrl(resolvedAuthority, correlationId), account.environment)
: resolvedAuthority;
// fall back to the authority from config
const builtAuthority = Authority.generateAuthority(userAuthority, requestAzureCloudOptions || config.auth.azureCloudOptions);
const discoveredAuthority = await invokeAsync(createDiscoveredInstance, AuthorityFactoryCreateDiscoveredInstance, logger, performanceClient, correlationId)(builtAuthority, config.system.networkClient, browserStorage, authorityOptions, logger, correlationId, performanceClient);
if (account && !discoveredAuthority.isAlias(account.environment)) {
throw createClientConfigurationError(authorityMismatch, correlationId);
}
return discoveredAuthority;
}
/**
* Clears cache and account information during logout.
*
* If an account is provided, removes the account from cache and, if it is the active account, sets the active account to null.
* If no account is provided, clears all accounts and tokens from cache.
*
* @param browserStorage - The browser cache manager instance used to manage cache.
* @param browserCrypto - The crypto interface for cache operations.
* @param logger - Logger instance for logging operations.
* @param correlationId - Correlation ID for the logout operation.
* @param account - (Optional) The account to clear from cache. If not provided, all accounts are cleared.
* @returns A promise that resolves when the cache has been cleared.
*/
async function clearCacheOnLogout(browserStorage, browserCrypto, logger, correlationId, account) {
if (account) {
// Clear given account.
try {
browserStorage.removeAccount(account, correlationId);
logger.verbose("0s4z6h", correlationId);
}
catch (error) {
logger.error("0mgg1d", correlationId);
}
}
else {
try {
logger.verbose("0zj631", correlationId);
// Clear all accounts and tokens
browserStorage.clear(correlationId);
// Clear any stray keys from IndexedDB
await browserCrypto.clearKeystore(correlationId);
}
catch (e) {
logger.error("12ih0c", correlationId);
}
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* This class implements MSAL's crypto interface, which allows it to perform base64 encoding and decoding, generating cryptographically random GUIDs and
* implementing Proof Key for Code Exchange specs for the OAuth Authorization Code Flow using PKCE (rfc here: https://tools.ietf.org/html/rfc7636).
*/
class CryptoOps {
constructor(logger, performanceClient, skipValidateSubtleCrypto) {
this.logger = logger;
// Browser crypto needs to be validated first before any other classes can be set.
validateCryptoAvailable(skipValidateSubtleCrypto ?? false);
this.performanceClient = performanceClient;
this.tokenBindingKeyManager = new TokenBindingKeyManager(this.logger, this.performanceClient);
}
/**
* Creates a new random GUID - used to populate state and nonce.
* @returns string (GUID)
*/
createNewGuid() {
return createNewGuid();
}
/**
* Encodes input string to base64.
* @param input
*/
base64Encode(input) {
return base64Encode(input);
}
/**
* Decodes input string from base64.
* @param input
*/
base64Decode(input) {
return base64Decode(input);
}
/**
* Encodes input string to base64 URL safe string.
* @param input
*/
base64UrlEncode(input) {
return urlEncode(input);
}
/**
* Stringifies and base64Url encodes input public key
* @param inputKid
* @returns Base64Url encoded public key
*/
encodeKid(inputKid) {
return this.base64UrlEncode(JSON.stringify({ kid: inputKid }));
}
/**
* Removes cryptographic keypair from key store matching the keyId passed in
* @param kid
* @param correlationId
*/
async removeTokenBindingKey(kid, correlationId) {
await this.tokenBindingKeyManager.removeTokenBindingKey(kid, correlationId);
}
/**
* Removes all cryptographic keys from IndexedDB storage
* @param correlationId
*/
async clearKeystore(correlationId) {
return this.tokenBindingKeyManager.clearKeystore(correlationId);
}
/** @internal */
async signTokenBindingJwt(header, payload, kid, correlationId) {
let telemetry = {};
const signTokenBindingJwtMeasurement = this.performanceClient?.startMeasurement(CryptoOptsSignJwt, correlationId);
try {
const cachedKeyPair = await this.tokenBindingKeyManager.getTokenBindingKeyPair(kid, correlationId);
await this.validateTokenBindingJwtHeaderKey(header, kid, correlationId);
telemetry = this.tokenBindingKeyManager.getTokenBindingKeyTelemetry(cachedKeyPair, header.alg);
const signingAlgorithm = this.getTokenBindingKeySigningAlgorithm(cachedKeyPair, header.alg, correlationId);
const tokenString = `${urlEncode(JSON.stringify(header))}.${urlEncode(JSON.stringify(payload))}`;
const encodedSignature = await this.signInput(cachedKeyPair, tokenString, signingAlgorithm);
signTokenBindingJwtMeasurement?.end({
success: true,
...telemetry,
});
return `${tokenString}.${encodedSignature}`;
}
catch (e) {
signTokenBindingJwtMeasurement?.end({
success: false,
...telemetry,
});
throw e;
}
}
/**
* Returns the SHA-256 hash of an input string
* @param plainText
*/
async hashString(plainText) {
return hashString(plainText);
}
async signInput(cachedKeyPair, signingInput, algorithm) {
const encoder = new TextEncoder();
const signatureBuffer = await sign(cachedKeyPair.privateKey, encoder.encode(signingInput), algorithm);
return urlEncodeArr(new Uint8Array(signatureBuffer));
}
getTokenBindingKeySigningAlgorithm(cachedKeyPair, requestedAlgorithm, correlationId) {
const keyAlgorithm = cachedKeyPair.privateKey.algorithm;
if (requestedAlgorithm === JsonWebTokenAlgorithms.RS256 &&
keyAlgorithm.name === RSA_SIGN_ALGORITHM_OPTIONS.name) {
return RSA_SIGN_ALGORITHM_OPTIONS;
}
if (requestedAlgorithm === JsonWebTokenAlgorithms.ES256 &&
keyAlgorithm.name ===
ECDSA_SHA256_SIGN_ALGORITHM_OPTIONS.name &&
keyAlgorithm.namedCurve ===
ECDSA_P256_KEYGEN_ALGORITHM_OPTIONS.namedCurve) {
return ECDSA_SHA256_SIGN_ALGORITHM_OPTIONS;
}
if (requestedAlgorithm === JsonWebTokenAlgorithms.RS256 ||
requestedAlgorithm === JsonWebTokenAlgorithms.ES256) {
throw createBrowserAuthError(unsupportedTokenBindingAlgorithm, correlationId, tokenBindingKeyAlgorithmMismatch);
}
throw createBrowserAuthError(unsupportedTokenBindingAlgorithm, correlationId);
}
async validateTokenBindingJwtHeaderKey(header, kid, correlationId) {
if (!header.jwk) {
return;
}
const headerKeyId = await computeJwkThumbprint(header.jwk, correlationId);
if (headerKeyId !== kid) {
throw createBrowserAuthError(invalidPublicJwk, correlationId, tokenBindingKeyJwkThumbprintMismatch);
}
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const SUPPORTED_AUTHENTICATION_SCHEMES = new Set([
AuthenticationScheme.BEARER,
AuthenticationScheme.POP,
AuthenticationScheme.DPOP,
AuthenticationScheme.SSH,
]);
function validateSshRequest(request, correlationId) {
if (!request.sshJwk) {
throw createClientConfigurationError(missingSshJwk, correlationId);
}
if (!request.sshKid) {
throw createClientConfigurationError(missingSshKid, correlationId);
}
}
function validateDpopRequest(request, correlationId) {
if (!request.resourceRequestMethod?.trim() ||
!request.resourceRequestUri?.trim()) {
throw createClientConfigurationError(dpopMissingResourceContext, correlationId);
}
}
/**
* Resolves the token-binding parameters needed before building authorize or token requests.
* Public PCA DPoP requests use a dpopJkt thumbprint, while platform broker PoP requests use
* a reqCnf confirmation claim. Requests that do not require request-time token binding return
* no additional parameters.
*/
async function getTokenBindingRequestParams(request, tokenBindingKeyManager, logger, performanceClient) {
switch (request.authenticationScheme) {
case AuthenticationScheme.DPOP:
if (request.platformBroker) {
return {};
}
if (request.dpopJkt) {
return { dpopJkt: request.dpopJkt };
}
return {
dpopJkt: await tokenBindingKeyManager.provisionTokenBindingKey({
tokenBindingKeyType: AuthenticationScheme.DPOP.toLowerCase(),
tokenBindingKeyAlgorithm: JsonWebTokenAlgorithms.ES256,
correlationId: request.correlationId,
}),
};
case AuthenticationScheme.POP:
if (!request.platformBroker) {
return {};
}
const cryptoOps = new CryptoOps(logger, performanceClient);
if (request.popKid) {
return { reqCnf: cryptoOps.encodeKid(request.popKid) };
}
const popTokenGenerator = new PopTokenGenerator(cryptoOps, tokenBindingKeyManager, performanceClient);
const generatedReqCnfData = await invokeAsync(popTokenGenerator.generateCnf.bind(popTokenGenerator), PopTokenGenerateCnf, logger, performanceClient, request.correlationId)(request, logger);
return { reqCnf: generatedReqCnfData.reqCnfString };
default:
return {};
}
}
/**
* Initializer function for all request APIs
* @param request
* @param config
* @param performanceClient
* @param logger
* @param correlationId
*/
async function initializeBaseRequest(request, config, performanceClient, logger, correlationId) {
const authority = request.authority || config.auth.authority;
const scopes = [...((request && request.scopes) || [])];
const validatedRequest = {
...request,
correlationId: request.correlationId,
authority,
scopes,
};
// Set authenticationScheme to BEARER if not explicitly set in the request
if (!validatedRequest.authenticationScheme) {
validatedRequest.authenticationScheme =
AuthenticationScheme.BEARER;
logger.verbose("1l4fwv", correlationId);
}
else {
if (!SUPPORTED_AUTHENTICATION_SCHEMES.has(validatedRequest.authenticationScheme)) {
throw createClientConfigurationError(unsupportedAuthenticationScheme, correlationId);
}
switch (validatedRequest.authenticationScheme) {
case AuthenticationScheme.SSH:
validateSshRequest(request, correlationId);
break;
case AuthenticationScheme.DPOP: {
validateDpopRequest(request, correlationId);
break;
}
}
logger.verbose(`1ecmns ${validatedRequest.authenticationScheme}`, correlationId);
}
return validatedRequest;
}
async function initializeSilentRequest(request, account, config, performanceClient, logger) {
const baseRequest = await invokeAsync(initializeBaseRequest, InitializeBaseRequest, logger, performanceClient, request.correlationId)(request, config, performanceClient, logger, request.correlationId);
return {
...request,
...baseRequest,
account: account,
forceRefresh: request.forceRefresh || false,
};
}
/**
* Validates that the combination of request method, protocol mode and authorize body parameters is correct.
* Returns the validated or defaulted HTTP method or throws if the configured combination is invalid.
* @param interactionRequest
* @param protocolMode
* @returns
*/
function validateRequestMethod(interactionRequest, protocolMode) {
let httpMethod;
const requestMethod = interactionRequest.httpMethod;
if (protocolMode === ProtocolMode.EAR) {
// Validate that method can only be POST when protocol mode is EAR
if (requestMethod && requestMethod !== HttpMethod$1.POST) {
throw createClientConfigurationError(invalidRequestMethodForEAR, "");
}
else {
httpMethod = HttpMethod$1.POST;
}
}
else {
// For non-EAR protocol modes, default to GET if httpMethod is not set
httpMethod = requestMethod || HttpMethod$1.GET;
}
return httpMethod;
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Defines the class structure and helper functions used by the "standard", non-brokered auth flows (popup, redirect, silent (RT), silent (iframe))
*/
class StandardInteractionClient extends BaseInteractionClient {
/**
* Initializer for the logout request.
* @param logoutRequest
*/
initializeLogoutRequest(logoutRequest) {
this.logger.verbose("0546u4", this.correlationId);
const validLogoutRequest = {
correlationId: this.correlationId,
...logoutRequest,
};
/**
* Set logout_hint to be login_hint from ID Token Claims if present
* and logoutHint attribute wasn't manually set in logout request
*/
if (logoutRequest) {
// If logoutHint isn't set and an account was passed in, try to extract logoutHint from account loginHint or ID Token Claims
if (!logoutRequest.logoutHint) {
if (logoutRequest.account) {
const logoutHint = logoutRequest.account.loginHint ||
this.getLogoutHintFromIdTokenClaims(logoutRequest.account);
if (logoutHint) {
this.logger.verbose("0d7s8p", this.correlationId);
validLogoutRequest.logoutHint = logoutHint;
}
}
else {
this.logger.verbose("0pdtc3", this.correlationId);
}
}
else {
this.logger.verbose("12k4l4", this.correlationId);
}
}
else {
this.logger.verbose("07ndze", this.correlationId);
}
/*
* Only set redirect uri if logout request isn't provided or the set uri isn't null.
* Otherwise, use passed uri, config, or current page.
*/
if (!logoutRequest || logoutRequest.postLogoutRedirectUri !== null) {
if (logoutRequest && logoutRequest.postLogoutRedirectUri) {
this.logger.verbose("1vamm6", validLogoutRequest.correlationId);
validLogoutRequest.postLogoutRedirectUri =
UrlString.getAbsoluteUrl(logoutRequest.postLogoutRedirectUri, getCurrentUri(), validLogoutRequest.correlationId);
}
else if (this.config.auth.postLogoutRedirectUri === null) {
this.logger.verbose("15m5g7", validLogoutRequest.correlationId);
}
else if (this.config.auth.postLogoutRedirectUri) {
this.logger.verbose("1f4xlz", validLogoutRequest.correlationId);
validLogoutRequest.postLogoutRedirectUri =
UrlString.getAbsoluteUrl(this.config.auth.postLogoutRedirectUri, getCurrentUri(), validLogoutRequest.correlationId);
}
else {
this.logger.verbose("17s5rf", validLogoutRequest.correlationId);
validLogoutRequest.postLogoutRedirectUri =
UrlString.getAbsoluteUrl(getCurrentUri(), getCurrentUri(), validLogoutRequest.correlationId);
}
}
else {
this.logger.verbose("0ljv63", validLogoutRequest.correlationId);
}
return validLogoutRequest;
}
/**
* Parses login_hint ID Token Claim out of AccountInfo object to be used as
* logout_hint in end session request.
* @param account
*/
getLogoutHintFromIdTokenClaims(account) {
const idTokenClaims = account.idTokenClaims;
if (idTokenClaims) {
if (idTokenClaims.login_hint) {
this.logger.verbose("0u5bmc", this.correlationId);
return idTokenClaims.login_hint;
}
else {
this.logger.verbose("0mvp54", this.correlationId);
}
}
else {
this.logger.verbose("1e7bdp", this.correlationId);
}
return null;
}
/**
* Creates an Authorization Code Client with the given authority, or the default authority.
* @param params {
* serverTelemetryManager: ServerTelemetryManager;
* authorityUrl?: string;
* requestAzureCloudOptions?: AzureCloudOptions;
* requestExtraQueryParameters?: StringDict;
* account?: AccountInfo;
* }
*/
async createAuthCodeClient(params) {
// Create auth module.
const clientConfig = await invokeAsync(this.getClientConfiguration.bind(this), StandardInteractionClientGetClientConfiguration, this.logger, this.performanceClient, this.correlationId)(params);
return new AuthorizationCodeClient(clientConfig, this.performanceClient);
}
/**
* Creates a Client Configuration object with the given request authority, or the default authority.
* @param params {
* serverTelemetryManager: ServerTelemetryManager;
* requestAuthority?: string;
* requestAzureCloudOptions?: AzureCloudOptions;
* requestExtraQueryParameters?: boolean;
* account?: AccountInfo;
* }
*/
async getClientConfiguration(params) {
const { serverTelemetryManager, requestAuthority, requestAzureCloudOptions, requestExtraQueryParameters, account, } = params;
const discoveredAuthority = params.authority ||
(await invokeAsync(getDiscoveredAuthority, StandardInteractionClientGetDiscoveredAuthority, this.logger, this.performanceClient, this.correlationId)(this.config, this.correlationId, this.performanceClient, this.browserStorage, this.logger, requestAuthority, requestAzureCloudOptions, requestExtraQueryParameters, account));
const logger = this.config.system.loggerOptions;
return {
authOptions: {
clientId: this.config.auth.clientId,
authority: discoveredAuthority,
clientCapabilities: this.config.auth.clientCapabilities,
redirectUri: this.config.auth.redirectUri,
isMcp: this.config.auth.isMcp,
},
systemOptions: {
tokenRenewalOffsetSeconds: this.config.system.tokenRenewalOffsetSeconds,
preventCorsPreflight: true,
},
loggerOptions: {
loggerCallback: logger.loggerCallback,
piiLoggingEnabled: logger.piiLoggingEnabled,
logLevel: logger.logLevel,
correlationId: this.correlationId,
},
cryptoInterface: this.browserCrypto,
tokenBindingKeyManager: this.tokenBindingKeyManager,
networkInterface: this.networkClient,
storageInterface: this.browserStorage,
serverTelemetryManager: serverTelemetryManager,
libraryInfo: {
sku: BrowserConstants.MSAL_SKU,
version: version,
cpu: "",
os: "",
},
telemetry: this.config.telemetry,
};
}
}
/**
* Helper to initialize required request parameters for interactive APIs and ssoSilent().
*
* @param request - The authentication request object (RedirectRequest, PopupRequest, or SsoSilentRequest).
* @param interactionType - The type of interaction (e.g., redirect, popup, silent).
* @param config - The browser configuration object.
* @param browserCrypto - The cryptographic interface for browser operations.
* @param browserStorage - The browser storage manager instance.
* @param logger - The logger instance for logging messages.
* @param performanceClient - The performance client for telemetry.
* @param correlationId - The correlation ID for the request.
* @returns A promise that resolves to a CommonAuthorizationUrlRequest object with initialized parameters.
*/
async function initializeAuthorizationRequest(request, interactionType, config, browserCrypto, browserStorage, logger, performanceClient, correlationId) {
const redirectUri = getRedirectUri(request.redirectUri, config.auth.redirectUri, logger, correlationId);
if (new URL(redirectUri).origin !== new URL(window.location.href).origin) {
logger.warning("08qbvw", correlationId);
performanceClient.addFields({ isRedirectUriCrossOrigin: true }, correlationId);
}
const browserState = {
interactionType: interactionType,
};
const state = setRequestState(browserCrypto, (request && request.state) || "", browserState, correlationId);
const baseRequest = await invokeAsync(initializeBaseRequest, InitializeBaseRequest, logger, performanceClient, correlationId)({ ...request, correlationId: correlationId }, config, performanceClient, logger, correlationId);
const interactionRequest = {
...baseRequest,
redirectUri: redirectUri,
state: state,
nonce: request.nonce || createNewGuid(),
responseMode: config.auth.OIDCOptions.responseMode,
};
const validatedRequest = {
...interactionRequest,
httpMethod: validateRequestMethod(interactionRequest, config.system.protocolMode),
};
// Skip active account lookup if either login hint or session id is set
if (request.loginHint || request.sid) {
return validatedRequest;
}
const account = request.account || browserStorage.getActiveAccount(correlationId);
if (account) {
logger.verbose("1eqlb3", correlationId);
logger.verbosePii(`0tf99t ${account.homeAccountId}`, correlationId);
validatedRequest.account = account;
}
return validatedRequest;
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class CustomAuthInteractionClientBase extends StandardInteractionClient {
constructor(config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, performanceClient, customAuthApiClient, customAuthAuthority, tokenBindingKeyManager) {
super(config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, performanceClient, "", undefined, tokenBindingKeyManager);
this.customAuthApiClient = customAuthApiClient;
this.customAuthAuthority = customAuthAuthority;
this.tokenResponseHandler = new ResponseHandler(this.config.auth.clientId, this.browserStorage, this.browserCrypto, this.logger, this.performanceClient, null, null, this.tokenBindingKeyManager);
}
getChallengeTypes(configuredChallengeTypes) {
const challengeType = configuredChallengeTypes ?? [];
if (!challengeType.some((type) => type.toLowerCase() === ChallengeType.REDIRECT)) {
challengeType.push(ChallengeType.REDIRECT);
}
return challengeType.join(" ");
}
getScopes(scopes) {
if (!!scopes && scopes.length > 0) {
return scopes;
}
return [
OPENID_SCOPE,
PROFILE_SCOPE,
OFFLINE_ACCESS_SCOPE,
];
}
/**
* Common method to handle token response processing.
* @param tokenResponse The token response from the API
* @param requestScopes Scopes for the token request
* @param correlationId Correlation ID for logging
* @returns Authentication result from the token response
*/
async handleTokenResponse(tokenResponse, requestScopes, correlationId, apiId) {
this.logger.verbose("04a00a", correlationId);
const requestTimestamp = Math.round(new Date().getTime() / 1000.0);
// Save tokens and create authentication result
const result = await this.tokenResponseHandler.handleServerTokenResponse(tokenResponse, this.customAuthAuthority, requestTimestamp, {
authority: this.customAuthAuthority.canonicalAuthority,
correlationId: tokenResponse.correlation_id ?? correlationId,
scopes: requestScopes,
}, apiId);
return result;
}
// It is not necessary to implement this method from base class.
acquireToken(
// eslint-disable-next-line @typescript-eslint/no-unused-vars
request) {
throw new MethodNotImplementedError("SignInClient.acquireToken");
}
// It is not necessary to implement this method from base class.
logout(
// eslint-disable-next-line @typescript-eslint/no-unused-vars
request) {
throw new MethodNotImplementedError("SignInClient.logout");
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const SIGN_IN_CODE_SEND_RESULT_TYPE = "SignInCodeSendResult";
const SIGN_IN_PASSWORD_REQUIRED_RESULT_TYPE = "SignInPasswordRequiredResult";
const SIGN_IN_COMPLETED_RESULT_TYPE = "SignInCompletedResult";
const SIGN_IN_JIT_REQUIRED_RESULT_TYPE = "SignInJitRequiredResult";
const SIGN_IN_MFA_REQUIRED_RESULT_TYPE = "SignInMfaRequiredResult";
function createSignInCompleteResult(input) {
return {
type: SIGN_IN_COMPLETED_RESULT_TYPE,
...input,
};
}
function createSignInPasswordRequiredResult(input) {
return {
type: SIGN_IN_PASSWORD_REQUIRED_RESULT_TYPE,
...input,
};
}
function createSignInCodeSendResult(input) {
return {
type: SIGN_IN_CODE_SEND_RESULT_TYPE,
...input,
};
}
function createSignInJitRequiredResult(input) {
return {
type: SIGN_IN_JIT_REQUIRED_RESULT_TYPE,
...input,
};
}
function createSignInMfaRequiredResult(input) {
return {
type: SIGN_IN_MFA_REQUIRED_RESULT_TYPE,
...input,
};
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* The public API ids should be claim in the MSAL telemtry tracker.
* All the following ids are hardcoded; so we need to find a way to claim them in the future and update them here.
*/
// Sign in
const SIGN_IN_WITH_CODE_START = 100001;
const SIGN_IN_WITH_PASSWORD_START = 100002;
const SIGN_IN_SUBMIT_CODE = 100003;
const SIGN_IN_SUBMIT_PASSWORD = 100004;
const SIGN_IN_RESEND_CODE = 100005;
const SIGN_IN_AFTER_SIGN_UP = 100006;
const SIGN_IN_AFTER_PASSWORD_RESET = 100007;
// Sign up
const SIGN_UP_WITH_PASSWORD_START = 100021;
const SIGN_UP_START = 100022;
const SIGN_UP_SUBMIT_CODE = 100023;
const SIGN_UP_SUBMIT_PASSWORD = 100024;
const SIGN_UP_SUBMIT_ATTRIBUTES = 100025;
const SIGN_UP_RESEND_CODE = 100026;
// Password reset
const PASSWORD_RESET_START = 100041;
const PASSWORD_RESET_SUBMIT_CODE = 100042;
const PASSWORD_RESET_SUBMIT_PASSWORD = 100043;
const PASSWORD_RESET_RESEND_CODE = 100044;
const ACCOUNT_GET_ACCESS_TOKEN = 100063;
// JIT (Just-In-Time) Auth Method Registration
const JIT_CHALLENGE_AUTH_METHOD = 100081;
const JIT_SUBMIT_CHALLENGE = 100082;
// MFA
const MFA_REQUEST_CHALLENGE = 100101;
const MFA_SUBMIT_CHALLENGE = 100102;
// Native Auth V2 (server-driven HAL flows) API Ids
const RESET_PASSWORD_V2_START = 100201;
const RESET_PASSWORD_V2_SUBMIT_CODE = 100202;
const RESET_PASSWORD_V2_RESEND_CODE = 100203;
const RESET_PASSWORD_V2_SUBMIT = 100204;
const RESET_PASSWORD_V2_CHALLENGE = 100205;
const SIGN_IN_V2_START = 100206;
const SIGN_IN_V2_CHALLENGE = 100207;
const SIGN_IN_V2_SUBMIT_PASSWORD = 100208;
const SIGN_IN_V2_COMPLETE = 100209;
const SIGN_IN_V2_SUBMIT_CODE = 100210;
const SIGN_UP_V2_START = 100211;
const SIGN_UP_V2_CHALLENGE = 100212;
const SIGN_UP_V2_SUBMIT_CODE = 100213;
const SIGN_UP_V2_SUBMIT_ATTRIBUTES = 100214;
const SIGN_UP_V2_RESEND_CODE = 100215;
const SIGN_UP_V2_COMPLETE = 100216;
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const SignInScenario = {
SignInAfterSignUp: "SignInAfterSignUp",
SignInAfterPasswordReset: "SignInAfterPasswordReset",
};
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class SignInClient extends CustomAuthInteractionClientBase {
/**
* Starts the signin flow.
* @param parameters The parameters required to start the sign-in flow.
* @returns The result of the sign-in start operation.
*/
async start(parameters) {
const correlationId = parameters.correlationId || this.correlationId;
const apiId = !parameters.password
? SIGN_IN_WITH_CODE_START
: SIGN_IN_WITH_PASSWORD_START;
const telemetryManager = initializeServerTelemetryManager(apiId, this.config.auth.clientId, correlationId, this.browserStorage, this.logger);
this.logger.verbose("1iuhun", correlationId);
const initReq = {
challenge_type: this.getChallengeTypes(parameters.challengeType),
username: parameters.username,
correlationId: correlationId,
telemetryManager: telemetryManager,
};
const initiateResponse = await this.customAuthApiClient.signInApi.initiate(initReq);
this.logger.verbose("1qs4yd", initiateResponse.correlation_id || correlationId);
const challengeReq = {
challenge_type: this.getChallengeTypes(parameters.challengeType),
continuation_token: initiateResponse.continuation_token ?? "",
correlationId: initiateResponse.correlation_id || correlationId,
telemetryManager: telemetryManager,
};
return this.performChallengeRequest(challengeReq);
}
/**
* Resends the code for sign-in flow.
* @param parameters The parameters required to resend the code.
* @returns The result of the sign-in resend code action.
*/
async resendCode(parameters) {
const correlationId = parameters.correlationId || this.correlationId;
const apiId = SIGN_IN_RESEND_CODE;
const telemetryManager = initializeServerTelemetryManager(apiId, this.config.auth.clientId, correlationId, this.browserStorage, this.logger);
const challengeReq = {
challenge_type: this.getChallengeTypes(parameters.challengeType),
continuation_token: parameters.continuationToken ?? "",
correlationId: correlationId,
telemetryManager: telemetryManager,
};
const result = await this.performChallengeRequest(challengeReq);
if (result.type === SIGN_IN_PASSWORD_REQUIRED_RESULT_TYPE) {
this.logger.error("0duqjg", result.correlationId || correlationId);
throw new CustomAuthApiError(UNSUPPORTED_CHALLENGE_TYPE, "Unsupported challenge type 'password'.", result.correlationId || correlationId);
}
return result;
}
/**
* Submits the code for sign-in flow.
* @param parameters The parameters required to submit the code.
* @returns The result of the sign-in submit code action.
*/
async submitCode(parameters) {
const correlationId = parameters.correlationId || this.correlationId;
ensureArgumentIsNotEmptyString("parameters.code", parameters.code, correlationId);
const apiId = SIGN_IN_SUBMIT_CODE;
const telemetryManager = initializeServerTelemetryManager(apiId, this.config.auth.clientId, correlationId, this.browserStorage, this.logger);
const scopes = this.getScopes(parameters.scopes);
const request = {
continuation_token: parameters.continuationToken,
oob: parameters.code,
grant_type: GrantType.OOB,
scope: scopes.join(" "),
correlationId: correlationId,
telemetryManager: telemetryManager,
...(parameters.claims && {
claims: parameters.claims,
}),
};
return this.performTokenRequest(() => this.customAuthApiClient.signInApi.requestTokensWithOob(request), scopes, correlationId, telemetryManager, apiId);
}
/**
* Submits the password for sign-in flow.
* @param parameters The parameters required to submit the password.
* @returns The result of the sign-in submit password action.
*/
async submitPassword(parameters) {
const correlationId = parameters.correlationId || this.correlationId;
ensureArgumentIsNotEmptyString("parameters.password", parameters.password, correlationId);
const apiId = SIGN_IN_SUBMIT_PASSWORD;
const telemetryManager = initializeServerTelemetryManager(apiId, this.config.auth.clientId, correlationId, this.browserStorage, this.logger);
const scopes = this.getScopes(parameters.scopes);
const request = {
continuation_token: parameters.continuationToken,
password: parameters.password,
scope: scopes.join(" "),
correlationId: correlationId,
telemetryManager: telemetryManager,
...(parameters.claims && {
claims: parameters.claims,
}),
};
return this.performTokenRequest(() => this.customAuthApiClient.signInApi.requestTokensWithPassword(request), scopes, correlationId, telemetryManager, apiId);
}
/**
* Signs in with continuation token.
* @param parameters The parameters required to sign in with continuation token.
* @returns The result of the sign-in complete action.
*/
async signInWithContinuationToken(parameters) {
const correlationId = parameters.correlationId || this.correlationId;
const apiId = this.getPublicApiIdBySignInScenario(parameters.signInScenario, correlationId);
const telemetryManager = initializeServerTelemetryManager(apiId, this.config.auth.clientId, correlationId, this.browserStorage, this.logger);
const scopes = this.getScopes(parameters.scopes);
// Create token request.
const request = {
continuation_token: parameters.continuationToken,
username: parameters.username,
correlationId: correlationId,
telemetryManager: telemetryManager,
scope: scopes.join(" "),
...(parameters.claims && {
claims: parameters.claims,
}),
};
// Call token endpoint.
return this.performTokenRequest(() => this.customAuthApiClient.signInApi.requestTokenWithContinuationToken(request), scopes, correlationId, telemetryManager, apiId);
}
/**
* Common method to handle token endpoint calls and create sign-in results.
* @param tokenEndpointCaller Function that calls the specific token endpoint
* @param scopes Scopes for the token request
* @param correlationId Correlation ID for logging and result
* @param telemetryManager Telemetry manager for telemetry logging
* @returns SignInCompletedResult | SignInJitRequiredResult | SignInMfaRequiredResult with authentication result
*/
async performTokenRequest(tokenEndpointCaller, scopes, correlationId, telemetryManager, apiId) {
this.logger.verbose("14tes8", correlationId);
try {
const tokenResponse = await tokenEndpointCaller();
this.logger.verbose("11zi01", tokenResponse.correlation_id || correlationId);
const authResult = await this.handleTokenResponse(tokenResponse, scopes, tokenResponse.correlation_id || correlationId, apiId);
return createSignInCompleteResult({
correlationId: tokenResponse.correlation_id || correlationId,
authenticationResult: authResult,
});
}
catch (error) {
if (error instanceof CustomAuthApiError &&
error.subError === REGISTRATION_REQUIRED) {
return this.handleJitRequiredError(error, telemetryManager, error.correlationId || correlationId);
}
else if (error instanceof CustomAuthApiError &&
error.subError === MFA_REQUIRED) {
return this.handleMfaRequiredError(error, telemetryManager, error.correlationId || correlationId);
}
// Re-throw any other errors or JIT errors when handleJit is false
throw error;
}
}
async performChallengeRequest(request) {
this.logger.verbose("0fr9br", request.correlationId);
const challengeResponse = await this.customAuthApiClient.signInApi.requestChallenge(request);
this.logger.verbose("083301", challengeResponse.correlation_id || request.correlationId);
if (challengeResponse.challenge_type === ChallengeType.OOB) {
// Code is required
this.logger.verbose("0m6hva", challengeResponse.correlation_id || request.correlationId);
return createSignInCodeSendResult({
correlationId: challengeResponse.correlation_id || request.correlationId,
continuationToken: challengeResponse.continuation_token ?? "",
challengeChannel: challengeResponse.challenge_channel ?? "",
challengeTargetLabel: challengeResponse.challenge_target_label ?? "",
codeLength: challengeResponse.code_length ??
DefaultCustomAuthApiCodeLength,
bindingMethod: challengeResponse.binding_method ?? "",
});
}
if (challengeResponse.challenge_type === ChallengeType.PASSWORD) {
// Password is required
this.logger.verbose("1xku2l", challengeResponse.correlation_id || request.correlationId);
return createSignInPasswordRequiredResult({
correlationId: challengeResponse.correlation_id || request.correlationId,
continuationToken: challengeResponse.continuation_token ?? "",
});
}
this.logger.error(`1tkddq ${challengeResponse.challenge_type}`, challengeResponse.correlation_id || request.correlationId);
throw new CustomAuthApiError(UNSUPPORTED_CHALLENGE_TYPE, `Unsupported challenge type '${challengeResponse.challenge_type}'.`, challengeResponse.correlation_id || request.correlationId);
}
getPublicApiIdBySignInScenario(scenario, correlationId) {
switch (scenario) {
case SignInScenario.SignInAfterSignUp:
return SIGN_IN_AFTER_SIGN_UP;
case SignInScenario.SignInAfterPasswordReset:
return SIGN_IN_AFTER_PASSWORD_RESET;
default:
throw new UnexpectedError(`Unsupported sign-in scenario '${scenario}'.`, correlationId);
}
}
async handleJitRequiredError(error, telemetryManager, correlationId) {
this.logger.verbose("0msz8y", correlationId);
// Call register introspect endpoint to get available authentication methods
const introspectRequest = {
continuation_token: error.continuationToken ?? "",
correlationId: correlationId,
telemetryManager,
};
this.logger.verbose("10zm99", correlationId);
const introspectResponse = await this.customAuthApiClient.registerApi.introspect(introspectRequest);
this.logger.verbose("1j7fgr", introspectResponse.correlation_id || correlationId);
return createSignInJitRequiredResult({
correlationId: introspectResponse.correlation_id || correlationId,
continuationToken: introspectResponse.continuation_token ?? "",
authMethods: introspectResponse.methods,
});
}
async handleMfaRequiredError(error, telemetryManager, correlationId) {
this.logger.verbose("19uxoc", correlationId);
// Call sign-in introspect endpoint to get available MFA methods
const introspectRequest = {
continuation_token: error.continuationToken ?? "",
correlationId: correlationId,
telemetryManager,
};
this.logger.verbose("0pqpya", correlationId);
const introspectResponse = await this.customAuthApiClient.signInApi.requestAuthMethods(introspectRequest);
this.logger.verbose("1ysax9", introspectResponse.correlation_id || correlationId);
return createSignInMfaRequiredResult({
correlationId: introspectResponse.correlation_id || correlationId,
continuationToken: introspectResponse.continuation_token ?? "",
authMethods: introspectResponse.methods,
});
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* The completed state of the sign-out flow.
*/
class SignOutCompletedState extends AuthFlowStateBase {
constructor() {
super(...arguments);
/**
* The type of the state.
*/
this.stateType = SIGN_OUT_COMPLETED_STATE_TYPE;
}
}
/**
* The failed state of the sign-out flow.
*/
class SignOutFailedState extends AuthFlowStateBase {
constructor() {
super(...arguments);
/**
* The type of the state.
*/
this.stateType = SIGN_OUT_FAILED_STATE_TYPE;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Result of a sign-out operation.
*/
class SignOutResult extends AuthFlowResultBase {
/**
* Creates a new instance of SignOutResult.
* @param state The state of the result.
*/
constructor() {
super(new SignOutCompletedState());
}
/**
* Creates a new instance of SignOutResult with an error.
* @param error The error that occurred during the sign-out operation.
*/
static createWithError(error) {
const result = new SignOutResult();
result.error = new SignOutError(SignOutResult.createErrorData(error));
result.state = new SignOutFailedState();
return result;
}
/**
* Checks if the sign-out operation is completed.
*/
isCompleted() {
return this.state.stateType === SIGN_OUT_COMPLETED_STATE_TYPE;
}
/**
* Checks if the sign-out operation failed.
*/
isFailed() {
return this.state.stateType === SIGN_OUT_FAILED_STATE_TYPE;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* The completed state of the get access token flow.
*/
class GetAccessTokenCompletedState extends AuthFlowStateBase {
constructor() {
super(...arguments);
/**
* The type of the state.
*/
this.stateType = GET_ACCESS_TOKEN_COMPLETED_STATE_TYPE;
}
}
/**
* The failed state of the get access token flow.
*/
class GetAccessTokenFailedState extends AuthFlowStateBase {
constructor() {
super(...arguments);
/**
* The type of the state.
*/
this.stateType = GET_ACCESS_TOKEN_FAILED_STATE_TYPE;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Result of getting an access token.
*/
class GetAccessTokenResult extends AuthFlowResultBase {
/**
* Creates a new instance of GetAccessTokenResult.
* @param resultData The result data of the access token.
*/
constructor(resultData) {
super(new GetAccessTokenCompletedState(), resultData);
}
/**
* Creates a new instance of GetAccessTokenResult with an error.
* @param error The error that occurred.
* @return {GetAccessTokenResult} The result with the error.
*/
static createWithError(error) {
const result = new GetAccessTokenResult();
result.error = new GetCurrentAccountAccessTokenError(GetAccessTokenResult.createErrorData(error));
result.state = new GetAccessTokenFailedState();
return result;
}
/**
* Checks if the result is completed.
*/
isCompleted() {
return this.state.stateType === GET_ACCESS_TOKEN_COMPLETED_STATE_TYPE;
}
/**
* Checks if the result is failed.
*/
isFailed() {
return this.state.stateType === GET_ACCESS_TOKEN_FAILED_STATE_TYPE;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Account information.
*/
class CustomAuthAccountData {
constructor(account, config, cacheClient, logger, correlationId) {
this.account = account;
this.config = config;
this.cacheClient = cacheClient;
this.logger = logger;
this.correlationId = correlationId;
ensureArgumentIsNotEmptyString("correlationId", correlationId);
ensureArgumentIsNotNullOrUndefined("account", account, correlationId);
}
/**
* This method triggers a sign-out operation,
* which removes the current account info and its tokens from browser cache.
* If sign-out successfully, redirect the page to postLogoutRedirectUri if provided in the configuration.
* @returns {Promise<SignOutResult>} The result of the SignOut operation.
*/
async signOut() {
try {
const currentAccount = this.cacheClient.getCurrentAccount(this.correlationId);
if (!currentAccount) {
throw new NoCachedAccountFoundError(this.correlationId);
}
this.logger.verbose("17l5fh", this.correlationId);
await this.cacheClient.logout({
correlationId: this.correlationId,
account: currentAccount,
});
this.logger.verbose("16o7ps", this.correlationId);
return new SignOutResult();
}
catch (error) {
this.logger.errorPii(`19tou7 ${error}`, this.correlationId);
return SignOutResult.createWithError(error);
}
}
getAccount() {
return this.account;
}
/**
* Gets the raw id-token of current account.
* Idtoken is only issued if openid scope is present in the scopes parameter when requesting for tokens,
* otherwise will return undefined from the response.
* @returns {string|undefined} The account id-token.
*/
getIdToken() {
return this.account.idToken;
}
/**
* Gets the id token claims extracted from raw IdToken of current account.
* @returns {AuthTokenClaims|undefined} The token claims.
*/
getClaims() {
return this.account.idTokenClaims;
}
/**
* Gets the access token of current account from browser cache if it is not expired,
* otherwise renew the token using cached refresh token if valid.
* If no refresh token is found or it is expired, then throws error.
* @param {AccessTokenRetrievalInputs} accessTokenRetrievalInputs - The inputs for retrieving the access token.
* @returns {Promise<GetAccessTokenResult>} The result of the operation.
*/
async getAccessToken(accessTokenRetrievalInputs) {
try {
ensureArgumentIsNotNullOrUndefined("accessTokenRetrievalInputs", accessTokenRetrievalInputs, this.correlationId);
if (accessTokenRetrievalInputs.claims) {
ensureArgumentIsJSONString("accessTokenRetrievalInputs.claims", accessTokenRetrievalInputs.claims, this.correlationId);
}
this.logger.verbose("0jrcu2", this.correlationId);
const currentAccount = this.cacheClient.getCurrentAccount(this.account.username);
if (!currentAccount) {
throw new NoCachedAccountFoundError(this.correlationId);
}
this.logger.verbose("108lch", this.correlationId);
const newScopes = accessTokenRetrievalInputs.scopes &&
accessTokenRetrievalInputs.scopes.length > 0
? accessTokenRetrievalInputs.scopes
: [...DefaultScopes];
const commonSilentFlowRequest = this.createCommonSilentFlowRequest(currentAccount, accessTokenRetrievalInputs.forceRefresh, newScopes, accessTokenRetrievalInputs.claims);
const result = await this.cacheClient.acquireToken(commonSilentFlowRequest);
this.logger.verbose("1w15hv", this.correlationId);
return new GetAccessTokenResult(result);
}
catch (error) {
this.logger.error("0yfud8", this.correlationId);
return GetAccessTokenResult.createWithError(error);
}
}
createCommonSilentFlowRequest(accountInfo, forceRefresh = false, requestScopes, claims) {
const silentRequest = {
authority: this.config.auth.authority,
correlationId: this.correlationId,
scopes: requestScopes || [],
account: accountInfo,
forceRefresh: forceRefresh || false,
storeInCache: {
idToken: true,
accessToken: true,
refreshToken: true,
},
...(claims && { claims: claims }),
};
return {
...silentRequest,
authenticationScheme: AuthenticationScheme.BEARER,
};
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class ResetPasswordError extends AuthActionErrorBase {
/**
* Checks if the error is due to the user not being found.
* @returns true if the error is due to the user not being found, false otherwise.
*/
isUserNotFound() {
return this.isUserNotFoundError();
}
/**
* Checks if the error is due to the username being invalid.
* @returns true if the error is due to the username being invalid, false otherwise.
*/
isInvalidUsername() {
return this.isUserInvalidError();
}
/**
* Checks if the error is due to the provided challenge type is not supported.
* @returns {boolean} True if the error is due to the provided challenge type is not supported, false otherwise.
*/
isUnsupportedChallengeType() {
return this.isUnsupportedChallengeTypeError();
}
}
class ResetPasswordSubmitPasswordError extends AuthActionErrorBase {
/**
* Checks if the new password is invalid or incorrect.
* @returns {boolean} True if the new password is invalid, false otherwise.
*/
isInvalidPassword() {
return (this.isInvalidNewPasswordError() || this.isPasswordIncorrectError());
}
/**
* Checks if the password reset failed due to reset timeout or password change failed.
* @returns {boolean} True if the password reset failed, false otherwise.
*/
isPasswordResetFailed() {
return (this.errorData instanceof CustomAuthApiError &&
(this.errorData.error ===
PASSWORD_RESET_TIMEOUT ||
this.errorData.error ===
PASSWORD_CHANGE_FAILED));
}
}
class ResetPasswordSubmitCodeError extends AuthActionErrorBase {
/**
* Checks if the provided code is invalid.
* @returns {boolean} True if the provided code is invalid, false otherwise.
*/
isInvalidCode() {
return this.isInvalidCodeError();
}
}
class ResetPasswordResendCodeError extends AuthActionErrorBase {
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* State of a reset password operation that has failed.
*/
class ResetPasswordFailedState extends AuthFlowStateBase {
constructor() {
super(...arguments);
/**
* The type of the state.
*/
this.stateType = RESET_PASSWORD_FAILED_STATE_TYPE;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Result of a reset password operation.
*/
class ResetPasswordStartResult extends AuthFlowResultBase {
/**
* Creates a new instance of ResetPasswordStartResult.
* @param state The state of the result.
*/
constructor(state) {
super(state);
}
/**
* Creates a new instance of ResetPasswordStartResult with an error.
* @param error The error that occurred.
* @returns {ResetPasswordStartResult} A new instance of ResetPasswordStartResult with the error set.
*/
static createWithError(error) {
const result = new ResetPasswordStartResult(new ResetPasswordFailedState());
result.error = new ResetPasswordError(ResetPasswordStartResult.createErrorData(error));
return result;
}
/**
* Checks if the result is in a failed state.
*/
isFailed() {
return this.state.stateType === RESET_PASSWORD_FAILED_STATE_TYPE;
}
/**
* Checks if the result is in a code required state.
*/
isCodeRequired() {
return this.state.stateType === RESET_PASSWORD_CODE_REQUIRED_STATE_TYPE;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Represents an HTTP method type.
*/
const HttpMethod = {
GET: "GET",
POST: "POST",
PUT: "PUT"};
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class ParsedUrlError extends CustomAuthError {
constructor(error, message, correlationId) {
super(error, message, correlationId);
Object.setPrototypeOf(this, ParsedUrlError.prototype);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const InvalidUrl = "invalid_url";
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
function parseUrl(url) {
try {
return new URL(url);
}
catch (e) {
throw new ParsedUrlError(InvalidUrl, `The URL "${url}" is invalid: ${e}`);
}
}
function buildUrl(baseUrl, path, queryParams) {
const newBaseUrl = !baseUrl.endsWith("/") ? `${baseUrl}/` : baseUrl;
const newPath = path.startsWith("/") ? path.slice(1) : path;
const url = new URL(newPath, newBaseUrl);
// Add query parameters if provided
if (queryParams) {
Object.entries(queryParams).forEach(([key, value]) => {
if (value !== undefined && value !== null) {
url.searchParams.set(key, String(value));
}
});
}
return url;
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Filters the headers returned by a {@link CustomAuthRequestInterceptor},
* keeping only those that conform to the custom-auth header naming rules.
*
* Rules (mirrors the iOS / Android native auth implementations):
* - Header names must start with `x-` (case-insensitive); others are dropped.
* - Header names that start with any reserved prefix (`x-client-`, `x-ms-`,
* `x-broker-`, `x-app-`) are dropped.
* - Headers with empty/whitespace-only names or null/undefined values are dropped.
*
* Dropped headers are logged as warnings (PII-safe) when a logger is provided.
*
* @param headers - Raw headers returned by the interceptor.
* @param logger - Optional logger used to emit warnings for dropped headers.
* @param correlationId - Optional correlation id forwarded to the logger.
* @returns A new record containing only the headers that pass the filter,
* preserving the original casing of header names.
*/
function filterCustomHeaders(headers, logger, correlationId) {
const filtered = {};
if (!headers) {
return filtered;
}
for (const [name, value] of Object.entries(headers)) {
if (!name || value === undefined || value === null) {
continue;
}
const trimmedName = name.trim();
if (!trimmedName) {
continue;
}
const lowerName = trimmedName.toLowerCase();
if (!lowerName.startsWith(CustomHeaderConstants.REQUIRED_PREFIX)) {
logger?.warningPii(`0vzpop ${trimmedName} ${CustomHeaderConstants.REQUIRED_PREFIX}`, correlationId ?? "");
continue;
}
const reservedPrefix = CustomHeaderConstants.RESERVED_PREFIXES.find((prefix) => lowerName.startsWith(prefix));
if (reservedPrefix) {
logger?.warningPii(`1m3lhk ${trimmedName} ${reservedPrefix}`, correlationId ?? "");
continue;
}
filtered[trimmedName] = value;
}
return filtered;
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const HTTP_REQUEST_FAILED = "http_request_failed";
const REDIRECT_TO_WEB = "redirect_to_web";
const UNEXPECTED_ERROR = "unexpected_error";
const AUTH_CODE_MISSING = "authorization_code_missing";
const INVALID_TOKEN_RESPONSE = "invalid_token_response";
const INVALID_RESPONSE_BODY = "invalid_response_body";
const CONTINUATION_TOKEN_MISSING = "continuation_token_missing";
const INVALID_HAL_RESPONSE = "invalid_hal_response";
const RESET_PASSWORD_UNSUPPORTED = "reset_password_unsupported";
const SIGN_IN_UNSUPPORTED = "sign_in_unsupported";
const SIGN_UP_UNSUPPORTED = "sign_up_unsupported";
const CONTINUATION_LINK_MISSING = "continuation_link_missing";
const RESET_PASSWORD_TIMEOUT = "reset_password_timeout";
const UNSUPPORTED_FLOW_STEP = "unsupported_flow_step";
const UNSUPPORTED_FLOW_TRANSITION = "unsupported_flow_transition";
const NO_AUTHENTICATION_METHODS = "no_authentication_methods";
const UNEXPECTED_AUTHENTICATION_FACTOR = "unexpected_authentication_factor";
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Normalizes nested HAL and flat OAuth error bodies into a `ServerErrorV2`.
* Returns `undefined` when the response contains no recognized error.
*/
function normalizeServerErrorV2(body) {
const error = body.error;
if (error && typeof error === "object") {
return normalizeHalError(body);
}
if (typeof error === "string") {
return normalizeOAuthError(body);
}
return undefined;
}
function normalizeHalError(response) {
const error = response.error ?? {};
return {
code: readString(error.code) ?? UNEXPECTED_ERROR,
message: readString(error.message),
innerErrorCode: readString(error.innerError?.code),
attributeValidationDetails: error.innerError?.details,
correlationId: readString(error.correlationId),
traceId: readString(error.traceId),
timestamp: readString(error.timestamp),
};
}
function normalizeOAuthError(response) {
return {
code: readString(response.error) ?? UNEXPECTED_ERROR,
message: readString(response.error_description),
errorCodes: readNumberArray(response.error_codes),
correlationId: readString(response.correlation_id),
traceId: readString(response.trace_id),
timestamp: readString(response.timestamp),
};
}
function readString(value) {
return typeof value === "string" ? value : undefined;
}
function readNumberArray(value) {
if (Array.isArray(value) && value.every((v) => typeof v === "number")) {
return value;
}
return undefined;
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
// Content type used by V2 JSON `/api` requests.
const JSON_CONTENT_TYPE = "application/json";
// Server action returned after successful credential verification.
const UPDATE_RELATION = "update";
const CHALLENGE_RELATION = "challenge";
const VERIFY_RELATION = "verify";
const RISK_VERIFY_RELATION = "riskverify";
const COLLECT_ATTRIBUTES_RELATION = "collectAttributes";
const AuthenticationMethodTypeV2 = {
EMAIL: "email",
PASSWORD: "password",
SMS: "sms",
};
/*
* Known `state` values on a HAL response. Kept open (the body field is typed as string) because
* the server may introduce new values; response parsing and flow logic branch on these constants.
*/
const ResponseStateV2 = {
CONTINUE: "continue",
WEB_FALLBACK_REQUIRED: "webFallbackRequired",
};
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Turns a raw HTTP response from a V2 endpoint into a typed, checked envelope, and validates HAL
* relations. Raw-preserving: the body keeps its HAL `_links`/`_embedded` shape so the api-client
* navigates typed hrefs directly. Parsing never throws on a non-200 status - every V2 response
* (including the entry response) carries a meaningful body, so only a non-object body is a hard
* failure; the wire error is normalized onto the envelope (`error`). Required response values use
* shared guards after callers read their strongly typed response properties directly.
*/
class ResponseHandlerV2 {
constructor(logger) {
this.logger = logger;
}
async parseResponse(response, requestCorrelationId) {
const correlationId = response.headers.get(HttpHeaderKeys.X_MS_REQUEST_ID) ??
requestCorrelationId;
const json = await this.parseBody(response, correlationId);
const state = typeof json.state === "string" ? json.state : undefined;
const continuationToken = (typeof json.continuationToken === "string"
? json.continuationToken
: undefined) ??
(typeof json.continuation_token === "string"
? json.continuation_token
: undefined);
const flatError = typeof json.error === "string" ? json.error : undefined;
const isWebFallbackRequired = flatError === REDIRECT_TO_WEB ||
state === ResponseStateV2.WEB_FALLBACK_REQUIRED;
const error = normalizeServerErrorV2(json);
// Surface the header correlation id on the body (HalResponseBaseV2.correlationId).
json.correlationId = correlationId;
return {
statusCode: response.status,
correlationId,
continuationToken,
isWebFallbackRequired,
error,
body: json,
};
}
// Required href; throws when it is absent.
requireHref(href, relation, correlationId, missingHrefError) {
if (!href) {
const errorCode = missingHrefError?.code ?? INVALID_HAL_RESPONSE;
const errorMessage = missingHrefError?.message ??
`Invalid HAL response: missing '${relation}' link`;
this.logger?.error(errorMessage, correlationId);
throw new CustomAuthApiError(errorCode, errorMessage, correlationId);
}
return href;
}
// Required continuation token to advance the flow; throws when absent.
requireContinuationToken(continuationToken, correlationId) {
if (!continuationToken) {
this.logger?.error("0a3z6v", correlationId);
throw new CustomAuthApiError(CONTINUATION_TOKEN_MISSING, "Continuation token is missing in the response", correlationId);
}
return continuationToken;
}
// Required embedded auth methods; throws when `_embedded.methods` is absent or empty.
requireMethods(methods, correlationId) {
if (!methods?.length) {
this.logger?.error("0u0cak", correlationId);
throw new CustomAuthApiError(NO_AUTHENTICATION_METHODS, "Invalid HAL response: no embedded authentication methods", correlationId);
}
return methods;
}
async parseBody(response, correlationId) {
let json;
try {
json = await response.json();
}
catch (e) {
this.logger?.error("0fc89v", correlationId);
throw new CustomAuthApiError(INVALID_RESPONSE_BODY, `V2 response body is not valid JSON: '${e}'`, correlationId);
}
// response.json() accepts primitives/arrays; every V2 body must be a JSON object.
if (typeof json !== "object" || json === null || Array.isArray(json)) {
this.logger?.error("09w4yw", correlationId);
throw new CustomAuthApiError(INVALID_RESPONSE_BODY, "V2 response body is not a JSON object", correlationId);
}
return json;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const API_MARKERS = ["/api/", "/oauth2/"];
/*
* Resolves a HAL href against the configured authority. Absolute HTTP(S) URLs
* pass through; relative URLs retain their API path and query while using the
* configured tenant path.
*
* TODO: Remove tenant-path rewriting once the service consistently returns links that can be
* resolved directly against the configured authority.
*/
function resolveHrefV2(base, href) {
const trimmed = href.trim();
if (!trimmed) {
throw new ParsedUrlError(InvalidUrl, "The HAL href cannot be empty");
}
const absolute = tryParseAbsolute(trimmed);
if (absolute) {
return absolute;
}
let resolved;
try {
resolved = new URL(trimmed, base.origin);
}
catch (e) {
throw new ParsedUrlError(InvalidUrl, `The HAL href "${href}" could not be resolved: ${e}`);
}
if (resolved.protocol !== "http:" && resolved.protocol !== "https:") {
throw new ParsedUrlError(InvalidUrl, `The HAL href "${href}" must use the HTTP or HTTPS protocol`);
}
const tenantPath = base.pathname.endsWith("/")
? base.pathname.slice(0, -1)
: base.pathname;
resolved.pathname = tenantPath + apiPath(resolved.pathname);
return resolved;
}
function tryParseAbsolute(href) {
try {
const url = new URL(href);
return url.protocol === "http:" || url.protocol === "https:"
? url
: undefined;
}
catch {
return undefined;
}
}
function apiPath(path) {
for (const marker of API_MARKERS) {
const index = path.indexOf(marker);
if (index >= 0) {
return path.slice(index);
}
}
return path.startsWith("/") ? path : `/${path}`;
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const SIGNIN_INITIATE = "/oauth2/v2.0/initiate";
const SIGNIN_CHALLENGE = "/oauth2/v2.0/challenge";
const SIGNIN_TOKEN = "/oauth2/v2.0/token";
const SIGNIN_INTROSPECT = "/oauth2/v2.0/introspect";
const AUTHORIZE_CHALLENGE = "/oauth2/v2.0/authorize-challenge";
const SIGNUP_START = "/signup/v1.0/start";
const SIGNUP_CHALLENGE = "/signup/v1.0/challenge";
const SIGNUP_CONTINUE = "/signup/v1.0/continue";
const RESET_PWD_START = "/resetpassword/v1.0/start";
const RESET_PWD_CHALLENGE = "/resetpassword/v1.0/challenge";
const RESET_PWD_CONTINUE = "/resetpassword/v1.0/continue";
const RESET_PWD_SUBMIT = "/resetpassword/v1.0/submit";
const RESET_PWD_POLL = "/resetpassword/v1.0/poll_completion";
const REGISTER_INTROSPECT = "/register/v1.0/introspect";
const REGISTER_CHALLENGE = "/register/v1.0/challenge";
const REGISTER_CONTINUE = "/register/v1.0/continue";
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Shared Native Auth V2 network client for OAuth and HAL requests.
* Handles serialization, headers, error normalization, and server-provided links.
*/
class BaseApiClientV2 {
constructor(baseUrl, clientId, httpClient, customAuthApiQueryParams, requestInterceptor, logger) {
this.clientId = clientId;
this.httpClient = httpClient;
this.customAuthApiQueryParams = customAuthApiQueryParams;
this.requestInterceptor = requestInterceptor;
this.logger = logger;
this.baseRequestUrl = parseUrl(!baseUrl.endsWith("/") ? `${baseUrl}/` : baseUrl);
this.handler = new ResponseHandlerV2(logger);
}
/*
* Starts authorization and returns the initial continuation token and flow links.
*/
async authorizeChallengeStart(context, scopes) {
const request = {
client_id: this.clientId,
};
if (scopes?.length) {
request.scope = scopes.join(" ");
}
const parsedResponse = await this.postOAuthForm(AUTHORIZE_CHALLENGE, request, context);
const { continuationToken, correlationId, error, body } = parsedResponse;
/*
* No token means a genuine server error: surface the normalized server error directly. The
* fallback code/message only applies to a malformed response that carries neither a token
* nor an error.
*/
if (!continuationToken) {
const apiError = error
? this.toApiError(error, correlationId)
: new CustomAuthApiError(CONTINUATION_TOKEN_MISSING, "Continuation token is missing in the response", correlationId);
this.logger?.error(`15sfif ${apiError.error}`, correlationId);
throw apiError;
}
return {
continuationToken,
resetPasswordHref: body.reset_password,
signInHref: body.sign_in,
signUpHref: body.sign_up,
};
}
/*
* Redeems a continuation token for an authorization code and then tokens.
*/
async completeWithTokens(request, context) {
const code = await this.authorizeChallengeContinue(request.continuationToken, context);
return this.token(code, request.scopes, context);
}
/*
* Redeems a continuation token for an authorization code.
*/
async authorizeChallengeContinue(continuationToken, context) {
const request = {
continuation_token: continuationToken,
};
const parsedResponse = await this.postOAuthForm(AUTHORIZE_CHALLENGE, request, context);
this.throwOnApiError(parsedResponse);
const code = parsedResponse.body.code;
if (!code) {
this.logger?.error("0hzeol", parsedResponse.correlationId);
throw new CustomAuthApiError(AUTH_CODE_MISSING, "Authorization code is missing in the response body", parsedResponse.correlationId);
}
return code;
}
/*
* Exchanges an authorization code for tokens.
*/
async token(code, scopes, context) {
const request = {
client_id: this.clientId,
grant_type: GrantType$1.AUTHORIZATION_CODE_GRANT,
code,
// Required so the server returns the client_info blob MSAL uses to build the home account id.
client_info: "1",
};
if (scopes.length > 0) {
request.scope = scopes.join(" ");
}
const parsedResponse = await this.postOAuthForm(SIGNIN_TOKEN, request, context);
this.throwOnApiError(parsedResponse);
this.ensureTokenResponseIsValid(parsedResponse.body, parsedResponse.correlationId);
return parsedResponse.body;
}
/*
* Sends a JSON action request to a server-provided link.
*/
async sendActionRequest(href, method, body, context) {
if (!body.continuationToken) {
this.logger?.error("1wtzk1", context.correlationId);
throw new CustomAuthApiError(CONTINUATION_TOKEN_MISSING, "The HAL request body did not include a continuation token, so the server-driven reset flow cannot advance", context.correlationId);
}
const url = resolveHrefV2(this.baseRequestUrl, href);
const response = await this.sendRequest(url, method, JSON.stringify(body), JSON_CONTENT_TYPE, context);
const parsedResponse = await this.handler.parseResponse(response, context.correlationId);
this.throwOnWebFallback(parsedResponse);
this.throwOnApiError(parsedResponse);
return parsedResponse;
}
throwOnApiError(parsedResponse) {
if (parsedResponse.error) {
const apiError = this.toApiError(parsedResponse.error, parsedResponse.correlationId);
this.logger?.error(`0u4c13 ${apiError.error}`, parsedResponse.correlationId);
throw apiError;
}
}
async postOAuthForm(endpoint, data, context) {
const formData = new URLSearchParams(Object.entries(data));
const url = buildUrl(this.baseRequestUrl.href, endpoint, this.customAuthApiQueryParams);
const response = await this.sendRequest(url, HttpMethod.POST, formData, URL_FORM_CONTENT_TYPE, context);
const parsedResponse = await this.handler.parseResponse(response, context.correlationId);
this.throwOnWebFallback(parsedResponse);
return parsedResponse;
}
async sendRequest(url, method, body, contentType, context) {
const headers = {
...this.getCommonHeaders(context.correlationId, context.telemetryManager, contentType),
...(await this.getAdditionalHeaders(url, context.correlationId)),
};
try {
return await this.httpClient.sendAsync(url, {
method,
body,
headers,
});
}
catch (e) {
throw new CustomAuthApiError(HTTP_REQUEST_FAILED, `Failed to send request to '${url}': '${e}'`, context.correlationId);
}
}
toApiError(serverError, correlationId) {
return new CustomAuthApiError(serverError.code, serverError.message ?? "", serverError.correlationId ?? correlationId, serverError.errorCodes, serverError.innerErrorCode, undefined, undefined, serverError.traceId, serverError.timestamp, serverError.attributeValidationDetails);
}
throwOnWebFallback(parsedResponse) {
if (parsedResponse.isWebFallbackRequired) {
throw new CustomAuthApiError(REDIRECT_TO_WEB, "The server requires the flow to continue in a web browser", parsedResponse.correlationId);
}
}
ensureTokenResponseIsValid(tokenResponse, correlationId) {
if (!tokenResponse.access_token) {
throw new CustomAuthApiError(INVALID_TOKEN_RESPONSE, "Access token is missing in the response body", correlationId);
}
}
getCommonHeaders(correlationId, telemetryManager, contentType) {
return {
[HttpHeaderKeys.CONTENT_TYPE]: contentType,
[X_CLIENT_SKU]: DefaultPackageInfo.SKU,
[X_CLIENT_VER]: DefaultPackageInfo.VERSION,
[X_CLIENT_OS]: DefaultPackageInfo.OS,
[X_CLIENT_CPU]: DefaultPackageInfo.CPU,
[X_CLIENT_CURR_TELEM]: telemetryManager.generateCurrentRequestHeaderValue(),
[X_CLIENT_LAST_TELEM]: telemetryManager.generateLastRequestHeaderValue(),
[CLIENT_REQUEST_ID]: correlationId,
};
}
async getAdditionalHeaders(url, correlationId) {
if (!this.requestInterceptor) {
return {};
}
try {
const result = await Promise.resolve(this.requestInterceptor.addAdditionalHeaderFields(url));
return filterCustomHeaders(result, this.logger, correlationId);
}
catch (e) {
this.logger?.warningPii(`1x9eyr ${e}`, correlationId);
return {};
}
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const AuthenticationFactorV2 = {
SINGLE_FACTOR: "singleFactor",
MULTI_FACTOR: "multiFactor",
};
const ChallengeNextActionV2 = {
VERIFY: "verify",
RISK_VERIFY: "riskVerify",
};
const VerifyNextActionV2 = {
UPDATE: "update",
CONTINUE: "continue",
CHALLENGE: "challenge",
COLLECT_ATTRIBUTES: "collectAttributes",
};
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const SignUpSubmitAttributesNextActionV2 = {
VERIFY: "verify",
COLLECT_ATTRIBUTES: "collectAttributes",
CONTINUE: "continue",
};
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Native Auth V2 network client that follows server-provided HAL links.
* Flow-specific entry methods reuse shared challenge, verification, and token operations.
*/
class CustomAuthApiClientV2 extends BaseApiClientV2 {
/*
* Starts the reset-password flow using a server-provided link.
*/
async resetPasswordStart(resetPasswordHref, request, context) {
return this.sendStartRequest(resetPasswordHref, request, context);
}
/*
* Starts sign-in using a server-provided link.
*/
async signInStart(signInHref, request, context) {
const result = await this.sendStartRequest(signInHref, request, context);
return result;
}
/*
* Starts sign-up using a server-provided link.
*/
async signUpStart(signUpHref, request, context) {
const parsedResponse = await this.sendActionRequest(signUpHref, HttpMethod.POST, request, context);
return {
continuationToken: this.handler.requireContinuationToken(parsedResponse.continuationToken, parsedResponse.correlationId),
submitAttributesHref: this.handler.requireHref(parsedResponse.body._links?.submitAttributes?.href, "submitAttributes", parsedResponse.correlationId),
attributes: parsedResponse.body.attributes,
};
}
/*
* Submits the initial sign-up attributes. A successful response has already
* sent the email code and supplies the links needed to verify or resend it.
*/
async submitSignUpAttributes(submitAttributesHref, request, context) {
const parsedResponse = await this.sendActionRequest(submitAttributesHref, HttpMethod.POST, request, context);
const correlationId = parsedResponse.correlationId;
const continuationToken = this.handler.requireContinuationToken(parsedResponse.continuationToken, correlationId);
if (parsedResponse.body.state === ResponseStateV2.CONTINUE) {
return {
nextAction: SignUpSubmitAttributesNextActionV2.CONTINUE,
continuationToken,
};
}
if (parsedResponse.body.action === COLLECT_ATTRIBUTES_RELATION) {
return {
nextAction: SignUpSubmitAttributesNextActionV2.COLLECT_ATTRIBUTES,
continuationToken,
attributes: parsedResponse.body.attributes ?? [],
submitAttributesHref: this.handler.requireHref(parsedResponse.body._links?.submitAttributes?.href, "submitAttributes", correlationId),
};
}
if (parsedResponse.body.action === VERIFY_RELATION) {
return {
...this.toChallengeVerificationResult(parsedResponse),
attributes: parsedResponse.body.attributes,
};
}
const message = "Invalid HAL response: sign-up attribute submission returned no known next action";
this.logger?.error(message, correlationId);
throw new CustomAuthApiError(INVALID_HAL_RESPONSE, message, correlationId);
}
/*
* Requests the selected method's challenge and returns the data needed for verification.
*/
async requestChallenge(challengeHref, request, context) {
const parsedResponse = await this.sendActionRequest(challengeHref, HttpMethod.POST, request, context);
return this.toChallengeResult(parsedResponse);
}
async verifyRisk(riskVerifyHref, request, context) {
const parsedResponse = await this.sendActionRequest(riskVerifyHref, HttpMethod.POST, request, context);
if (parsedResponse.body.action !== VERIFY_RELATION) {
throw new CustomAuthApiError(INVALID_HAL_RESPONSE, "Invalid HAL response: SMS risk verification returned no known next action", parsedResponse.correlationId);
}
if (parsedResponse.body.type?.toLowerCase() !==
AuthenticationMethodTypeV2.SMS) {
throw new CustomAuthApiError(INVALID_HAL_RESPONSE, "Invalid HAL response: SMS risk verification returned a non-SMS challenge", parsedResponse.correlationId);
}
return this.toChallengeVerificationResult(parsedResponse);
}
/*
* Verifies the submitted credential and returns the server-directed next action.
*/
async verifyChallenge(verifyHref, request, context) {
const parsedResponse = await this.sendActionRequest(verifyHref, HttpMethod.POST, request, context);
return this.toVerifyResult(parsedResponse);
}
/*
* Submits the new password and returns the link used to poll for completion.
*/
async submitNewPassword(updateHref, request, context) {
const parsedResponse = await this.sendActionRequest(updateHref, HttpMethod.PUT, request, context);
const nextContinuationToken = this.handler.requireContinuationToken(parsedResponse.continuationToken, parsedResponse.correlationId);
return {
continuationToken: nextContinuationToken,
pollHref: this.handler.requireHref(parsedResponse.body._links?.poll?.href, "poll", parsedResponse.correlationId),
};
}
/*
* Polls once for reset completion and returns the next server-provided link.
*/
async poll(pollHref, request, context) {
const parsedResponse = await this.sendActionRequest(pollHref, HttpMethod.POST, request, context);
const isCompleted = parsedResponse.body.state === ResponseStateV2.CONTINUE;
return {
continuationToken: parsedResponse.continuationToken ?? request.continuationToken,
isCompleted,
pollHref: isCompleted
? undefined
: this.handler.requireHref(parsedResponse.body._links?.poll?.href, "poll", parsedResponse.correlationId),
};
}
async sendStartRequest(startHref, request, context) {
const parsedResponse = await this.sendActionRequest(startHref, HttpMethod.POST, request, context);
const continuationToken = this.handler.requireContinuationToken(parsedResponse.continuationToken, parsedResponse.correlationId);
return {
continuationToken,
methods: this.resolveMethods(parsedResponse.body, parsedResponse.correlationId),
authenticationFactor: this.resolveAuthenticationFactor(parsedResponse.body.challengeContext?.authenticationFactor, parsedResponse.correlationId),
scenario: parsedResponse.body.scenario,
};
}
toVerifyResult(parsedResponse) {
const correlationId = parsedResponse.correlationId;
const continuationToken = this.handler.requireContinuationToken(parsedResponse.continuationToken, correlationId);
if (parsedResponse.body.state === ResponseStateV2.CONTINUE) {
return {
nextAction: VerifyNextActionV2.CONTINUE,
continuationToken,
};
}
if (parsedResponse.body.action === COLLECT_ATTRIBUTES_RELATION) {
return {
nextAction: VerifyNextActionV2.COLLECT_ATTRIBUTES,
continuationToken,
attributes: parsedResponse.body.attributes ?? [],
submitAttributesHref: this.handler.requireHref(parsedResponse.body._links?.submitAttributes?.href, "submitAttributes", correlationId),
};
}
if (parsedResponse.body.action === UPDATE_RELATION) {
return {
nextAction: VerifyNextActionV2.UPDATE,
continuationToken,
updateHref: this.handler.requireHref(parsedResponse.body._links?.update?.href, "update", correlationId),
};
}
if (parsedResponse.body.action === CHALLENGE_RELATION) {
return {
nextAction: VerifyNextActionV2.CHALLENGE,
continuationToken,
authenticationFactor: this.resolveAuthenticationFactor(parsedResponse.body.challengeContext?.authenticationFactor, correlationId),
methods: this.resolveMethods(parsedResponse.body, correlationId),
};
}
throw new CustomAuthApiError(INVALID_HAL_RESPONSE, "Invalid HAL response: verify returned no known next action", correlationId);
}
resolveAuthenticationFactor(authenticationFactor, correlationId) {
if (authenticationFactor === AuthenticationFactorV2.SINGLE_FACTOR ||
authenticationFactor === AuthenticationFactorV2.MULTI_FACTOR) {
return authenticationFactor;
}
const message = authenticationFactor
? `Unexpected authentication factor '${authenticationFactor}'.`
: "The response did not include an authentication factor.";
this.logger?.error(message, correlationId);
throw new CustomAuthApiError(UNEXPECTED_AUTHENTICATION_FACTOR, message, correlationId);
}
toChallengeResult(parsedResponse) {
if (parsedResponse.body.action === RISK_VERIFY_RELATION) {
const riskResponse = parsedResponse.body;
return {
nextAction: ChallengeNextActionV2.RISK_VERIFY,
continuationToken: this.handler.requireContinuationToken(parsedResponse.continuationToken, parsedResponse.correlationId),
riskVerifyHref: this.handler.requireHref(riskResponse._links?.riskverify?.href, RISK_VERIFY_RELATION, parsedResponse.correlationId),
};
}
if (parsedResponse.body.action === VERIFY_RELATION) {
return this.toChallengeVerificationResult(parsedResponse);
}
throw new CustomAuthApiError(INVALID_HAL_RESPONSE, "Invalid HAL response: challenge returned no known next action", parsedResponse.correlationId);
}
toChallengeVerificationResult(parsedResponse) {
const continuationToken = this.handler.requireContinuationToken(parsedResponse.continuationToken, parsedResponse.correlationId);
const links = parsedResponse.body._links;
const codeMetadata = "hint" in parsedResponse.body ||
"codeLength" in parsedResponse.body ||
"payload" in parsedResponse.body
? parsedResponse.body
: undefined;
return {
nextAction: ChallengeNextActionV2.VERIFY,
continuationToken,
verifyHref: this.handler.requireHref(links?.verify?.href, "verify", parsedResponse.correlationId),
resendHref: links && "resend" in links ? links.resend?.href : undefined,
codeLength: codeMetadata?.codeLength ?? codeMetadata?.payload?.codeLength,
hint: codeMetadata?.hint,
type: parsedResponse.body.type,
};
}
resolveMethods(body, correlationId) {
const methods = this.handler.requireMethods(body._embedded?.methods, correlationId);
const resolved = [];
methods.forEach((method, index) => {
const href = method._links?.challenge?.href;
if (href) {
resolved.push({
id: method.id ?? method.type ?? `method-${index}`,
type: method.type,
hint: method.hint,
challengeHref: href,
});
}
});
if (resolved.length === 0) {
this.logger?.error("1poo9g", correlationId);
throw new CustomAuthApiError(NO_AUTHENTICATION_METHODS, "The flow-start response contains no authentication method with a challenge link", correlationId);
}
return resolved;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Shared base for Native Auth V2 interaction clients. It extends
* `StandardInteractionClient` for common browser infrastructure while keeping
* V1 and V2 token handling independent.
*/
class InteractionClientBaseV2 extends StandardInteractionClient {
constructor(config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, performanceClient, customAuthAuthority) {
super(config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, performanceClient, "");
this.customAuthAuthority = customAuthAuthority;
this.tokenResponseHandler = new ResponseHandler(this.config.auth.clientId, this.browserStorage, this.browserCrypto, this.logger, this.performanceClient, null, null);
}
// Required by the base contract. After sign-in, use CustomAuthAccountData.getAccessToken().
acquireToken(
// eslint-disable-next-line @typescript-eslint/no-unused-vars
request) {
throw new MethodNotImplementedError("InteractionClientBaseV2.acquireToken");
}
// Required by the base contract. After sign-in, use CustomAuthAccountData.signOut().
logout(
// eslint-disable-next-line @typescript-eslint/no-unused-vars
request) {
throw new MethodNotImplementedError("InteractionClientBaseV2.logout");
}
getScopes(scopes) {
const requestedScopes = scopes?.filter((scope) => !!scope) ?? [];
const seenScopes = new Set(requestedScopes.map((scope) => scope.toLowerCase()));
const defaultScopes = [
OPENID_SCOPE,
PROFILE_SCOPE,
OFFLINE_ACCESS_SCOPE,
];
return [
...requestedScopes,
...defaultScopes.filter((scope) => !seenScopes.has(scope.toLowerCase())),
];
}
async handleTokenResponse(tokenResponse, requestScopes, correlationId, apiId) {
this.logger.verbose("1aahxi", correlationId);
const requestTimestamp = Math.round(new Date().getTime() / 1000.0);
const result = await this.tokenResponseHandler.handleServerTokenResponse(tokenResponse, this.customAuthAuthority, requestTimestamp, {
authority: this.customAuthAuthority.canonicalAuthority,
correlationId,
scopes: requestScopes,
}, apiId);
return result;
}
createRequestContext(apiId, correlationId) {
return {
correlationId,
telemetryManager: initializeServerTelemetryManager(apiId, this.config.auth.clientId, correlationId, this.browserStorage, this.logger),
};
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
// Result type discriminators.
const FLOW_METHOD_SELECTION_REQUIRED_V2 = "FlowMethodSelectionRequiredResultV2";
const FLOW_CODE_REQUIRED_V2 = "FlowCodeRequiredResultV2";
const FLOW_PASSWORD_REQUIRED_V2 = "FlowPasswordRequiredResultV2";
const FLOW_SIGN_UP_PASSWORD_REQUIRED_V2 = "FlowSignUpPasswordRequiredResultV2";
const FLOW_MFA_REQUIRED_V2 = "FlowMFARequiredResultV2";
const FLOW_NEW_PASSWORD_REQUIRED_V2 = "FlowNewPasswordRequiredResultV2";
const FLOW_ATTRIBUTES_REQUIRED_V2 = "FlowAttributesRequiredResultV2";
const FLOW_SIGN_IN_CONTINUATION_REQUIRED_V2 = "FlowSignInContinuationRequiredResultV2";
const FLOW_COMPLETED_V2 = "FlowCompletedResultV2";
function createFlowMethodSelectionRequiredResultV2(input) {
return { type: FLOW_METHOD_SELECTION_REQUIRED_V2, ...input };
}
function createFlowCodeRequiredResultV2(input) {
return { type: FLOW_CODE_REQUIRED_V2, ...input };
}
function createFlowPasswordRequiredResultV2(input) {
return { type: FLOW_PASSWORD_REQUIRED_V2, ...input };
}
function createFlowSignUpPasswordRequiredResultV2(input) {
return { type: FLOW_SIGN_UP_PASSWORD_REQUIRED_V2, ...input };
}
function createFlowMFARequiredResultV2(input) {
return { type: FLOW_MFA_REQUIRED_V2, ...input };
}
function createFlowNewPasswordRequiredResultV2(input) {
return { type: FLOW_NEW_PASSWORD_REQUIRED_V2, ...input };
}
function createFlowAttributesRequiredResultV2(input) {
return { type: FLOW_ATTRIBUTES_REQUIRED_V2, ...input };
}
function createFlowSignInContinuationRequiredResultV2(input) {
return { type: FLOW_SIGN_IN_CONTINUATION_REQUIRED_V2, ...input };
}
function createFlowCompletedResultV2(input) {
return { type: FLOW_COMPLETED_V2, ...input };
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* The native auth V2 flow that a result or error originates from (sign-in,
* sign-up, or password reset). It lets a shared result or error type report
* which entry flow produced it; `Unknown` is used when the flow cannot be
* determined.
*/
const CustomAuthFlowScenarioV2 = {
SignIn: "signIn",
SignUp: "signUp",
PasswordReset: "passwordReset",
Unknown: "unknown",
};
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const FLOW_STEP_API_IDS_V2 = {
[CustomAuthFlowScenarioV2.PasswordReset]: {
requestChallenge: RESET_PASSWORD_V2_CHALLENGE,
submitCode: RESET_PASSWORD_V2_SUBMIT_CODE,
resendCode: RESET_PASSWORD_V2_RESEND_CODE,
submitNewPassword: RESET_PASSWORD_V2_SUBMIT,
signInWithContinuation: SIGN_IN_AFTER_PASSWORD_RESET,
},
[CustomAuthFlowScenarioV2.SignIn]: {
requestChallenge: SIGN_IN_V2_CHALLENGE,
submitCode: SIGN_IN_V2_SUBMIT_CODE,
resendCode: SIGN_IN_V2_CHALLENGE,
submitPassword: SIGN_IN_V2_SUBMIT_PASSWORD,
signInWithContinuation: SIGN_IN_V2_COMPLETE,
},
[CustomAuthFlowScenarioV2.SignUp]: {
requestChallenge: SIGN_UP_V2_CHALLENGE,
submitCode: SIGN_UP_V2_SUBMIT_CODE,
resendCode: SIGN_UP_V2_RESEND_CODE,
submitAttributes: SIGN_UP_V2_SUBMIT_ATTRIBUTES,
signInWithContinuation: SIGN_UP_V2_COMPLETE,
},
};
function getPublicApiIdV2(scenario, step) {
return FLOW_STEP_API_IDS_V2[scenario]?.[step];
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Polls up to five times for password-update completion, waiting 1.5 seconds
* between attempts. The first request runs immediately.
*/
const POLL_MAX_ATTEMPTS = 5;
// TODO: Replace this fallback with the server-provided polling interval once available.
const POLL_INTERVAL_MS = 1500;
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
/*
* Drives server-directed Native Auth V2 flows using opaque continuation state
* and HAL links. Each operation returns only its valid discriminated results.
*/
class FlowInteractionClientV2 extends InteractionClientBaseV2 {
constructor(config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, performanceClient, customAuthAuthority, apiClient) {
super(config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, performanceClient, customAuthAuthority);
this.apiClient = apiClient;
}
/*
* Starts sign-in using the preferred supported method offered by the server.
*/
async signIn(parameters) {
const correlationId = parameters.correlationId;
const context = this.createRequestContext(SIGN_IN_V2_START, correlationId);
this.logger.verbose("1jeyrn", correlationId);
const entryResult = await this.apiClient.authorizeChallengeStart(context);
const startResult = await this.apiClient.signInStart(this.requireLink(correlationId, entryResult.signInHref, {
code: SIGN_IN_UNSUPPORTED,
message: "The authorize-challenge entry response did not include a sign-in link.",
}), {
continuationToken: entryResult.continuationToken,
username: parameters.username,
}, context);
this.ensureAuthenticationFactor(startResult.authenticationFactor, AuthenticationFactorV2.SINGLE_FACTOR, "sign-in start", correlationId);
const continuationState = {
continuationToken: startResult.continuationToken,
scenario: CustomAuthFlowScenarioV2.SignIn,
links: {},
tokenRequest: {
scopes: parameters.scopes,
},
};
const methods = startResult.methods.map((method) => ({
id: method.id,
type: method.type ?? "",
hint: method.hint,
challengeHref: method.challengeHref,
}));
const selectedMethod = this.selectSignInMethod(methods, parameters.password !== undefined, correlationId);
const challengeResult = await this.requestChallenge({
correlationId,
continuationState: {
...continuationState,
links: {
...continuationState.links,
challenge: selectedMethod.challengeHref,
},
},
});
if (challengeResult.type === FLOW_CODE_REQUIRED_V2) {
return {
...challengeResult,
method: selectedMethod,
};
}
if (parameters.password) {
return this.submitSignInPassword({
correlationId,
continuationState: challengeResult.continuationState,
password: parameters.password,
});
}
return challengeResult;
}
/*
* Starts sign-up and resolves the server-provided attribute-submission transition.
*/
async signUp(parameters) {
const correlationId = parameters.correlationId;
const context = this.createRequestContext(SIGN_UP_V2_START, correlationId);
this.logger.verbose("19e1ak", correlationId);
const entryResult = await this.apiClient.authorizeChallengeStart(context, parameters.scopes);
const startResult = await this.apiClient.signUpStart(this.requireLink(correlationId, entryResult.signUpHref, {
code: SIGN_UP_UNSUPPORTED,
message: "The authorize-challenge entry response did not include a sign-up link.",
}), {
continuationToken: entryResult.continuationToken,
}, context);
const attributes = Object.fromEntries(Object.entries(parameters.attributes ?? {}).filter(([name]) => name.toLowerCase() !== "email" &&
name.toLowerCase() !== "password"));
attributes.email = parameters.username;
if (parameters.password !== undefined) {
attributes.password = parameters.password;
}
const submitResult = await this.apiClient.submitSignUpAttributes(startResult.submitAttributesHref, {
continuationToken: startResult.continuationToken,
attributes,
}, context);
const continuationState = {
continuationToken: startResult.continuationToken,
scenario: CustomAuthFlowScenarioV2.SignUp,
links: {},
tokenRequest: {
scopes: parameters.scopes,
},
signUp: {
passwordWasSupplied: attributes.password !== undefined,
},
};
const result = this.toSignUpActionResult(submitResult, continuationState, correlationId);
if (result.type === FLOW_SIGN_IN_CONTINUATION_REQUIRED_V2) {
const message = "Initial sign-up attribute submission cannot complete without code verification or additional attributes.";
this.logger.error(message, correlationId);
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, message, correlationId);
}
return result;
}
/*
* Starts password reset, automatically challenging a sole method or
* returning multiple methods for selection.
*/
async resetPassword(parameters) {
const correlationId = parameters.correlationId;
const context = this.createRequestContext(RESET_PASSWORD_V2_START, correlationId);
this.logger.verbose("1en88i", correlationId);
const entryResult = await this.apiClient.authorizeChallengeStart(context);
const startResult = await this.apiClient.resetPasswordStart(this.requireLink(correlationId, entryResult.resetPasswordHref, {
code: RESET_PASSWORD_UNSUPPORTED,
message: "The authorize-challenge entry response did not include a reset-password link.",
}), {
username: parameters.username,
continuationToken: entryResult.continuationToken,
}, context);
this.ensureAuthenticationFactor(startResult.authenticationFactor, AuthenticationFactorV2.SINGLE_FACTOR, "password-reset start", correlationId);
const continuationState = {
continuationToken: startResult.continuationToken,
scenario: CustomAuthFlowScenarioV2.PasswordReset,
links: {},
};
const methods = startResult.methods.map((method) => ({
id: method.id,
type: method.type ?? "",
hint: method.hint,
challengeHref: method.challengeHref,
}));
if (methods.length === 0) {
const message = "The password-reset start response did not include an authentication method.";
this.logger.error(message, correlationId);
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, message, correlationId);
}
if (methods.length === 1) {
const selectedMethod = methods[0];
const challengeResult = await this.requestChallenge({
correlationId,
continuationState: {
...continuationState,
links: {
challenge: selectedMethod.challengeHref,
},
},
});
if (challengeResult.type === FLOW_CODE_REQUIRED_V2 &&
(challengeResult.channel?.toLowerCase() ===
AuthenticationMethodTypeV2.EMAIL ||
challengeResult.channel?.toLowerCase() ===
AuthenticationMethodTypeV2.SMS)) {
return {
...challengeResult,
method: selectedMethod,
};
}
const channel = challengeResult.type === FLOW_CODE_REQUIRED_V2
? challengeResult.channel
: AuthenticationMethodTypeV2.PASSWORD;
const message = `Challenge type '${challengeResult.type}' with channel '${channel}' is not supported for password reset.`;
this.logger.error(message, correlationId);
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, message, correlationId);
}
this.logger.verbose("0k8yah", correlationId);
return createFlowMethodSelectionRequiredResultV2({
correlationId,
continuationState,
methods,
});
}
/*
* Requests a one-time code for the selected authentication method. Returns
* the continuation state and code metadata needed for verification.
*/
async requestChallenge(parameters) {
const challengeResult = await this.sendMethodChallenge(parameters, "requestChallenge");
const challengeType = challengeResult.type ?? AuthenticationMethodTypeV2.EMAIL;
const continuationState = this.createChallengeContinuationState(parameters.continuationState, challengeResult);
if (challengeType.toLowerCase() === AuthenticationMethodTypeV2.PASSWORD) {
return createFlowPasswordRequiredResultV2({
correlationId: parameters.correlationId,
continuationState,
});
}
return createFlowCodeRequiredResultV2({
correlationId: parameters.correlationId,
continuationState,
channel: challengeType,
sentTo: challengeResult.hint,
codeLength: challengeResult.codeLength,
});
}
/*
* Verifies the submitted one-time code using the server-provided link. The
* response determines the next required action.
*/
async submitCode(parameters) {
const continuationState = parameters.continuationState;
const correlationId = parameters.correlationId;
const context = this.createRequestContext(this.resolveStepApiId(continuationState.scenario, "submitCode", correlationId), correlationId);
this.logger.verbose("16ks6n", correlationId);
const verifyHref = this.requireLink(correlationId, continuationState.links.verify);
const verifyRequest = {
continuationToken: continuationState.continuationToken,
otp: parameters.code,
};
const verifyResult = await this.apiClient.verifyChallenge(verifyHref, verifyRequest, context);
if (continuationState.scenario ===
CustomAuthFlowScenarioV2.PasswordReset &&
verifyResult.nextAction === VerifyNextActionV2.UPDATE) {
return createFlowNewPasswordRequiredResultV2({
correlationId,
continuationState: {
continuationToken: verifyResult.continuationToken,
scenario: continuationState.scenario,
links: { update: verifyResult.updateHref },
},
});
}
if (continuationState.scenario === CustomAuthFlowScenarioV2.SignIn) {
return this.handleSignInVerification(continuationState, verifyResult, correlationId);
}
if (continuationState.scenario === CustomAuthFlowScenarioV2.SignUp &&
verifyResult.nextAction === VerifyNextActionV2.COLLECT_ATTRIBUTES) {
const requiredPasswordAttribute = verifyResult.attributes.find((attribute) => attribute.attributeId.toLowerCase() === "password" &&
attribute.required === true);
const nextContinuationState = {
continuationToken: verifyResult.continuationToken,
scenario: continuationState.scenario,
links: {
submitAttributes: verifyResult.submitAttributesHref,
},
tokenRequest: continuationState.tokenRequest,
signUp: continuationState.signUp,
};
const attributes = verifyResult.attributes.filter((attribute) => attribute.attributeId.toLowerCase() !== "password");
if (requiredPasswordAttribute &&
continuationState.signUp?.passwordWasSupplied !== true) {
return createFlowSignUpPasswordRequiredResultV2({
correlationId,
continuationState: nextContinuationState,
attributes,
requiredPasswordAttribute,
});
}
return createFlowAttributesRequiredResultV2({
correlationId,
continuationState: nextContinuationState,
attributes,
});
}
if (continuationState.scenario === CustomAuthFlowScenarioV2.SignUp &&
verifyResult.nextAction === VerifyNextActionV2.CONTINUE) {
return createFlowSignInContinuationRequiredResultV2({
correlationId,
continuationState: {
continuationToken: verifyResult.continuationToken,
scenario: continuationState.scenario,
links: {},
tokenRequest: continuationState.tokenRequest,
},
});
}
const message = `Verification next action '${verifyResult.nextAction}' is not supported for the '${continuationState.scenario}' flow.`;
this.logger.error(message, correlationId);
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, message, correlationId);
}
/*
* Requests a new one-time code using the server-provided resend link.
* Returns refreshed continuation state and code metadata.
*/
async resendCode(parameters) {
const challengeResult = await this.sendMethodChallenge(parameters, "resendCode");
return createFlowCodeRequiredResultV2({
correlationId: parameters.correlationId,
continuationState: this.createChallengeContinuationState(parameters.continuationState, challengeResult),
channel: challengeResult.type,
sentTo: challengeResult.hint,
codeLength: challengeResult.codeLength,
});
}
async submitSignUpAttributes(parameters) {
const { continuationState, correlationId, attributes } = parameters;
const context = this.createRequestContext(this.resolveStepApiId(continuationState.scenario, "submitAttributes", correlationId), correlationId);
this.logger.verbose("0js2ub", correlationId);
const submitResult = await this.apiClient.submitSignUpAttributes(this.requireLink(correlationId, continuationState.links.submitAttributes), {
continuationToken: continuationState.continuationToken,
attributes,
}, context);
return this.toSignUpActionResult(submitResult, {
...continuationState,
signUp: {
passwordWasSupplied: continuationState.signUp?.passwordWasSupplied ===
true || attributes.password !== undefined,
},
}, correlationId);
}
/*
* Submits the new password and polls until the reset completes. The result
* contains the continuation state required for explicit sign-in.
*/
async submitNewPassword(parameters) {
const continuationState = parameters.continuationState;
const correlationId = parameters.correlationId;
const context = this.createRequestContext(this.resolveStepApiId(continuationState.scenario, "submitNewPassword", correlationId), correlationId);
this.logger.verbose("0ie1qa", correlationId);
const updateResult = await this.apiClient.submitNewPassword(this.requireLink(correlationId, continuationState.links.update), {
continuationToken: continuationState.continuationToken,
newPassword: parameters.newPassword,
}, context);
let pollToken = updateResult.continuationToken;
let pollHref = updateResult.pollHref;
let completionToken;
for (let attempt = 1; attempt <= POLL_MAX_ATTEMPTS; attempt++) {
const pollResult = await this.apiClient.poll(pollHref, { continuationToken: pollToken }, context);
if (pollResult.isCompleted) {
completionToken = pollResult.continuationToken;
break;
}
pollToken = pollResult.continuationToken;
pollHref = pollResult.pollHref ?? pollHref;
if (attempt < POLL_MAX_ATTEMPTS) {
await delay(POLL_INTERVAL_MS);
}
}
if (!completionToken) {
const message = "The password reset did not complete within the allotted number of polling attempts.";
this.logger.error(message, correlationId);
throw new CustomAuthError(RESET_PASSWORD_TIMEOUT, message, correlationId);
}
this.logger.verbose("0hrwdj", correlationId);
return createFlowSignInContinuationRequiredResultV2({
correlationId,
continuationState: {
continuationToken: completionToken,
scenario: continuationState.scenario,
links: {},
},
});
}
/*
* Verifies a sign-in password and returns the next sign-in action.
*/
async submitSignInPassword(parameters) {
const verifyResult = await this.verifySignInPassword(parameters);
return this.handleSignInVerification(parameters.continuationState, verifyResult, parameters.correlationId);
}
/*
* Redeems the completed flow continuation for tokens. Returns the
* authentication result after validating and caching the response.
*/
async signInWithContinuation(parameters) {
const continuationState = parameters.continuationState;
const correlationId = parameters.correlationId;
const apiId = this.resolveStepApiId(continuationState.scenario, "signInWithContinuation", correlationId);
const context = this.createRequestContext(apiId, correlationId);
this.logger.verbose("09mk3f", correlationId);
const scopes = this.getScopes(parameters.scopes);
const tokenResponse = await this.apiClient.completeWithTokens({
continuationToken: continuationState.continuationToken,
scopes,
}, context);
const authenticationResult = await this.handleTokenResponse(tokenResponse, scopes, correlationId, apiId);
this.logger.verbose("15nu4j", correlationId);
return createFlowCompletedResultV2({
correlationId,
authenticationResult,
});
}
async handleSignInVerification(continuationState, verifyResult, correlationId) {
if (verifyResult.nextAction === VerifyNextActionV2.CHALLENGE) {
this.ensureAuthenticationFactor(verifyResult.authenticationFactor, AuthenticationFactorV2.MULTI_FACTOR, "after sign-in verification", correlationId);
return createFlowMFARequiredResultV2({
correlationId,
continuationState: {
continuationToken: verifyResult.continuationToken,
scenario: continuationState.scenario,
links: {},
tokenRequest: continuationState.tokenRequest,
},
methods: verifyResult.methods.map((method) => ({
id: method.id,
type: method.type ?? "",
hint: method.hint,
challengeHref: method.challengeHref,
})),
});
}
if (verifyResult.nextAction === VerifyNextActionV2.CONTINUE) {
return this.completeSignInAfterVerification(continuationState, verifyResult.continuationToken, correlationId);
}
const message = `Verification next action '${verifyResult.nextAction}' is not supported for sign-in.`;
this.logger.error(message, correlationId);
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, message, correlationId);
}
selectSignInMethod(methods, passwordProvided, correlationId) {
const passwordMethod = methods.find((method) => method.type.toLowerCase() ===
AuthenticationMethodTypeV2.PASSWORD);
const emailMethod = methods.find((method) => method.type.toLowerCase() === AuthenticationMethodTypeV2.EMAIL);
if (passwordProvided) {
if (passwordMethod) {
return passwordMethod;
}
const message = "A password was supplied, but the sign-in response did not include a password method.";
this.logger.error(message, correlationId);
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, message, correlationId);
}
const selectedMethod = emailMethod ?? passwordMethod;
if (selectedMethod) {
return selectedMethod;
}
const message = "The sign-in start response did not include a supported email or password method.";
this.logger.error(message, correlationId);
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, message, correlationId);
}
toSignUpActionResult(result, continuationState, correlationId) {
const nextAction = result.nextAction;
if (result.nextAction === SignUpSubmitAttributesNextActionV2.VERIFY) {
return createFlowCodeRequiredResultV2({
correlationId,
continuationState: {
continuationToken: result.continuationToken,
scenario: continuationState.scenario,
links: {
verify: result.verifyHref,
resend: result.resendHref,
},
tokenRequest: continuationState.tokenRequest,
signUp: continuationState.signUp,
},
channel: result.type,
sentTo: result.hint,
codeLength: result.codeLength,
});
}
if (result.nextAction ===
SignUpSubmitAttributesNextActionV2.COLLECT_ATTRIBUTES) {
const requiredPasswordAttribute = result.attributes.find((attribute) => attribute.attributeId.toLowerCase() === "password" &&
attribute.required === true);
const nextContinuationState = {
continuationToken: result.continuationToken,
scenario: continuationState.scenario,
links: {
submitAttributes: result.submitAttributesHref,
},
tokenRequest: continuationState.tokenRequest,
signUp: continuationState.signUp,
};
const attributes = result.attributes.filter((attribute) => attribute.attributeId.toLowerCase() !== "password");
if (requiredPasswordAttribute &&
continuationState.signUp?.passwordWasSupplied !== true) {
return createFlowSignUpPasswordRequiredResultV2({
correlationId,
continuationState: nextContinuationState,
attributes,
requiredPasswordAttribute,
});
}
return createFlowAttributesRequiredResultV2({
correlationId,
continuationState: nextContinuationState,
attributes,
});
}
if (result.nextAction === SignUpSubmitAttributesNextActionV2.CONTINUE) {
return createFlowSignInContinuationRequiredResultV2({
correlationId,
continuationState: {
continuationToken: result.continuationToken,
scenario: continuationState.scenario,
links: {},
tokenRequest: continuationState.tokenRequest,
},
});
}
const message = `Sign-up attribute submission next action '${nextAction}' is not supported.`;
this.logger.error(message, correlationId);
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, message, correlationId);
}
ensureAuthenticationFactor(authenticationFactor, expectedFactor, transition, correlationId) {
if (authenticationFactor === expectedFactor) {
return;
}
const message = `Authentication factor '${authenticationFactor}' is not supported for ${transition}.`;
this.logger.error(message, correlationId);
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, message, correlationId);
}
async verifySignInPassword(parameters) {
const { continuationState, correlationId } = parameters;
const context = this.createRequestContext(this.resolveStepApiId(continuationState.scenario, "submitPassword", correlationId), correlationId);
this.logger.verbose("1bi1xn", correlationId);
return this.apiClient.verifyChallenge(this.requireLink(correlationId, continuationState.links.verify), {
continuationToken: continuationState.continuationToken,
password: parameters.password,
}, context);
}
completeSignInAfterVerification(continuationState, continuationToken, correlationId) {
return this.signInWithContinuation({
correlationId,
continuationState: {
continuationToken,
scenario: continuationState.scenario,
links: {},
tokenRequest: continuationState.tokenRequest,
},
scopes: continuationState.tokenRequest?.scopes,
});
}
async sendMethodChallenge(parameters, step) {
const continuationState = parameters.continuationState;
const correlationId = parameters.correlationId;
const challengeHref = step === "resendCode"
? continuationState.links.resend
: continuationState.links.challenge;
const context = this.createRequestContext(this.resolveStepApiId(continuationState.scenario, step, correlationId), correlationId);
this.logger.verbose(step === "0d2mys"
? "Resending V2 one-time code."
: "Requesting V2 challenge.", correlationId);
const challengeResult = await this.apiClient.requestChallenge(this.requireLink(correlationId, challengeHref), { continuationToken: continuationState.continuationToken }, context);
const nextAction = challengeResult.nextAction;
if (challengeResult.nextAction === ChallengeNextActionV2.VERIFY) {
return challengeResult;
}
if (challengeResult.nextAction === ChallengeNextActionV2.RISK_VERIFY) {
return this.apiClient.verifyRisk(challengeResult.riskVerifyHref, { continuationToken: challengeResult.continuationToken }, context);
}
const message = `Challenge next action '${nextAction}' is not supported.`;
this.logger.error(message, correlationId);
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, message, correlationId);
}
createChallengeContinuationState(continuationState, challengeResult) {
return {
continuationToken: challengeResult.continuationToken,
scenario: continuationState.scenario,
links: {
challenge: continuationState.links.challenge,
verify: challengeResult.verifyHref,
resend: challengeResult.resendHref ??
continuationState.links.resend,
},
...(continuationState.tokenRequest && {
tokenRequest: continuationState.tokenRequest,
}),
...(continuationState.signUp && {
signUp: continuationState.signUp,
}),
};
}
resolveStepApiId(scenario, step, correlationId) {
const apiId = getPublicApiIdV2(scenario, step);
if (apiId === undefined) {
const message = `No telemetry API id is registered for step '${step}' of the '${scenario}' flow.`;
this.logger.error(message, correlationId);
throw new CustomAuthError(UNSUPPORTED_FLOW_STEP, message, correlationId);
}
return apiId;
}
requireLink(correlationId, href, missingLinkError) {
if (!href) {
const errorCode = missingLinkError?.code ?? CONTINUATION_LINK_MISSING;
const message = missingLinkError?.message ??
"The continuation state is missing a link required to advance the flow.";
this.logger.error(message, correlationId);
throw new CustomAuthError(errorCode, message, correlationId);
}
return href;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Terminal state indicating the operation failed.
*
* The error is carried by the result's `error` payload, not by this state.
*/
class FailedStateV2 extends AuthFlowStateBase {
constructor() {
super(...arguments);
this.stateType = "failed";
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Result of a native auth V2 operation. Use {@link CustomAuthResultV2.isState}
* to narrow the state before accessing its members.
*/
class CustomAuthResultV2 {
constructor(state, data, scenario = CustomAuthFlowScenarioV2.Unknown) {
this.state = state;
this.data = data;
this.scenario = scenario;
}
/**
* Narrows the result to a specific state by its `stateType` discriminator.
* A successful match makes the state's properties available without a cast.
* @param stateType - The state type to test for.
* @returns True (and narrows `state`) when the current state matches `stateType`.
*/
isState(stateType) {
return this.state.stateType === stateType;
}
/**
* Checks whether the result is in the terminal failed state. A failed result
* contains the flow-specific error.
* @returns True (and narrows `state`) when the operation failed.
*/
isFailed() {
return this.state.stateType === "failed";
}
/**
* Creates a failed result from the supplied error. The result uses the
* shared {@link FailedStateV2} terminal state.
* @param error - The error that occurred.
* @param options - The flow-error type and error context.
* @returns A failed result carrying the flow-specific error.
*/
static createWithError(error, options) {
const { errorType: ErrorType, scenario = CustomAuthFlowScenarioV2.Unknown, correlationId, } = options;
const errorData = CustomAuthResultV2.createErrorData(error, correlationId);
const flowError = new ErrorType(errorData, scenario);
const result = new CustomAuthResultV2(new FailedStateV2(), undefined, scenario);
result.error = flowError;
return result;
}
static createErrorData(error, correlationId) {
if (error instanceof CustomAuthError) {
return error;
}
if (error instanceof AuthError) {
const errorCodes = [];
if ("errorNo" in error) {
if (typeof error.errorNo === "string") {
const code = Number(error.errorNo);
if (!isNaN(code)) {
errorCodes.push(code);
}
}
else if (typeof error.errorNo === "number") {
errorCodes.push(error.errorNo);
}
}
return new MsalCustomAuthError(error.errorCode, error.errorMessage, error.subError, errorCodes, error.correlationId);
}
return new UnexpectedError(error, correlationId);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const INVALID_ONE_TIME_CODE = "invalidOneTimeCode";
const INVALID_USERNAME_OR_PASSWORD = "invalidUserNameOrPassword";
const PASSWORD_TOO_WEAK = "passwordTooWeak";
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Standalone V2 error base; intentionally does NOT extend the V1 AuthFlowErrorBase.
* Provides the detectors common to every V2 flow; each per-action subclass adds only
* the detectors relevant to its own action.
*/
class AuthFlowErrorBaseV2 {
constructor(errorData, scenario = CustomAuthFlowScenarioV2.Unknown) {
this.errorData = errorData;
this.scenario = scenario;
}
get correlationId() {
return this.errorData.correlationId;
}
get errorCodes() {
return this.errorData.errorCodes;
}
get errorDescription() {
return this.errorData.errorDescription;
}
/**
* Checks if the error requires the flow to continue in the browser. The
* server surfaces this as a `redirect_to_web` failure, so a browser hand-off
* always arrives as a `FailedStateV2` on which this detector returns true.
* @returns True if the browser is required, false otherwise.
*/
isBrowserRequired() {
return this.errorData.error === REDIRECT_TO_WEB;
}
/**
* Checks if the error is due to a caller-supplied argument failing
* client-side validation before the request was issued (for example an empty
* username, code, or password, or an unknown method id). Use it to prompt the
* user to correct the input rather than treating it as a server failure.
* @returns True if the input was invalid, false otherwise.
*/
isInvalidInput() {
return this.errorData instanceof InvalidArgumentError;
}
/**
* Checks whether an account already exists for the supplied identifier.
* This can occur at different stages while completing sign-up.
* @returns True if the account already exists, otherwise false.
*/
isUserAlreadyExists() {
return this.getAttributeValidationDetails().some((detail) => detail.code === "userAlreadyExists");
}
/*
* User-not-found arrives as AADSTS50034. The nested `/api` error carries no
* innerError and no error_codes array, so the AADSTS marker in the message is
* the only signal.
*/
// TODO: Use the service-provided suberror when it becomes available.
isUserNotFoundError() {
return (this.errorData.error === "invalidRequest" &&
this.errorData.errorDescription?.includes("AADSTS50034") === true);
}
isUserInvalidError() {
return (this.errorData.error === "invalidRequest" &&
this.errorData.errorDescription?.includes("AADSTS90100") === true &&
this.errorData.errorDescription
.toLowerCase()
.includes("username parameter"));
}
// The verification endpoint uses this outer/inner code pair for an invalid one-time code.
isInvalidCodeError() {
return (this.errorData.error === "invalidGrant" &&
this.errorData.subError === INVALID_ONE_TIME_CODE);
}
// New password rejected by policy: inner `passwordTooWeak` (AADSTS120002).
isInvalidPasswordError() {
return (this.errorData.error === "invalidRequest" &&
this.errorData.subError === PASSWORD_TOO_WEAK);
}
isPasswordPolicyViolationError() {
return this.getAttributeValidationDetails().some((detail) => detail.code === "passwordPolicyViolation" &&
detail.attributeIds?.some((attributeId) => attributeId.toLowerCase() === "password") === true);
}
isPasswordIncorrectError() {
return (this.errorData.error === "invalidGrant" &&
this.errorData.subError === INVALID_USERNAME_OR_PASSWORD);
}
getAttributeValidationDetails() {
const details = this.errorData.attributeValidationDetails;
return Array.isArray(details)
? details.filter((detail) => typeof detail === "object" && detail !== null)
: [];
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Error raised when requesting (or resending) a challenge for a selected
* authentication method. It is a shared action error bound to the shared
* `RequestChallengeResultV2` and returned regardless of which entry flow reached
* it. It currently exposes no action-specific detectors — only the inherited
* `isBrowserRequired()`.
*/
class RequestChallengeErrorV2 extends AuthFlowErrorBaseV2 {
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Error raised when verifying a challenge (submitting a one-time code). It
* exposes the detectors relevant to code verification so the app can respond to
* a rejected code specifically. Unrecognised failures carry no specific
* detector; inspect the error code (`unexpected_error` when the server gives
* none) and `errorDescription`.
*/
class VerifyChallengeErrorV2 extends AuthFlowErrorBaseV2 {
/**
* Checks if the error is due to the provided code being invalid or expired.
* Use it to prompt the user to re-enter the code or request a new one, rather
* than restarting the whole flow.
* @returns True if the code is invalid, false otherwise.
*/
isInvalidCode() {
return this.isInvalidCodeError();
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Terminal state indicating the operation completed successfully.
*
* Completion data (for example the signed-in account) is carried by the
* result's `data` payload, not by this state.
*/
class CompletedStateV2 extends AuthFlowStateBase {
constructor() {
super(...arguments);
this.stateType = "completed";
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Error raised when redeeming a completed V2 flow's continuation for tokens.
* It adds no action-specific detectors beyond the inherited
* `isBrowserRequired()`; the app typically retries or starts sign-in explicitly.
*/
class SignInContinuationErrorV2 extends AuthFlowErrorBaseV2 {
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Shared state returned when a completed V2 flow can sign the user in by
* redeeming its continuation. Password reset and sign-up can both surface this
* state without duplicating the token-acquisition behavior.
*/
class SignInContinuationStateV2 extends AuthFlowActionRequiredStateBase {
constructor() {
super(...arguments);
this.stateType = "signInContinuation";
}
/**
* Signs the user in using the continuation established by the completed V2
* flow. On success the returned result reaches the completed state
* carrying the signed-in account data; on failure the result's error reports
* why the follow-up sign-in could not complete.
* @param inputs - Optional scopes requested for the issued token. Claims
* are accepted for API alignment but are not sent until the V2 service
* supports them on authorize-challenge.
* @returns The result of signing in after the password reset.
*/
async signIn(inputs) {
const { correlationId, logger, continuationState, flowClient } = this.stateParameters;
try {
if (inputs?.claims) {
ensureArgumentIsJSONString("inputs.claims", inputs.claims, correlationId);
}
logger.verbose("09mk3f", correlationId);
const result = await flowClient.signInWithContinuation({
correlationId,
continuationState,
scopes: inputs?.scopes,
});
const account = new CustomAuthAccountData(result.authenticationResult.account, this.stateParameters.config, this.stateParameters.cacheClient, logger, correlationId);
return new CustomAuthResultV2(new CompletedStateV2(), account, continuationState.scenario);
}
catch (error) {
logger.errorPii(`0zoo5u ${error}`, correlationId);
return CustomAuthResultV2.createWithError(error, {
errorType: SignInContinuationErrorV2,
scenario: continuationState.scenario,
correlationId,
});
}
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Error raised when submitting a new password. It exposes the detectors relevant
* to password submission so the app can react to a rejected password
* specifically. Unrecognised failures carry no specific detector; inspect the
* error code (`unexpected_error` when the server gives none) and
* `errorDescription`.
*/
class SubmitNewPasswordErrorV2 extends AuthFlowErrorBaseV2 {
/**
* Checks if the error is due to the new password being invalid, for example
* because it fails the tenant's complexity policy. Use it to prompt the user
* for a stronger password rather than restarting the reset flow.
* @returns True if the new password is invalid, false otherwise.
*/
isInvalidPassword() {
return this.isInvalidPasswordError();
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* State returned when the user must supply a new password to complete the flow.
* A successful submission returns `SignInContinuationStateV2` so the app can
* sign the user in.
*/
class NewPasswordRequiredStateV2 extends AuthFlowActionRequiredStateBase {
constructor() {
super(...arguments);
this.stateType = "newPasswordRequired";
}
/**
* Submits the new password to complete the reset. The result either allows
* sign-in or reports that the password was rejected.
* @param password - The new password to set.
* @returns The result of submitting the new password.
*/
async submitNewPassword(password) {
const { correlationId, logger, continuationState, flowClient } = this.stateParameters;
try {
this.ensurePasswordIsNotEmpty(password);
logger.verbose("0ie1qa", correlationId);
const result = await flowClient.submitNewPassword({
correlationId,
continuationState,
newPassword: password,
});
return new CustomAuthResultV2(new SignInContinuationStateV2({
correlationId: result.correlationId,
logger,
config: this.stateParameters.config,
flowClient,
continuationState: result.continuationState,
cacheClient: this.stateParameters.cacheClient,
}), undefined, result.continuationState.scenario);
}
catch (error) {
logger.errorPii(`03m081 ${error}`, correlationId);
return CustomAuthResultV2.createWithError(error, {
errorType: SubmitNewPasswordErrorV2,
scenario: continuationState.scenario,
correlationId,
});
}
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class ChallengeVerificationStateBaseV2 extends AuthFlowActionRequiredStateBase {
constructor(stateParameters) {
super(stateParameters);
this.method = stateParameters.method;
this.sentTo = stateParameters.sentTo;
this.channel = stateParameters.channel;
this.codeLength = stateParameters.codeLength;
}
async submitCodeCore(code) {
if (this.codeLength) {
this.ensureCodeIsValid(code, this.codeLength);
}
return this.stateParameters.flowClient.submitCode({
correlationId: this.stateParameters.correlationId,
continuationState: this.stateParameters.continuationState,
code,
});
}
async resendCodeCore() {
return this.stateParameters.flowClient.resendCode({
correlationId: this.stateParameters.correlationId,
continuationState: this.stateParameters.continuationState,
});
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* State returned when sign-in requires verification of an email or SMS MFA
* challenge. It allows the app to submit the challenge or request a replacement.
*/
class MFAVerificationRequiredStateV2 extends ChallengeVerificationStateBaseV2 {
constructor() {
super(...arguments);
this.stateType = "mfaVerificationRequired";
}
/**
* Submits the email or SMS challenge as the second authentication factor.
* Successful verification completes sign-in.
* @param challenge - The challenge value to submit.
* @returns The result of submitting the MFA challenge.
*/
async submitChallenge(challenge) {
const { correlationId, logger, continuationState } = this.stateParameters;
try {
logger.verbose("10k0lc", correlationId);
const result = await this.submitCodeCore(challenge);
if (result.type !== FLOW_COMPLETED_V2) {
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, `MFA challenge submission result type '${result.type}' is not supported.`, correlationId);
}
const account = new CustomAuthAccountData(result.authenticationResult.account, this.stateParameters.config, this.stateParameters.cacheClient, logger, correlationId);
return new CustomAuthResultV2(new CompletedStateV2(), account, continuationState.scenario);
}
catch (error) {
logger.errorPii(`178w0g ${error}`, correlationId);
return CustomAuthResultV2.createWithError(error, {
errorType: VerifyChallengeErrorV2,
scenario: continuationState.scenario,
correlationId,
});
}
}
/**
* Requests a replacement challenge for the selected MFA method. The
* returned state contains the refreshed email or SMS challenge metadata.
* @returns The result of requesting a replacement MFA challenge.
*/
async resendChallenge() {
const { correlationId, logger, continuationState } = this.stateParameters;
try {
logger.verbose("13st9u", correlationId);
const result = await this.resendCodeCore();
return new CustomAuthResultV2(new MFAVerificationRequiredStateV2({
correlationId: result.correlationId,
logger,
config: this.stateParameters.config,
flowClient: this.stateParameters.flowClient,
continuationState: result.continuationState,
cacheClient: this.stateParameters.cacheClient,
method: this.method,
sentTo: result.sentTo,
channel: result.channel,
codeLength: result.codeLength,
}), undefined, result.continuationState.scenario);
}
catch (error) {
logger.errorPii(`1qw1ey ${error}`, correlationId);
return CustomAuthResultV2.createWithError(error, {
errorType: RequestChallengeErrorV2,
scenario: continuationState.scenario,
correlationId,
});
}
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class AuthenticationMethodSelectionStateBaseV2 extends AuthFlowActionRequiredStateBase {
constructor(stateParameters) {
super(stateParameters);
this.methods = stateParameters.methods;
}
async requestSelectedMethodChallenge(method) {
const { correlationId, continuationState, flowClient } = this.stateParameters;
const selectedMethod = this.methods.find((candidate) => candidate.id === method.id);
if (!selectedMethod) {
throw new InvalidArgumentError("method", correlationId);
}
const result = await flowClient.requestChallenge({
correlationId,
continuationState: {
...continuationState,
links: {
...continuationState.links,
challenge: selectedMethod.challengeHref,
},
},
});
return { result, selectedMethod };
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* State returned when sign-in requires a registered multi-factor
* authentication method.
*/
class MFARequiredStateV2 extends AuthenticationMethodSelectionStateBaseV2 {
constructor() {
super(...arguments);
this.stateType = "mfaRequired";
}
/**
* Requests a challenge for a registered MFA method.
* @param method - A method from {@link methods}.
* @returns A result requiring challenge verification or describing failure.
*/
async requestChallenge(method) {
const { correlationId, logger, continuationState, flowClient } = this.stateParameters;
try {
const { result, selectedMethod } = await this.requestSelectedMethodChallenge(method);
if (result.type !== FLOW_CODE_REQUIRED_V2) {
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, `MFA method selection expected a code challenge but received '${result.type}'.`, correlationId);
}
return new CustomAuthResultV2(new MFAVerificationRequiredStateV2({
correlationId: result.correlationId,
logger,
config: this.stateParameters.config,
flowClient,
continuationState: result.continuationState,
cacheClient: this.stateParameters.cacheClient,
method: selectedMethod,
sentTo: result.sentTo,
channel: result.channel,
codeLength: result.codeLength,
}), undefined, result.continuationState.scenario);
}
catch (error) {
logger.errorPii(`0ax1kt ${error}`, correlationId);
return CustomAuthResultV2.createWithError(error, {
errorType: RequestChallengeErrorV2,
scenario: continuationState.scenario,
correlationId,
});
}
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* State returned when first-factor email authentication requires a one-time
* code. It allows the app to submit the code or request a replacement.
*/
class CodeRequiredStateV2 extends ChallengeVerificationStateBaseV2 {
constructor() {
super(...arguments);
this.stateType = "codeRequired";
}
/**
* Submits the first-factor email code and advances the active flow. The
* result may complete the operation or require another flow-specific step.
* @param code - The code to submit.
* @returns The result of submitting the first-factor code.
*/
async submitCode(code) {
const { correlationId, logger, continuationState } = this.stateParameters;
try {
logger.verbose("1x3xae", correlationId);
const result = await this.submitCodeCore(code);
const resultType = result.type;
if (result.type === FLOW_NEW_PASSWORD_REQUIRED_V2) {
return new CustomAuthResultV2(new NewPasswordRequiredStateV2({
correlationId: result.correlationId,
logger,
config: this.stateParameters.config,
flowClient: this.stateParameters.flowClient,
continuationState: result.continuationState,
cacheClient: this.stateParameters.cacheClient,
}), undefined, result.continuationState.scenario);
}
if (result.type === FLOW_ATTRIBUTES_REQUIRED_V2 ||
result.type === FLOW_SIGN_UP_PASSWORD_REQUIRED_V2) {
const signUpStateTransitionHandler = this.stateParameters.signUpStateTransitionHandler;
if (!signUpStateTransitionHandler) {
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, "Sign-up state transition handler is missing.", correlationId);
}
return signUpStateTransitionHandler.handleVerification(result, {
...this.stateParameters,
signUpStateTransitionHandler,
});
}
if (result.type === FLOW_SIGN_IN_CONTINUATION_REQUIRED_V2) {
return new CustomAuthResultV2(new SignInContinuationStateV2({
correlationId: result.correlationId,
logger,
config: this.stateParameters.config,
flowClient: this.stateParameters.flowClient,
continuationState: result.continuationState,
cacheClient: this.stateParameters.cacheClient,
}), undefined, result.continuationState.scenario);
}
if (result.type === FLOW_MFA_REQUIRED_V2) {
return new CustomAuthResultV2(new MFARequiredStateV2({
correlationId: result.correlationId,
logger,
config: this.stateParameters.config,
flowClient: this.stateParameters.flowClient,
continuationState: result.continuationState,
cacheClient: this.stateParameters.cacheClient,
methods: result.methods,
}), undefined, result.continuationState.scenario);
}
if (result.type === FLOW_COMPLETED_V2) {
const account = new CustomAuthAccountData(result.authenticationResult.account, this.stateParameters.config, this.stateParameters.cacheClient, logger, correlationId);
return new CustomAuthResultV2(new CompletedStateV2(), account, continuationState.scenario);
}
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, `Code submission result type '${resultType}' is not supported.`, correlationId);
}
catch (error) {
logger.errorPii(`0br9qy ${error}`, correlationId);
return CustomAuthResultV2.createWithError(error, {
errorType: VerifyChallengeErrorV2,
scenario: continuationState.scenario,
correlationId,
});
}
}
/**
* Requests a replacement first-factor email code. The returned state
* contains the refreshed challenge metadata.
* @returns The result of requesting a replacement code.
*/
async resendCode() {
const { correlationId, logger, continuationState } = this.stateParameters;
try {
logger.verbose("1xub2c", correlationId);
const result = await this.resendCodeCore();
return new CustomAuthResultV2(new CodeRequiredStateV2({
correlationId: result.correlationId,
logger,
config: this.stateParameters.config,
flowClient: this.stateParameters.flowClient,
continuationState: result.continuationState,
cacheClient: this.stateParameters.cacheClient,
signUpStateTransitionHandler: this.stateParameters.signUpStateTransitionHandler,
method: this.method,
sentTo: result.sentTo,
channel: result.channel,
codeLength: result.codeLength,
}), undefined, result.continuationState.scenario);
}
catch (error) {
logger.errorPii(`0eq23q ${error}`, correlationId);
return CustomAuthResultV2.createWithError(error, {
errorType: RequestChallengeErrorV2,
scenario: continuationState.scenario,
correlationId,
});
}
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* State returned when the user must select one of several authentication
* methods before a challenge can be issued. It exposes the list of offered
* methods and lets the app request a challenge for the chosen one. The flow
* stays on this state until a challenge is successfully requested.
*/
class AuthMethodSelectionRequiredStateV2 extends AuthenticationMethodSelectionStateBaseV2 {
constructor() {
super(...arguments);
this.stateType = "authMethodSelectionRequired";
}
/**
* Requests a challenge for the selected authentication method. The returned
* state identifies the credential the application must collect.
* @param method - The method to challenge, from {@link methods}.
* @returns The result of requesting the challenge.
*/
async requestChallenge(method) {
const { correlationId, logger, continuationState, flowClient } = this.stateParameters;
try {
logger.verbose("1r2ypl", correlationId);
const { result, selectedMethod } = await this.requestSelectedMethodChallenge(method);
const resultType = result.type;
const commonStateParameters = {
correlationId: result.correlationId,
logger,
config: this.stateParameters.config,
flowClient,
continuationState: result.continuationState,
cacheClient: this.stateParameters.cacheClient,
};
if (result.type === FLOW_CODE_REQUIRED_V2 &&
(result.channel?.toLowerCase() ===
AuthenticationMethodTypeV2.EMAIL ||
result.channel?.toLowerCase() ===
AuthenticationMethodTypeV2.SMS)) {
return new CustomAuthResultV2(new CodeRequiredStateV2({
...commonStateParameters,
method: selectedMethod,
sentTo: result.sentTo,
channel: result.channel,
codeLength: result.codeLength,
}), undefined, result.continuationState.scenario);
}
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, `Challenge type '${resultType}' with channel '${result.type === FLOW_CODE_REQUIRED_V2
? result.channel
: AuthenticationMethodTypeV2.PASSWORD}' is not supported for password reset.`, correlationId);
}
catch (error) {
logger.errorPii(`0z5x7r ${error}`, correlationId);
return CustomAuthResultV2.createWithError(error, {
errorType: RequestChallengeErrorV2,
scenario: continuationState.scenario,
correlationId,
});
}
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Error raised by the first call of the native auth V2 reset-password flow
* (`resetPasswordV2`). It surfaces only the detectors relevant to starting a
* password reset, so an app inspecting `result.error` sees a small, focused set.
* Any unrecognised failure carries no specific detector; inspect the error code
* (`unexpected_error` when the server gives none) and `errorDescription`.
*/
class ResetPasswordStartErrorV2 extends AuthFlowErrorBaseV2 {
/**
* Checks if the supplied username is empty or invalid.
* @returns True if the username is invalid, false otherwise.
*/
isInvalidUsername() {
return this.isUserInvalidError();
}
/**
* Checks if the error is due to the user not being found. Use it to tell the
* user no account matches the supplied username, rather than exposing a
* generic failure that hides the real cause.
* @returns True if the user was not found, false otherwise.
*/
isUserNotFound() {
return this.isUserNotFoundError();
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Error returned when native auth V2 sign-in cannot start.
*/
class SignInStartErrorV2 extends AuthFlowErrorBaseV2 {
/**
* Checks whether the service rejected the username parameter.
* @returns True when the username was empty or invalid.
*/
isInvalidUsername() {
return this.isUserInvalidError();
}
/**
* Checks whether the supplied username does not identify an account.
* @returns True when the service reports that the user was not found.
*/
isUserNotFound() {
return this.isUserNotFoundError();
}
/**
* Checks whether an automatically submitted password was rejected.
* @returns True when the password is incorrect.
*/
isInvalidPassword() {
return this.isPasswordIncorrectError();
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Error returned when native auth V2 sign-up cannot start. It exposes
* detectors for failures that an app can correct without restarting the flow.
*/
class SignUpStartErrorV2 extends AuthFlowErrorBaseV2 {
/**
* Checks whether an upfront password violates the tenant's password policy.
* Use it to prompt the user for a stronger password.
* @returns True when the password violates policy, otherwise false.
*/
isInvalidPassword() {
return this.isPasswordPolicyViolationError();
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Error returned when a password cannot be submitted for V2 sign-in.
*/
class SubmitPasswordErrorV2 extends AuthFlowErrorBaseV2 {
/**
* Checks whether the supplied password was rejected.
* @returns True when the password is incorrect.
*/
isInvalidPassword() {
return this.isPasswordIncorrectError();
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* State returned when the selected sign-in method requires the user's
* password.
*/
class PasswordRequiredStateV2 extends AuthFlowActionRequiredStateBase {
constructor() {
super(...arguments);
this.stateType = "passwordRequired";
}
/**
* Submits the password and advances sign-in.
* @param password - The account password.
* @returns A completed sign-in, MFA selection, or password submission error.
*/
async submitPassword(password) {
const { correlationId, logger, continuationState, flowClient } = this.stateParameters;
try {
this.ensurePasswordIsNotEmpty(password);
const result = await flowClient.submitSignInPassword({
correlationId,
continuationState,
password,
});
const resultType = result.type;
if (result.type === FLOW_COMPLETED_V2) {
const account = new CustomAuthAccountData(result.authenticationResult.account, this.stateParameters.config, this.stateParameters.cacheClient, logger, correlationId);
return new CustomAuthResultV2(new CompletedStateV2(), account, continuationState.scenario);
}
if (result.type === FLOW_MFA_REQUIRED_V2) {
return new CustomAuthResultV2(new MFARequiredStateV2({
correlationId: result.correlationId,
logger,
config: this.stateParameters.config,
flowClient,
continuationState: result.continuationState,
cacheClient: this.stateParameters.cacheClient,
methods: result.methods,
}), undefined, result.continuationState.scenario);
}
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, `Password verification result type '${resultType}' is not supported.`, correlationId);
}
catch (error) {
logger.errorPii(`0qvjzk ${error}`, correlationId);
return CustomAuthResultV2.createWithError(error, {
errorType: SubmitPasswordErrorV2,
scenario: continuationState.scenario,
correlationId,
});
}
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Error returned when additional V2 sign-up attributes cannot be submitted. It
* identifies attribute failures that an app can correct and resubmit.
*/
class SubmitAttributesErrorV2 extends AuthFlowErrorBaseV2 {
/**
* Checks whether the service requires attributes omitted from the request.
* Use it to collect the required attributes before resubmitting.
* @returns True when required attributes are missing, otherwise false.
*/
isMissingRequiredAttributes() {
return this.getAttributeValidationDetails().some((detail) => detail.code === "attributeRequired");
}
/**
* Checks whether a submitted password violates the tenant's password policy.
* Use it to prompt the user for a stronger password.
* @returns True when the password violates policy, otherwise false.
*/
isInvalidPassword() {
return this.isPasswordPolicyViolationError();
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class SignUpAttributesRequiredStateBaseV2 extends AuthFlowActionRequiredStateBase {
constructor(stateParameters) {
super(stateParameters);
this.attributes = stateParameters.attributes;
}
async submitAttributesAction(attributes) {
const { correlationId, continuationState, flowClient } = this.stateParameters;
return flowClient.submitSignUpAttributes({
correlationId,
continuationState,
attributes,
});
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* State returned when sign-up requires profile or custom attributes.
*/
class AttributesRequiredStateV2 extends SignUpAttributesRequiredStateBaseV2 {
constructor() {
super(...arguments);
this.stateType = "attributesRequired";
}
/**
* Submits the attributes requested by the latest server response.
*/
async submitAttributes(attributes) {
const { correlationId, logger, continuationState } = this.stateParameters;
try {
const result = await this.submitAttributesAction(attributes);
return this.stateParameters.signUpStateTransitionHandler.handleAttributeSubmission(result, this.stateParameters, "attribute");
}
catch (error) {
logger.errorPii(`0l4w01 ${error}`, correlationId);
return CustomAuthResultV2.createWithError(error, {
errorType: SubmitAttributesErrorV2,
scenario: continuationState.scenario,
correlationId,
});
}
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* State returned when sign-up requires a password that was not submitted with
* an earlier attribute request.
*/
class SignUpPasswordRequiredStateV2 extends SignUpAttributesRequiredStateBaseV2 {
constructor(stateParameters) {
super(stateParameters);
this.stateType = "passwordRequired";
this.requiredPasswordAttribute =
stateParameters.requiredPasswordAttribute;
}
/**
* Submits the password and any profile attributes requested alongside it.
*/
async submitPassword(password, attributes = {}) {
const { correlationId, logger, continuationState } = this.stateParameters;
try {
this.ensurePasswordIsNotEmpty(password);
const result = await this.submitAttributesAction({
...attributes,
password,
});
return this.stateParameters.signUpStateTransitionHandler.handleAttributeSubmission(result, this.stateParameters, "password");
}
catch (error) {
logger.errorPii(`07t30r ${error}`, correlationId);
return CustomAuthResultV2.createWithError(error, {
errorType: SubmitAttributesErrorV2,
scenario: continuationState.scenario,
correlationId,
});
}
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class SignUpStateTransitionHandlerV2 {
handleAttributeSubmission(result, stateParameters, submission) {
const commonStateParameters = this.createCommonStateParameters(result, stateParameters);
if (result.type === FLOW_CODE_REQUIRED_V2) {
return new CustomAuthResultV2(new CodeRequiredStateV2({
...commonStateParameters,
sentTo: result.sentTo,
channel: result.channel,
codeLength: result.codeLength,
}), undefined, result.continuationState.scenario);
}
if (result.type === FLOW_SIGN_IN_CONTINUATION_REQUIRED_V2) {
return new CustomAuthResultV2(new SignInContinuationStateV2(commonStateParameters), undefined, result.continuationState.scenario);
}
throw new CustomAuthError(UNSUPPORTED_FLOW_TRANSITION, `Sign-up ${submission} submission result type '${result.type}' is not supported.`, stateParameters.correlationId);
}
handleVerification(result, stateParameters) {
const commonStateParameters = this.createCommonStateParameters(result, stateParameters);
if (result.type === FLOW_ATTRIBUTES_REQUIRED_V2) {
return new CustomAuthResultV2(new AttributesRequiredStateV2({
...commonStateParameters,
attributes: result.attributes,
}), undefined, result.continuationState.scenario);
}
return new CustomAuthResultV2(new SignUpPasswordRequiredStateV2({
...commonStateParameters,
attributes: result.attributes,
requiredPasswordAttribute: result.requiredPasswordAttribute,
}), undefined, result.continuationState.scenario);
}
createCommonStateParameters(result, stateParameters) {
return {
correlationId: result.correlationId,
logger: stateParameters.logger,
config: stateParameters.config,
flowClient: stateParameters.flowClient,
continuationState: result.continuationState,
cacheClient: stateParameters.cacheClient,
signUpStateTransitionHandler: stateParameters.signUpStateTransitionHandler,
};
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Authority class which can be used to create an authority object for Custom Auth features.
*/
class CustomAuthAuthority extends Authority {
/**
* Constructor for the Custom Auth Authority.
* @param authority - The authority URL for the authority.
* @param networkInterface - The network interface implementation to make requests.
* @param cacheManager - The cache manager.
* @param authorityOptions - The options for the authority.
* @param logger - The logger for the authority.
* @param customAuthProxyDomain - The custom auth proxy domain.
*/
constructor(authority, config, networkInterface, cacheManager, logger, performanceClient, customAuthProxyDomain) {
const ciamAuthorityUrl = CustomAuthAuthority.transformCIAMAuthority(authority, "");
const authorityOptions = {
protocolMode: config.system.protocolMode,
OIDCOptions: config.auth.OIDCOptions,
knownAuthorities: config.auth.knownAuthorities,
cloudDiscoveryMetadata: config.auth.cloudDiscoveryMetadata,
authorityMetadata: config.auth.authorityMetadata,
};
super(ciamAuthorityUrl, networkInterface, cacheManager, authorityOptions, logger, "", performanceClient);
this.customAuthProxyDomain = customAuthProxyDomain;
// Set the metadata for the authority
const metadataEntity = {
aliases: [this.hostnameAndPort],
preferred_cache: this.getPreferredCache(),
preferred_network: this.hostnameAndPort,
canonical_authority: this.canonicalAuthority,
authorization_endpoint: "",
token_endpoint: this.tokenEndpoint,
end_session_endpoint: "",
issuer: "",
aliasesFromNetwork: false,
endpointsFromNetwork: false,
/*
* give max value to make sure it doesn't expire,
* as we only initiate the authority metadata entity once and it doesn't change
*/
expiresAt: Number.MAX_SAFE_INTEGER,
jwks_uri: "",
};
const cacheKey = this.cacheManager.generateAuthorityMetadataCacheKey(metadataEntity.preferred_cache, this.correlationId);
cacheManager.setAuthorityMetadata(cacheKey, metadataEntity, this.correlationId);
}
/**
* Gets the custom auth endpoint.
* The open id configuration doesn't have the correct endpoint for the auth APIs.
* We need to generate the endpoint manually based on the authority URL.
* @returns The custom auth endpoint
*/
getCustomAuthApiDomain() {
/*
* The customAuthProxyDomain is used to resolve the CORS issue when calling the auth APIs.
* If the customAuthProxyDomain is not provided, we will generate the auth API domain based on the authority URL.
*/
return !this.customAuthProxyDomain
? this.canonicalAuthority
: this.customAuthProxyDomain;
}
getPreferredCache() {
return this.canonicalAuthorityUrlComponents.HostNameAndPort;
}
get tokenEndpoint() {
const endpointUrl = buildUrl(this.getCustomAuthApiDomain(), SIGNIN_TOKEN);
return endpointUrl.href;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const SIGN_UP_COMPLETED_RESULT_TYPE = "SignUpCompletedResult";
const SIGN_UP_PASSWORD_REQUIRED_RESULT_TYPE = "SignUpPasswordRequiredResult";
const SIGN_UP_CODE_REQUIRED_RESULT_TYPE = "SignUpCodeRequiredResult";
const SIGN_UP_ATTRIBUTES_REQUIRED_RESULT_TYPE = "SignUpAttributesRequiredResult";
function createSignUpCompletedResult(input) {
return {
type: SIGN_UP_COMPLETED_RESULT_TYPE,
...input,
};
}
function createSignUpPasswordRequiredResult(input) {
return {
type: SIGN_UP_PASSWORD_REQUIRED_RESULT_TYPE,
...input,
};
}
function createSignUpCodeRequiredResult(input) {
return {
type: SIGN_UP_CODE_REQUIRED_RESULT_TYPE,
...input,
};
}
function createSignUpAttributesRequiredResult(input) {
return {
type: SIGN_UP_ATTRIBUTES_REQUIRED_RESULT_TYPE,
...input,
};
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class SignUpClient extends CustomAuthInteractionClientBase {
/**
* Starts the sign up flow.
* @param parameters The parameters for the sign up start action.
* @returns The result of the sign up start action.
*/
async start(parameters) {
const correlationId = parameters.correlationId || this.correlationId;
const apiId = !parameters.password
? SIGN_UP_START
: SIGN_UP_WITH_PASSWORD_START;
const telemetryManager = initializeServerTelemetryManager(apiId, this.config.auth.clientId, correlationId, this.browserStorage, this.logger);
const startRequest = {
username: parameters.username,
password: parameters.password,
attributes: parameters.attributes,
challenge_type: this.getChallengeTypes(parameters.challengeType),
telemetryManager,
correlationId: correlationId,
};
this.logger.verbose("1ufort", correlationId);
const startResponse = await this.customAuthApiClient.signUpApi.start(startRequest);
this.logger.verbose("1mzh8i", startResponse.correlation_id || correlationId);
const challengeRequest = {
continuation_token: startResponse.continuation_token ?? "",
challenge_type: this.getChallengeTypes(parameters.challengeType),
telemetryManager,
correlationId: startResponse.correlation_id || correlationId,
};
return this.performChallengeRequest(challengeRequest);
}
/**
* Submits the code for the sign up flow.
* @param parameters The parameters for the sign up submit code action.
* @returns The result of the sign up submit code action.
*/
async submitCode(parameters) {
const correlationId = parameters.correlationId || this.correlationId;
const apiId = SIGN_UP_SUBMIT_CODE;
const telemetryManager = initializeServerTelemetryManager(apiId, this.config.auth.clientId, correlationId, this.browserStorage, this.logger);
const requestSubmitCode = {
continuation_token: parameters.continuationToken,
oob: parameters.code,
telemetryManager,
correlationId: correlationId,
};
const result = await this.performContinueRequest("SignUpClient.submitCode", parameters, telemetryManager, () => this.customAuthApiClient.signUpApi.continueWithCode(requestSubmitCode), correlationId);
if (result.type === SIGN_UP_CODE_REQUIRED_RESULT_TYPE) {
throw new CustomAuthApiError(UNSUPPORTED_CHALLENGE_TYPE, "The challenge type 'oob' is invalid after submtting code for sign up.", result.correlationId || correlationId);
}
return result;
}
/**
* Submits the password for the sign up flow.
* @param parameters The parameters for the sign up submit password action.
* @returns The result of the sign up submit password action.
*/
async submitPassword(parameters) {
const correlationId = parameters.correlationId || this.correlationId;
const apiId = SIGN_UP_SUBMIT_PASSWORD;
const telemetryManager = initializeServerTelemetryManager(apiId, this.config.auth.clientId, correlationId, this.browserStorage, this.logger);
const requestSubmitPwd = {
continuation_token: parameters.continuationToken,
password: parameters.password,
telemetryManager,
correlationId: correlationId,
};
const result = await this.performContinueRequest("SignUpClient.submitPassword", parameters, telemetryManager, () => this.customAuthApiClient.signUpApi.continueWithPassword(requestSubmitPwd), correlationId);
if (result.type === SIGN_UP_PASSWORD_REQUIRED_RESULT_TYPE) {
throw new CustomAuthApiError(UNSUPPORTED_CHALLENGE_TYPE, "The challenge type 'password' is invalid after submtting password for sign up.", result.correlationId || correlationId);
}
return result;
}
/**
* Submits the attributes for the sign up flow.
* @param parameters The parameters for the sign up submit attributes action.
* @returns The result of the sign up submit attributes action.
*/
async submitAttributes(parameters) {
const correlationId = parameters.correlationId || this.correlationId;
const apiId = SIGN_UP_SUBMIT_ATTRIBUTES;
const telemetryManager = initializeServerTelemetryManager(apiId, this.config.auth.clientId, correlationId, this.browserStorage, this.logger);
const reqWithAttr = {
continuation_token: parameters.continuationToken,
attributes: parameters.attributes,
telemetryManager,
correlationId: correlationId,
};
const result = await this.performContinueRequest("SignUpClient.submitAttributes", parameters, telemetryManager, () => this.customAuthApiClient.signUpApi.continueWithAttributes(reqWithAttr), correlationId);
if (result.type === SIGN_UP_ATTRIBUTES_REQUIRED_RESULT_TYPE) {
throw new CustomAuthApiError(ATTRIBUTES_REQUIRED, "User attributes required", result.correlationId || correlationId, [], "", result.requiredAttributes, result.continuationToken);
}
return result;
}
/**
* Resends the code for the sign up flow.
* @param parameters The parameters for the sign up resend code action.
* @returns The result of the sign up resend code action.
*/
async resendCode(parameters) {
const correlationId = parameters.correlationId || this.correlationId;
const apiId = SIGN_UP_RESEND_CODE;
const telemetryManager = initializeServerTelemetryManager(apiId, this.config.auth.clientId, correlationId, this.browserStorage, this.logger);
const challengeRequest = {
continuation_token: parameters.continuationToken ?? "",
challenge_type: this.getChallengeTypes(parameters.challengeType),
telemetryManager,
correlationId: correlationId,
};
const result = await this.performChallengeRequest(challengeRequest);
if (result.type === SIGN_UP_PASSWORD_REQUIRED_RESULT_TYPE) {
throw new CustomAuthApiError(UNSUPPORTED_CHALLENGE_TYPE, "The challenge type 'password' is invalid after resending code for sign up.", result.correlationId || correlationId);
}
return result;
}
async performChallengeRequest(request) {
this.logger.verbose("0wfw94", request.correlationId);
const challengeResponse = await this.customAuthApiClient.signUpApi.requestChallenge(request);
this.logger.verbose("1izuav", challengeResponse.correlation_id || request.correlationId);
if (challengeResponse.challenge_type === ChallengeType.OOB) {
// Code is required
this.logger.verbose("0ucygy", challengeResponse.correlation_id || request.correlationId);
return createSignUpCodeRequiredResult({
correlationId: challengeResponse.correlation_id || request.correlationId,
continuationToken: challengeResponse.continuation_token ?? "",
challengeChannel: challengeResponse.challenge_channel ?? "",
challengeTargetLabel: challengeResponse.challenge_target_label ?? "",
codeLength: challengeResponse.code_length ??
DefaultCustomAuthApiCodeLength,
interval: challengeResponse.interval ??
DefaultCustomAuthApiCodeResendIntervalInSec,
bindingMethod: challengeResponse.binding_method ?? "",
});
}
if (challengeResponse.challenge_type === ChallengeType.PASSWORD) {
// Password is required
this.logger.verbose("11vq5l", challengeResponse.correlation_id || request.correlationId);
return createSignUpPasswordRequiredResult({
correlationId: challengeResponse.correlation_id || request.correlationId,
continuationToken: challengeResponse.continuation_token ?? "",
});
}
this.logger.error(`0wg2fe ${challengeResponse.challenge_type}`, challengeResponse.correlation_id || request.correlationId);
throw new CustomAuthApiError(UNSUPPORTED_CHALLENGE_TYPE, `Unsupported challenge type '${challengeResponse.challenge_type}'.`, challengeResponse.correlation_id || request.correlationId);
}
async performContinueRequest(callerName, requestParams, telemetryManager, responseGetter, requestCorrelationId) {
this.logger.verbose(`0sw5ym ${callerName}`, requestCorrelationId);
try {
const response = await responseGetter();
this.logger.verbose(`0ib062 ${callerName}`, response.correlation_id || requestCorrelationId);
return createSignUpCompletedResult({
correlationId: response.correlation_id || requestCorrelationId,
continuationToken: response.continuation_token ?? "",
});
}
catch (error) {
if (error instanceof CustomAuthApiError) {
return this.handleContinueResponseError(error, error.correlationId || requestCorrelationId, requestParams, telemetryManager);
}
else {
this.logger.errorPii(`03rje8 ${callerName} ${error}`, requestCorrelationId);
throw new UnexpectedError(error, requestCorrelationId);
}
}
}
async handleContinueResponseError(responseError, correlationId, requestParams, telemetryManager) {
if (responseError.error ===
CREDENTIAL_REQUIRED &&
!!responseError.errorCodes &&
responseError.errorCodes.includes(55103)) {
// Credential is required
this.logger.verbose("164mmt", correlationId);
const continuationToken = this.readContinuationTokenFromResponeError(responseError, correlationId);
// Call the challenge endpoint to ensure the password challenge type is supported.
const challengeRequest = {
continuation_token: continuationToken,
challenge_type: this.getChallengeTypes(requestParams.challengeType),
telemetryManager,
correlationId,
};
const challengeResult = await this.performChallengeRequest(challengeRequest);
if (challengeResult.type === SIGN_UP_PASSWORD_REQUIRED_RESULT_TYPE) {
return createSignUpPasswordRequiredResult({
correlationId: challengeResult.correlationId || correlationId,
continuationToken: challengeResult.continuationToken,
});
}
if (challengeResult.type === SIGN_UP_CODE_REQUIRED_RESULT_TYPE) {
return createSignUpCodeRequiredResult({
correlationId: challengeResult.correlationId || correlationId,
continuationToken: challengeResult.continuationToken,
challengeChannel: challengeResult.challengeChannel,
challengeTargetLabel: challengeResult.challengeTargetLabel,
codeLength: challengeResult.codeLength,
interval: challengeResult.interval,
bindingMethod: challengeResult.bindingMethod,
});
}
throw new CustomAuthApiError(UNSUPPORTED_CHALLENGE_TYPE, "The challenge type is not supported.", correlationId);
}
if (this.isAttributesRequiredError(responseError, correlationId)) {
// Attributes are required
this.logger.verbose("13zvmd", correlationId);
const continuationToken = this.readContinuationTokenFromResponeError(responseError, correlationId);
return createSignUpAttributesRequiredResult({
correlationId: correlationId,
continuationToken: continuationToken,
requiredAttributes: responseError.attributes ?? [],
});
}
throw responseError;
}
isAttributesRequiredError(responseError, correlationId) {
if (responseError.error === ATTRIBUTES_REQUIRED) {
if (!responseError.attributes ||
responseError.attributes.length === 0) {
throw new CustomAuthApiError(INVALID_RESPONSE_BODY$1, "Attributes are required but required_attributes field is missing in the response body.", correlationId);
}
return true;
}
return false;
}
readContinuationTokenFromResponeError(responseError, correlationId) {
if (!responseError.continuationToken) {
throw new CustomAuthApiError(CONTINUATION_TOKEN_MISSING$1, "Continuation token is missing in the response body", correlationId);
}
return responseError.continuationToken;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class CustomAuthInterationClientFactory {
constructor(config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, performanceClient, customAuthApiClient, customAuthAuthority, tokenBindingKeyManager) {
this.config = config;
this.storageImpl = storageImpl;
this.browserCrypto = browserCrypto;
this.logger = logger;
this.eventHandler = eventHandler;
this.navigationClient = navigationClient;
this.performanceClient = performanceClient;
this.customAuthApiClient = customAuthApiClient;
this.customAuthAuthority = customAuthAuthority;
this.tokenBindingKeyManager = tokenBindingKeyManager;
}
create(clientConstructor) {
return new clientConstructor(this.config, this.storageImpl, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, this.performanceClient, this.customAuthApiClient, this.customAuthAuthority, this.tokenBindingKeyManager);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class BaseApiClient {
constructor(baseUrl, clientId, httpClient, customAuthApiQueryParams, requestInterceptor, logger) {
this.clientId = clientId;
this.httpClient = httpClient;
this.customAuthApiQueryParams = customAuthApiQueryParams;
this.requestInterceptor = requestInterceptor;
this.logger = logger;
this.baseRequestUrl = parseUrl(!baseUrl.endsWith("/") ? `${baseUrl}/` : baseUrl);
}
async request(endpoint, data, telemetryManager, correlationId) {
const formData = new URLSearchParams({
client_id: this.clientId,
...data,
});
const commonHeaders = this.getCommonHeaders(correlationId, telemetryManager);
const url = buildUrl(this.baseRequestUrl.href, endpoint, this.customAuthApiQueryParams);
const additionalHeaders = await this.getAdditionalHeaders(url, correlationId);
const headers = { ...commonHeaders, ...additionalHeaders };
let response;
try {
response = await this.httpClient.post(url, formData, headers);
}
catch (e) {
throw new CustomAuthApiError(HTTP_REQUEST_FAILED$1, `Failed to perform '${endpoint}' request: ${e}`, correlationId);
}
return this.handleApiResponse(response, correlationId);
}
ensureContinuationTokenIsValid(continuationToken, correlationId) {
if (!continuationToken) {
throw new CustomAuthApiError(CONTINUATION_TOKEN_MISSING$1, "Continuation token is missing in the response body", correlationId);
}
}
readResponseCorrelationId(response, requestCorrelationId) {
return (response.headers.get(HttpHeaderKeys.X_MS_REQUEST_ID) ||
requestCorrelationId);
}
getCommonHeaders(correlationId, telemetryManager) {
return {
[HttpHeaderKeys.CONTENT_TYPE]: "application/x-www-form-urlencoded",
[X_CLIENT_SKU]: DefaultPackageInfo.SKU,
[X_CLIENT_VER]: DefaultPackageInfo.VERSION,
[X_CLIENT_OS]: DefaultPackageInfo.OS,
[X_CLIENT_CPU]: DefaultPackageInfo.CPU,
[X_CLIENT_CURR_TELEM]: telemetryManager.generateCurrentRequestHeaderValue(),
[X_CLIENT_LAST_TELEM]: telemetryManager.generateLastRequestHeaderValue(),
[CLIENT_REQUEST_ID]: correlationId,
};
}
async handleApiResponse(response, requestCorrelationId) {
if (!response) {
throw new CustomAuthApiError("empty_response", "Response is empty", requestCorrelationId);
}
const correlationId = this.readResponseCorrelationId(response, requestCorrelationId);
const responseData = await response.json();
if (response.ok) {
// Ensure the response doesn't have redirect challenge type
if (typeof responseData === "object" &&
responseData.challenge_type === ChallengeType.REDIRECT) {
throw new RedirectError(correlationId, responseData.redirect_reason);
}
return {
...responseData,
correlation_id: correlationId,
};
}
const responseError = responseData;
if (!responseError) {
throw new CustomAuthApiError(INVALID_RESPONSE_BODY$1, "Response error body is empty or invalid", correlationId);
}
const attributes = !!responseError.required_attributes &&
responseError.required_attributes.length > 0
? responseError.required_attributes
: responseError.invalid_attributes ?? [];
throw new CustomAuthApiError(responseError.error, responseError.error_description, responseError.correlation_id, responseError.error_codes, responseError.suberror, attributes, responseError.continuation_token, responseError.trace_id, responseError.timestamp);
}
async getAdditionalHeaders(url, correlationId) {
if (!this.requestInterceptor) {
return {};
}
try {
const result = await Promise.resolve(this.requestInterceptor.addAdditionalHeaderFields(url));
return filterCustomHeaders(result, this.logger, correlationId);
}
catch (e) {
this.logger?.warningPii(`1ptwx4 ${e}`, correlationId);
return {};
}
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class ResetPasswordApiClient extends BaseApiClient {
constructor(customAuthApiBaseUrl, clientId, httpClient, capabilities, customAuthApiQueryParams, requestInterceptor, logger) {
super(customAuthApiBaseUrl, clientId, httpClient, customAuthApiQueryParams, requestInterceptor, logger);
this.capabilities = capabilities;
}
/**
* Start the password reset flow
*/
async start(params) {
const result = await this.request(RESET_PWD_START, {
challenge_type: params.challenge_type,
username: params.username,
...(this.capabilities && {
capabilities: this.capabilities,
}),
}, params.telemetryManager, params.correlationId);
this.ensureContinuationTokenIsValid(result.continuation_token, params.correlationId);
return result;
}
/**
* Request a challenge (OTP) to be sent to the user's email
* @param ChallengeResetPasswordRequest Parameters for the challenge request
*/
async requestChallenge(params) {
const result = await this.request(RESET_PWD_CHALLENGE, {
challenge_type: params.challenge_type,
continuation_token: params.continuation_token,
}, params.telemetryManager, params.correlationId);
this.ensureContinuationTokenIsValid(result.continuation_token, params.correlationId);
return result;
}
/**
* Submit the code for verification
* @param ContinueResetPasswordRequest Token from previous response
*/
async continueWithCode(params) {
const result = await this.request(RESET_PWD_CONTINUE, {
continuation_token: params.continuation_token,
grant_type: GrantType.OOB,
oob: params.oob,
}, params.telemetryManager, params.correlationId);
this.ensureContinuationTokenIsValid(result.continuation_token, params.correlationId);
return result;
}
/**
* Submit the new password
* @param SubmitResetPasswordResponse Token from previous response
*/
async submitNewPassword(params) {
const result = await this.request(RESET_PWD_SUBMIT, {
continuation_token: params.continuation_token,
new_password: params.new_password,
}, params.telemetryManager, params.correlationId);
this.ensureContinuationTokenIsValid(result.continuation_token, params.correlationId);
if (result.poll_interval === 0) {
result.poll_interval = 2;
}
return result;
}
/**
* Poll for password reset completion status
* @param continuationToken Token from previous response
*/
async pollCompletion(params) {
const result = await this.request(RESET_PWD_POLL, {
continuation_token: params.continuation_token,
}, params.telemetryManager, params.correlationId);
this.ensurePollStatusIsValid(result.status, params.correlationId);
return result;
}
ensurePollStatusIsValid(status, correlationId) {
if (status !== ResetPasswordPollStatus.FAILED &&
status !== ResetPasswordPollStatus.IN_PROGRESS &&
status !== ResetPasswordPollStatus.SUCCEEDED &&
status !== ResetPasswordPollStatus.NOT_STARTED) {
throw new CustomAuthApiError(INVALID_POLL_STATUS, `The poll status '${status}' for password reset is invalid`, correlationId);
}
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class SignupApiClient extends BaseApiClient {
constructor(customAuthApiBaseUrl, clientId, httpClient, capabilities, customAuthApiQueryParams, requestInterceptor, logger) {
super(customAuthApiBaseUrl, clientId, httpClient, customAuthApiQueryParams, requestInterceptor, logger);
this.capabilities = capabilities;
}
/**
* Start the sign-up flow
*/
async start(params) {
const result = await this.request(SIGNUP_START, {
username: params.username,
...(params.password && { password: params.password }),
...(params.attributes && {
attributes: JSON.stringify(params.attributes),
}),
challenge_type: params.challenge_type,
...(this.capabilities && {
capabilities: this.capabilities,
}),
}, params.telemetryManager, params.correlationId);
this.ensureContinuationTokenIsValid(result.continuation_token, params.correlationId);
return result;
}
/**
* Request challenge (e.g., OTP)
*/
async requestChallenge(params) {
const result = await this.request(SIGNUP_CHALLENGE, {
continuation_token: params.continuation_token,
challenge_type: params.challenge_type,
}, params.telemetryManager, params.correlationId);
this.ensureContinuationTokenIsValid(result.continuation_token, params.correlationId);
return result;
}
/**
* Continue sign-up flow with code.
*/
async continueWithCode(params) {
const result = await this.request(SIGNUP_CONTINUE, {
continuation_token: params.continuation_token,
grant_type: GrantType.OOB,
oob: params.oob,
}, params.telemetryManager, params.correlationId);
this.ensureContinuationTokenIsValid(result.continuation_token, params.correlationId);
return result;
}
async continueWithPassword(params) {
const result = await this.request(SIGNUP_CONTINUE, {
continuation_token: params.continuation_token,
grant_type: GrantType.PASSWORD,
password: params.password,
}, params.telemetryManager, params.correlationId);
this.ensureContinuationTokenIsValid(result.continuation_token, params.correlationId);
return result;
}
async continueWithAttributes(params) {
const result = await this.request(SIGNUP_CONTINUE, {
continuation_token: params.continuation_token,
grant_type: GrantType.ATTRIBUTES,
attributes: JSON.stringify(params.attributes),
}, params.telemetryManager, params.correlationId);
this.ensureContinuationTokenIsValid(result.continuation_token, params.correlationId);
return result;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class SignInApiClient extends BaseApiClient {
constructor(customAuthApiBaseUrl, clientId, httpClient, capabilities, customAuthApiQueryParams, requestInterceptor, logger) {
super(customAuthApiBaseUrl, clientId, httpClient, customAuthApiQueryParams, requestInterceptor, logger);
this.capabilities = capabilities;
}
/**
* Initiates the sign-in flow
* @param username User's email
* @param authMethod 'email-otp' | 'email-password'
*/
async initiate(params) {
const result = await this.request(SIGNIN_INITIATE, {
username: params.username,
challenge_type: params.challenge_type,
...(this.capabilities && {
capabilities: this.capabilities,
}),
}, params.telemetryManager, params.correlationId);
this.ensureContinuationTokenIsValid(result.continuation_token, params.correlationId);
return result;
}
/**
* Requests authentication challenge (OTP or password validation)
* @param continuationToken Token from initiate response
* @param authMethod 'email-otp' | 'email-password'
*/
async requestChallenge(params) {
const result = await this.request(SIGNIN_CHALLENGE, {
continuation_token: params.continuation_token,
challenge_type: params.challenge_type,
...(params.id && { id: params.id }),
}, params.telemetryManager, params.correlationId);
this.ensureContinuationTokenIsValid(result.continuation_token, params.correlationId);
return result;
}
/**
* Requests security tokens using either password or OTP
* @param continuationToken Token from challenge response
* @param credentials Password or OTP
* @param authMethod 'email-otp' | 'email-password'
*/
async requestTokensWithPassword(params) {
return this.requestTokens({
continuation_token: params.continuation_token,
grant_type: GrantType.PASSWORD,
scope: params.scope,
password: params.password,
...(params.claims && { claims: params.claims }),
}, params.telemetryManager, params.correlationId);
}
async requestTokensWithOob(params) {
return this.requestTokens({
continuation_token: params.continuation_token,
scope: params.scope,
oob: params.oob,
grant_type: params.grant_type,
...(params.claims && { claims: params.claims }),
}, params.telemetryManager, params.correlationId);
}
async requestTokenWithContinuationToken(params) {
return this.requestTokens({
continuation_token: params.continuation_token,
scope: params.scope,
grant_type: GrantType.CONTINUATION_TOKEN,
...(params.claims && { claims: params.claims }),
...(params.username && { username: params.username }),
}, params.telemetryManager, params.correlationId);
}
/**
* Requests available authentication methods for MFA
* @param continuationToken Token from previous response
*/
async requestAuthMethods(params) {
const result = await this.request(SIGNIN_INTROSPECT, {
continuation_token: params.continuation_token,
}, params.telemetryManager, params.correlationId);
this.ensureContinuationTokenIsValid(result.continuation_token, params.correlationId);
return result;
}
async requestTokens(requestData, telemetryManager, correlationId) {
// The client_info parameter is required for MSAL to return the uid and utid in the response.
requestData.client_info = "1";
const result = await this.request(SIGNIN_TOKEN, requestData, telemetryManager, correlationId);
SignInApiClient.ensureTokenResponseIsValid(result);
return result;
}
static ensureTokenResponseIsValid(tokenResponse) {
let errorCode = "";
let errorDescription = "";
if (!tokenResponse.access_token) {
errorCode = ACCESS_TOKEN_MISSING;
errorDescription = "Access token is missing in the response body";
}
else if (!tokenResponse.id_token) {
errorCode = ID_TOKEN_MISSING;
errorDescription = "Id token is missing in the response body";
}
else if (!tokenResponse.refresh_token) {
errorCode = REFRESH_TOKEN_MISSING;
errorDescription = "Refresh token is missing in the response body";
}
else if (!tokenResponse.expires_in || tokenResponse.expires_in <= 0) {
errorCode = INVALID_EXPIRES_IN;
errorDescription = "Expires in is invalid in the response body";
}
else if (tokenResponse.token_type !== "Bearer") {
errorCode = INVALID_TOKEN_TYPE;
errorDescription = `Token type '${tokenResponse.token_type}' is invalid in the response body`;
}
else if (!tokenResponse.client_info) {
errorCode = CLIENT_INFO_MISSING;
errorDescription = "Client info is missing in the response body";
}
if (!errorCode && !errorDescription) {
return;
}
throw new CustomAuthApiError(errorCode, errorDescription, tokenResponse.correlation_id);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class RegisterApiClient extends BaseApiClient {
/**
* Gets available authentication methods for registration
*/
async introspect(params) {
const result = await this.request(REGISTER_INTROSPECT, {
continuation_token: params.continuation_token,
}, params.telemetryManager, params.correlationId);
this.ensureContinuationTokenIsValid(result.continuation_token, params.correlationId);
return result;
}
/**
* Sends challenge to specified authentication method
*/
async challenge(params) {
const result = await this.request(REGISTER_CHALLENGE, {
continuation_token: params.continuation_token,
challenge_type: params.challenge_type,
challenge_target: params.challenge_target,
...(params.challenge_channel && {
challenge_channel: params.challenge_channel,
}),
}, params.telemetryManager, params.correlationId);
this.ensureContinuationTokenIsValid(result.continuation_token, params.correlationId);
return result;
}
/**
* Submits challenge response and continues registration
*/
async continue(params) {
const result = await this.request(REGISTER_CONTINUE, {
continuation_token: params.continuation_token,
grant_type: params.grant_type,
...(params.oob && { oob: params.oob }),
}, params.telemetryManager, params.correlationId);
this.ensureContinuationTokenIsValid(result.continuation_token, params.correlationId);
return result;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class CustomAuthApiClient {
constructor(customAuthApiBaseUrl, clientId, httpClient, capabilities, customAuthApiQueryParams, requestInterceptor, logger) {
this.signInApi = new SignInApiClient(customAuthApiBaseUrl, clientId, httpClient, capabilities, customAuthApiQueryParams, requestInterceptor, logger);
this.signUpApi = new SignupApiClient(customAuthApiBaseUrl, clientId, httpClient, capabilities, customAuthApiQueryParams, requestInterceptor, logger);
this.resetPasswordApi = new ResetPasswordApiClient(customAuthApiBaseUrl, clientId, httpClient, capabilities, customAuthApiQueryParams, requestInterceptor, logger);
this.registerApi = new RegisterApiClient(customAuthApiBaseUrl, clientId, httpClient, customAuthApiQueryParams, requestInterceptor, logger);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class HttpError extends CustomAuthError {
constructor(error, message, correlationId) {
super(error, message, correlationId);
Object.setPrototypeOf(this, HttpError.prototype);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const NoNetworkConnectivity = "no_network_connectivity";
const FailedSendRequest = "failed_send_request";
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Implementation of IHttpClient using fetch.
*/
class FetchHttpClient {
constructor(logger) {
this.logger = logger;
}
async sendAsync(url, options) {
const headers = options.headers;
const correlationId = headers?.[CLIENT_REQUEST_ID] || "";
try {
this.logger.verbosePii(`17dhbs ${url}`, correlationId);
const startTime = performance.now();
const response = await fetch(url, options);
const endTime = performance.now();
this.logger.verbosePii(`1egykc ${url} ${endTime - startTime} ${response.status}`, correlationId);
return response;
}
catch (e) {
this.logger.errorPii(`0ye3lm ${url} ${e}`, correlationId);
if (!window.navigator.onLine) {
throw new HttpError(NoNetworkConnectivity, `No network connectivity: ${e}`, correlationId);
}
throw new HttpError(FailedSendRequest, `Failed to send request: ${e}`, correlationId);
}
}
async post(url, body, headers = {}) {
return this.sendAsync(url, {
method: HttpMethod.POST,
headers,
body,
});
}
async get(url, headers = {}) {
return this.sendAsync(url, {
method: HttpMethod.GET,
headers,
});
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class ResetPasswordClient extends CustomAuthInteractionClientBase {
/**
* Starts the password reset flow.
* @param parameters The parameters for starting the password reset flow.
* @returns The result of password reset start operation.
*/
async start(parameters) {
const correlationId = parameters.correlationId || this.correlationId;
const apiId = PASSWORD_RESET_START;
const telemetryManager = initializeServerTelemetryManager(apiId, this.config.auth.clientId, correlationId, this.browserStorage, this.logger);
const startRequest = {
challenge_type: this.getChallengeTypes(parameters.challengeType),
username: parameters.username,
correlationId: correlationId,
telemetryManager: telemetryManager,
};
this.logger.verbose("13zstj", correlationId);
const startResponse = await this.customAuthApiClient.resetPasswordApi.start(startRequest);
this.logger.verbose("0wsodm", correlationId);
const challengeRequest = {
continuation_token: startResponse.continuation_token ?? "",
challenge_type: this.getChallengeTypes(parameters.challengeType),
correlationId: startResponse.correlation_id || correlationId,
telemetryManager: telemetryManager,
};
return this.performChallengeRequest(challengeRequest);
}
/**
* Submits the code for password reset.
* @param parameters The parameters for submitting the code for password reset.
* @returns The result of submitting the code for password reset.
*/
async submitCode(parameters) {
const correlationId = parameters.correlationId || this.correlationId;
ensureArgumentIsNotEmptyString("parameters.code", parameters.code, correlationId);
const apiId = PASSWORD_RESET_SUBMIT_CODE;
const telemetryManager = initializeServerTelemetryManager(apiId, this.config.auth.clientId, correlationId, this.browserStorage, this.logger);
const continueRequest = {
continuation_token: parameters.continuationToken,
oob: parameters.code,
correlationId: correlationId,
telemetryManager: telemetryManager,
};
this.logger.verbose("0rnsi3", correlationId);
const response = await this.customAuthApiClient.resetPasswordApi.continueWithCode(continueRequest);
this.logger.verbose("1w9r8y", response.correlation_id);
return {
correlationId: response.correlation_id || correlationId,
continuationToken: response.continuation_token ?? "",
};
}
/**
* Resends the another one-time passcode if the previous one hasn't been verified
* @param parameters The parameters for resending the code for password reset.
* @returns The result of resending the code for password reset.
*/
async resendCode(parameters) {
const correlationId = parameters.correlationId || this.correlationId;
const apiId = PASSWORD_RESET_RESEND_CODE;
const telemetryManager = initializeServerTelemetryManager(apiId, this.config.auth.clientId, correlationId, this.browserStorage, this.logger);
const challengeRequest = {
continuation_token: parameters.continuationToken,
challenge_type: this.getChallengeTypes(parameters.challengeType),
correlationId: correlationId,
telemetryManager: telemetryManager,
};
return this.performChallengeRequest(challengeRequest);
}
/**
* Submits the new password for password reset.
* @param parameters The parameters for submitting the new password for password reset.
* @returns The result of submitting the new password for password reset.
*/
async submitNewPassword(parameters) {
const correlationId = parameters.correlationId || this.correlationId;
ensureArgumentIsNotEmptyString("parameters.newPassword", parameters.newPassword, correlationId);
const apiId = PASSWORD_RESET_SUBMIT_PASSWORD;
const telemetryManager = initializeServerTelemetryManager(apiId, this.config.auth.clientId, correlationId, this.browserStorage, this.logger);
const submitRequest = {
continuation_token: parameters.continuationToken,
new_password: parameters.newPassword,
correlationId: correlationId,
telemetryManager: telemetryManager,
};
this.logger.verbose("060415", correlationId);
const submitResponse = await this.customAuthApiClient.resetPasswordApi.submitNewPassword(submitRequest);
this.logger.verbose("0vmsxm", submitResponse.correlation_id || correlationId);
return this.performPollCompletionRequest(submitResponse.continuation_token ?? "", submitResponse.poll_interval, submitResponse.correlation_id || correlationId, telemetryManager);
}
async performChallengeRequest(request) {
const correlationId = request.correlationId;
this.logger.verbose("0sjpbp", correlationId);
const response = await this.customAuthApiClient.resetPasswordApi.requestChallenge(request);
this.logger.verbose("1l48o7", response.correlation_id || correlationId);
if (response.challenge_type === ChallengeType.OOB) {
// Code is required
this.logger.verbose("1oz986", response.correlation_id || correlationId);
return {
correlationId: response.correlation_id || correlationId,
continuationToken: response.continuation_token ?? "",
challengeChannel: response.challenge_channel ?? "",
challengeTargetLabel: response.challenge_target_label ?? "",
codeLength: response.code_length ?? DefaultCustomAuthApiCodeLength,
bindingMethod: response.binding_method ?? "",
};
}
this.logger.error(`0emdih ${response.challenge_type}`, response.correlation_id || correlationId);
throw new CustomAuthApiError(UNSUPPORTED_CHALLENGE_TYPE, `Unsupported challenge type '${response.challenge_type}'.`, response.correlation_id || correlationId);
}
async performPollCompletionRequest(continuationToken, pollInterval, correlationId, telemetryManager) {
const startTime = performance.now();
while (performance.now() - startTime <
PasswordResetPollingTimeoutInMs) {
const pollRequest = {
continuation_token: continuationToken,
correlationId: correlationId,
telemetryManager: telemetryManager,
};
this.logger.verbose("1hadzp", correlationId);
const pollResponse = await this.customAuthApiClient.resetPasswordApi.pollCompletion(pollRequest);
this.logger.verbose("0cghal", correlationId);
if (pollResponse.status === ResetPasswordPollStatus.SUCCEEDED) {
return {
correlationId: pollResponse.correlation_id,
continuationToken: pollResponse.continuation_token ?? "",
};
}
else if (pollResponse.status === ResetPasswordPollStatus.FAILED) {
throw new CustomAuthApiError(PASSWORD_CHANGE_FAILED, "Password is failed to be reset.", pollResponse.correlation_id);
}
this.logger.verbose(`0ykdlr ${pollInterval}`, correlationId);
await this.delay(pollInterval * 1000);
}
this.logger.error("0v2tkb", correlationId);
throw new CustomAuthApiError(PASSWORD_RESET_TIMEOUT, "Password reset flow has timed out.", correlationId);
}
async delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
// Result type constants
const JIT_VERIFICATION_REQUIRED_RESULT_TYPE = "JitVerificationRequiredResult";
const JIT_COMPLETED_RESULT_TYPE = "JitCompletedResult";
function createJitVerificationRequiredResult(input) {
return {
type: JIT_VERIFICATION_REQUIRED_RESULT_TYPE,
...input,
};
}
function createJitCompletedResult(input) {
return {
type: JIT_COMPLETED_RESULT_TYPE,
...input,
};
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* JIT client for handling just-in-time authentication method registration flows.
*/
class JitClient extends CustomAuthInteractionClientBase {
/**
* Challenges an authentication method for JIT registration.
* @param parameters The parameters for challenging the auth method.
* @returns Promise that resolves to either JitVerificationRequiredResult or JitCompletedResult.
*/
async challengeAuthMethod(parameters) {
const correlationId = parameters.correlationId || this.correlationId;
const apiId = JIT_CHALLENGE_AUTH_METHOD;
const telemetryManager = initializeServerTelemetryManager(apiId, this.config.auth.clientId, correlationId, this.browserStorage, this.logger);
this.logger.verbose("1kxcgm", correlationId);
const challengeReq = {
continuation_token: parameters.continuationToken,
challenge_type: parameters.authMethod.challenge_type,
challenge_target: parameters.verificationContact,
challenge_channel: parameters.authMethod.challenge_channel,
correlationId: correlationId,
telemetryManager: telemetryManager,
};
const challengeResponse = await this.customAuthApiClient.registerApi.challenge(challengeReq);
this.logger.verbose("07vc8z", challengeResponse.correlation_id || correlationId);
/*
* Handle fast-pass scenario (preverified)
* This occurs when the user selects the same email used during sign-up
* Since the email was already verified during sign-up, no additional verification is needed
*/
if (challengeResponse.challenge_type === ChallengeType.PREVERIFIED) {
this.logger.verbose("0tmt75", challengeResponse.correlation_id || correlationId);
// Use submitChallenge for fast-pass scenario with continuation_token grant type
const fastPassParams = {
correlationId: challengeResponse.correlation_id || correlationId,
continuationToken: challengeResponse.continuation_token,
grantType: GrantType.CONTINUATION_TOKEN,
scopes: parameters.scopes,
username: parameters.username,
claims: parameters.claims,
};
const completedResult = await this.submitChallenge(fastPassParams);
return completedResult;
}
// Verification required
return createJitVerificationRequiredResult({
correlationId: challengeResponse.correlation_id || correlationId,
continuationToken: challengeResponse.continuation_token,
challengeChannel: challengeResponse.challenge_channel,
challengeTargetLabel: challengeResponse.challenge_target,
codeLength: challengeResponse.code_length || DefaultCustomAuthApiCodeLength,
});
}
/**
* Submits challenge response and completes JIT registration.
* @param parameters The parameters for submitting the challenge.
* @returns Promise that resolves to JitCompletedResult.
*/
async submitChallenge(parameters) {
const correlationId = parameters.correlationId || this.correlationId;
const apiId = JIT_SUBMIT_CHALLENGE;
const telemetryManager = initializeServerTelemetryManager(apiId, this.config.auth.clientId, correlationId, this.browserStorage, this.logger);
this.logger.verbose("1l3zg1", correlationId);
// Submit challenge to complete registration
const continueReq = {
continuation_token: parameters.continuationToken,
grant_type: parameters.grantType,
...(parameters.challenge && {
oob: parameters.challenge,
}),
correlationId: correlationId,
telemetryManager: telemetryManager,
};
const continueResponse = await this.customAuthApiClient.registerApi.continue(continueReq);
this.logger.verbose("10bc4x", parameters.correlationId);
// Use continuation token to get authentication tokens
const scopes = this.getScopes(parameters.scopes);
const tokenRequest = {
continuation_token: continueResponse.continuation_token,
scope: scopes.join(" "),
correlationId: continueResponse.correlation_id || correlationId,
telemetryManager: telemetryManager,
...(parameters.claims && {
claims: parameters.claims,
}),
};
const tokenResponse = await this.customAuthApiClient.signInApi.requestTokenWithContinuationToken(tokenRequest);
const authResult = await this.handleTokenResponse(tokenResponse, scopes, tokenResponse.correlation_id ||
continueResponse.correlation_id ||
correlationId, apiId);
return createJitCompletedResult({
correlationId: continueResponse.correlation_id || correlationId,
authenticationResult: authResult,
});
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
// Result type constants
const MFA_VERIFICATION_REQUIRED_RESULT_TYPE = "MfaVerificationRequiredResult";
const MFA_COMPLETED_RESULT_TYPE = "MfaCompletedResult";
function createMfaVerificationRequiredResult(input) {
return {
type: MFA_VERIFICATION_REQUIRED_RESULT_TYPE,
...input,
};
}
function createMfaCompletedResult(input) {
return {
type: MFA_COMPLETED_RESULT_TYPE,
...input,
};
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* MFA client for handling multi-factor authentication flows.
*/
class MfaClient extends CustomAuthInteractionClientBase {
/**
* Requests an MFA challenge to be sent to the user.
* @param parameters The parameters for requesting the challenge.
* @returns Promise that resolves to either MfaVerificationRequiredResult.
*/
async requestChallenge(parameters) {
const apiId = MFA_REQUEST_CHALLENGE;
const correlationId = parameters.correlationId || this.correlationId;
const telemetryManager = initializeServerTelemetryManager(apiId, this.config.auth.clientId, correlationId, this.browserStorage, this.logger);
this.logger.verbose("1cbc4t", correlationId);
const challengeReq = {
challenge_type: this.getChallengeTypes(parameters.challengeType),
continuation_token: parameters.continuationToken,
id: parameters.authMethodId,
correlationId: correlationId,
telemetryManager: telemetryManager,
};
const challengeResponse = await this.customAuthApiClient.signInApi.requestChallenge(challengeReq);
this.logger.verbose("0egw9i", correlationId);
if (challengeResponse.challenge_type === ChallengeType.OOB) {
// Verification required - code will be sent
return createMfaVerificationRequiredResult({
correlationId: challengeResponse.correlation_id || correlationId,
continuationToken: challengeResponse.continuation_token ?? "",
challengeChannel: challengeResponse.challenge_channel ?? "",
challengeTargetLabel: challengeResponse.challenge_target_label ?? "",
codeLength: challengeResponse.code_length ??
DefaultCustomAuthApiCodeLength,
bindingMethod: challengeResponse.binding_method ?? "",
});
}
this.logger.error(`1jifg6 ${challengeResponse.challenge_type}`, challengeResponse.correlation_id || correlationId);
throw new CustomAuthApiError(UNSUPPORTED_CHALLENGE_TYPE, `Unsupported challenge type '${challengeResponse.challenge_type}'.`, challengeResponse.correlation_id || correlationId);
}
/**
* Submits the MFA challenge response (e.g., OTP code).
* @param parameters The parameters for submitting the challenge.
* @returns Promise that resolves to MfaCompletedResult.
*/
async submitChallenge(parameters) {
const correlationId = parameters.correlationId || this.correlationId;
ensureArgumentIsNotEmptyString("parameters.challenge", parameters.challenge, correlationId);
const apiId = MFA_SUBMIT_CHALLENGE;
const telemetryManager = initializeServerTelemetryManager(apiId, this.config.auth.clientId, correlationId, this.browserStorage, this.logger);
const scopes = this.getScopes(parameters.scopes);
const request = {
continuation_token: parameters.continuationToken,
oob: parameters.challenge,
grant_type: GrantType.MFA_OOB,
scope: scopes.join(" "),
correlationId: correlationId,
telemetryManager: telemetryManager,
...(parameters.claims && {
claims: parameters.claims,
}),
};
this.logger.verbose("1rkonv", correlationId);
const tokenResponse = await this.customAuthApiClient.signInApi.requestTokensWithOob(request);
// Save tokens and create authentication result
const result = await this.handleTokenResponse(tokenResponse, scopes, tokenResponse.correlation_id || correlationId, apiId);
return createMfaCompletedResult({
correlationId: tokenResponse.correlation_id || correlationId,
authenticationResult: result,
});
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class UserAlreadySignedInError extends CustomAuthError {
constructor(correlationId) {
super("user_already_signed_in", "The user has already signed in.", correlationId);
Object.setPrototypeOf(this, UserAlreadySignedInError.prototype);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class CustomAuthSilentCacheClient extends CustomAuthInteractionClientBase {
/**
* Acquires a token from the cache if it is not expired. Otherwise, makes a request to renew the token.
* If forceRresh is set to false, then looks up the access token in cache first.
* If access token is expired or not found, then uses refresh token to get a new access token.
* If no refresh token is found or it is expired, then throws error.
* If forceRefresh is set to true, then skips token cache lookup and fetches a new token using refresh token
* If no refresh token is found or it is expired, then throws error.
* @param silentRequest The silent request object.
* @returns {Promise<AuthenticationResult>} The promise that resolves to an AuthenticationResult.
*/
async acquireToken(silentRequest) {
const correlationId = silentRequest.correlationId || this.correlationId;
const telemetryManager = initializeServerTelemetryManager(ACCOUNT_GET_ACCESS_TOKEN, this.config.auth.clientId, correlationId, this.browserStorage, this.logger, silentRequest.forceRefresh);
const clientConfig = this.getCustomAuthClientConfiguration(telemetryManager, this.customAuthAuthority, correlationId);
const silentFlowClient = new SilentFlowClient(clientConfig, this.performanceClient);
try {
this.logger.verbose("1arlz4", correlationId);
const result = await silentFlowClient.acquireCachedToken(silentRequest);
this.logger.verbose("1dzrjc", correlationId);
return result[0];
}
catch (error) {
if (error instanceof ClientAuthError &&
error.errorCode === tokenRefreshRequired) {
this.logger.verbose("05sqvp", correlationId);
const refreshTokenClient = new RefreshTokenClient(clientConfig, this.performanceClient);
this.logger.verbose("0ogm3j", correlationId);
const refreshTokenResult = await refreshTokenClient.acquireTokenByRefreshToken(silentRequest, ACCOUNT_GET_ACCESS_TOKEN);
this.logger.verbose("0vydnd", correlationId);
return refreshTokenResult;
}
throw error;
}
}
async logout(logoutRequest) {
const validLogoutRequest = this.initializeLogoutRequest(logoutRequest);
const correlationId = logoutRequest?.correlationId || this.correlationId;
// Clear the cache
this.logger.verbose("02fvrq", correlationId);
await clearCacheOnLogout(this.browserStorage, this.browserCrypto, this.logger, correlationId, validLogoutRequest?.account);
this.logger.verbose("12w2ul", correlationId);
const postLogoutRedirectUri = this.config.auth.postLogoutRedirectUri;
if (postLogoutRedirectUri) {
const absoluteRedirectUri = UrlString.getAbsoluteUrl(postLogoutRedirectUri, getCurrentUri(), correlationId);
this.logger.verbose("1fgk77", correlationId);
// Redirect to post logout redirect uri
await this.navigationClient.navigateExternal(absoluteRedirectUri, {
apiId: ApiId.logout,
timeout: this.config.system.redirectNavigationTimeout,
noHistory: false,
});
}
}
getCurrentAccount(correlationId) {
let account = null;
this.logger.verbose("1ry0zt", correlationId);
const allAccounts = this.browserStorage.getAllAccounts({}, correlationId);
if (allAccounts.length > 0) {
if (allAccounts.length !== 1) {
this.logger.warning("0rh9ou", correlationId);
}
account = allAccounts[0];
}
if (account) {
this.logger.verbose("1utnrc", correlationId);
}
else {
this.logger.verbose("0w3jks", correlationId);
}
return account;
}
getCustomAuthClientConfiguration(serverTelemetryManager, customAuthAuthority, correlationId) {
const logger = this.config.system.loggerOptions;
return {
authOptions: {
clientId: this.config.auth.clientId,
authority: customAuthAuthority,
clientCapabilities: this.config.auth.clientCapabilities,
redirectUri: this.config.auth.redirectUri,
},
systemOptions: {
tokenRenewalOffsetSeconds: this.config.system.tokenRenewalOffsetSeconds,
preventCorsPreflight: true,
},
loggerOptions: {
loggerCallback: logger.loggerCallback,
piiLoggingEnabled: logger.piiLoggingEnabled,
logLevel: logger.logLevel,
correlationId: correlationId,
},
cryptoInterface: this.browserCrypto,
tokenBindingKeyManager: this.tokenBindingKeyManager,
networkInterface: this.networkClient,
storageInterface: this.browserStorage,
serverTelemetryManager: serverTelemetryManager,
libraryInfo: {
sku: DefaultPackageInfo.SKU,
version: DefaultPackageInfo.VERSION,
cpu: DefaultPackageInfo.CPU,
os: DefaultPackageInfo.OS,
},
telemetry: this.config.telemetry,
};
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class UnsupportedEnvironmentError extends CustomAuthError {
constructor(correlationId) {
super("unsupported_env", "The current environment is not browser", correlationId);
Object.setPrototypeOf(this, UnsupportedEnvironmentError.prototype);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class SignInResendCodeResult extends AuthFlowResultBase {
/**
* Creates a new instance of SignInResendCodeResult.
* @param state The state of the result.
*/
constructor(state) {
super(state);
}
/**
* Creates a new instance of SignInResendCodeResult with an error.
* @param error The error that occurred.
* @returns {SignInResendCodeResult} A new instance of SignInResendCodeResult with the error set.
*/
static createWithError(error) {
const result = new SignInResendCodeResult(new SignInFailedState());
result.error = new SignInResendCodeError(SignInResendCodeResult.createErrorData(error));
return result;
}
/**
* Checks if the result is in a failed state.
*/
isFailed() {
return this.state.stateType === SIGN_IN_FAILED_STATE_TYPE;
}
/**
* Checks if the result is in a code required state.
*/
isCodeRequired() {
/*
* The instanceof operator couldn't be used here to check the state type since the circular dependency issue.
* So we are using the constructor name to check the state type.
*/
return this.state.stateType === SIGN_IN_CODE_REQUIRED_STATE_TYPE;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Result of a sign-in submit code operation.
*/
class SignInSubmitCodeResult extends AuthFlowResultBase {
/**
* Creates a new instance of SignInSubmitCodeResult with error data.
* @param error The error that occurred.
* @returns {SignInSubmitCodeResult} A new instance of SignInSubmitCodeResult with the error set.
*/
static createWithError(error) {
const result = new SignInSubmitCodeResult(new SignInFailedState());
result.error = new SignInSubmitCodeError(SignInSubmitCodeResult.createErrorData(error));
return result;
}
/**
* Checks if the result is in a failed state.
*/
isFailed() {
return this.state.stateType === SIGN_IN_FAILED_STATE_TYPE;
}
/**
* Checks if the result is in a completed state.
*/
isCompleted() {
return this.state.stateType === SIGN_IN_COMPLETED_STATE_TYPE;
}
/**
* Checks if the result requires authentication method registration.
* @warning This API is experimental. It may be changed in the future without notice. Do not use in production applications.
*/
isAuthMethodRegistrationRequired() {
return (this.state.stateType ===
AUTH_METHOD_REGISTRATION_REQUIRED_STATE_TYPE);
}
/**
* Checks if the result requires MFA.
* @warning This API is experimental. It may be changed in the future without notice. Do not use in production applications.
*/
isMfaRequired() {
return this.state.stateType === MFA_AWAITING_STATE_TYPE;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Error that occurred during authentication method challenge request.
*/
class AuthMethodRegistrationChallengeMethodError extends AuthActionErrorBase {
/**
* Checks if the input for auth method registration is incorrect.
* @returns true if the input is incorrect, false otherwise.
*/
isInvalidInput() {
return this.isInvalidInputError();
}
/**
* Checks if the error is due to the verification contact (e.g., phone number or email) being blocked. Consider using a different email/phone number or a different authentication method.
* @returns true if the error is due to the verification contact being blocked, false otherwise.
*/
isVerificationContactBlocked() {
return this.isVerificationContactBlockedError();
}
}
/**
* Error that occurred during authentication method challenge submission.
*/
class AuthMethodRegistrationSubmitChallengeError extends AuthActionErrorBase {
/**
* Checks if the submitted challenge code is incorrect.
* @returns true if the challenge code is incorrect, false otherwise.
*/
isIncorrectChallenge() {
return this.isInvalidCodeError();
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* State indicating that the auth method registration flow has failed.
*/
class AuthMethodRegistrationFailedState extends AuthFlowStateBase {
constructor() {
super(...arguments);
/**
* The type of the state.
*/
this.stateType = AUTH_METHOD_REGISTRATION_FAILED_STATE_TYPE;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Result of challenging an authentication method for registration.
* Uses base state type to avoid circular dependencies.
*/
class AuthMethodRegistrationChallengeMethodResult extends AuthFlowResultBase {
/**
* Creates an AuthMethodRegistrationChallengeMethodResult with an error.
* @param error The error that occurred.
* @returns The AuthMethodRegistrationChallengeMethodResult with error.
*/
static createWithError(error) {
const result = new AuthMethodRegistrationChallengeMethodResult(new AuthMethodRegistrationFailedState());
result.error = new AuthMethodRegistrationChallengeMethodError(AuthMethodRegistrationChallengeMethodResult.createErrorData(error));
return result;
}
/**
* Checks if the result indicates that verification is required.
* @returns true if verification is required, false otherwise.
* @warning This API is experimental. It may be changed in the future without notice. Do not use in production applications.
*/
isVerificationRequired() {
return (this.state.stateType ===
AUTH_METHOD_VERIFICATION_REQUIRED_STATE_TYPE);
}
/**
* Checks if the result indicates that registration is completed (fast-pass scenario).
* @returns true if registration is completed, false otherwise.
* @warning This API is experimental. It may be changed in the future without notice. Do not use in production applications.
*/
isCompleted() {
return (this.state.stateType ===
AUTH_METHOD_REGISTRATION_COMPLETED_STATE_TYPE);
}
/**
* Checks if the result is in a failed state.
* @returns true if the result is failed, false otherwise.
* @warning This API is experimental. It may be changed in the future without notice. Do not use in production applications.
*/
isFailed() {
return (this.state.stateType === AUTH_METHOD_REGISTRATION_FAILED_STATE_TYPE);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Result of submitting a challenge for authentication method registration.
*/
class AuthMethodRegistrationSubmitChallengeResult extends AuthFlowResultBase {
/**
* Creates an AuthMethodRegistrationSubmitChallengeResult with an error.
* @param error The error that occurred.
* @returns The AuthMethodRegistrationSubmitChallengeResult with error.
*/
static createWithError(error) {
const result = new AuthMethodRegistrationSubmitChallengeResult(new AuthMethodRegistrationFailedState());
result.error = new AuthMethodRegistrationSubmitChallengeError(AuthMethodRegistrationSubmitChallengeResult.createErrorData(error));
return result;
}
/**
* Checks if the result indicates that registration is completed.
* @returns true if registration is completed, false otherwise.
* @warning This API is experimental. It may be changed in the future without notice. Do not use in production applications.
*/
isCompleted() {
return (this.state.stateType ===
AUTH_METHOD_REGISTRATION_COMPLETED_STATE_TYPE);
}
/**
* Checks if the result is in a failed state.
* @returns true if the result is failed, false otherwise.
* @warning This API is experimental. It may be changed in the future without notice. Do not use in production applications.
*/
isFailed() {
return (this.state.stateType === AUTH_METHOD_REGISTRATION_FAILED_STATE_TYPE);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* State indicating that the auth method registration flow has completed successfully.
*/
class AuthMethodRegistrationCompletedState extends AuthFlowStateBase {
constructor() {
super(...arguments);
/**
* The type of the state.
*/
this.stateType = AUTH_METHOD_REGISTRATION_COMPLETED_STATE_TYPE;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Abstract base class for authentication method registration states.
*/
class AuthMethodRegistrationState extends AuthFlowActionRequiredStateBase {
/**
* Internal method to challenge an authentication method.
* @param authMethodDetails The authentication method details to challenge.
* @returns Promise that resolves to AuthMethodRegistrationChallengeMethodResult.
*/
async challengeAuthMethodInternal(authMethodDetails) {
try {
this.stateParameters.logger.verbose(`0vi650 ${authMethodDetails.authMethodType.id}`, this.stateParameters.correlationId);
const challengeParams = {
correlationId: this.stateParameters.correlationId,
continuationToken: this.stateParameters.continuationToken ?? "",
authMethod: authMethodDetails.authMethodType,
verificationContact: authMethodDetails.verificationContact,
scopes: this.stateParameters.scopes ?? [],
username: this.stateParameters.username,
claims: this.stateParameters.claims,
};
const result = await this.stateParameters.jitClient.challengeAuthMethod(challengeParams);
this.stateParameters.logger.verbose("1ipjwn", this.stateParameters.correlationId);
if (result.type === JIT_VERIFICATION_REQUIRED_RESULT_TYPE) {
// Verification required
this.stateParameters.logger.verbose("0puifv", this.stateParameters.correlationId);
return new AuthMethodRegistrationChallengeMethodResult(new AuthMethodVerificationRequiredState({
correlationId: result.correlationId,
continuationToken: result.continuationToken,
config: this.stateParameters.config,
logger: this.stateParameters.logger,
jitClient: this.stateParameters.jitClient,
cacheClient: this.stateParameters.cacheClient,
challengeChannel: result.challengeChannel,
challengeTargetLabel: result.challengeTargetLabel,
codeLength: result.codeLength,
scopes: this.stateParameters.scopes ?? [],
username: this.stateParameters.username,
claims: this.stateParameters.claims,
}));
}
else if (result.type === JIT_COMPLETED_RESULT_TYPE) {
// Registration completed (fast-pass scenario)
this.stateParameters.logger.verbose("01b21i", this.stateParameters.correlationId);
const accountInfo = new CustomAuthAccountData(result.authenticationResult.account, this.stateParameters.config, this.stateParameters.cacheClient, this.stateParameters.logger, this.stateParameters.correlationId);
return new AuthMethodRegistrationChallengeMethodResult(new AuthMethodRegistrationCompletedState(), accountInfo);
}
else {
// Handle unexpected result type with proper typing
this.stateParameters.logger.error("16lk12", this.stateParameters.correlationId);
throw new UnexpectedError("Unexpected result type from auth challenge method");
}
}
catch (error) {
this.stateParameters.logger.errorPii(`17im04 ${error}`, this.stateParameters.correlationId);
return AuthMethodRegistrationChallengeMethodResult.createWithError(error);
}
}
}
/**
* State indicating that authentication method registration is required.
*/
class AuthMethodRegistrationRequiredState extends AuthMethodRegistrationState {
constructor() {
super(...arguments);
/**
* The type of the state.
*/
this.stateType = AUTH_METHOD_REGISTRATION_REQUIRED_STATE_TYPE;
}
/**
* Gets the available authentication methods for registration.
* @returns Array of available authentication methods.
* @warning This API is experimental. It may be changed in the future without notice. Do not use in production applications.
*/
getAuthMethods() {
return this.stateParameters.authMethods;
}
/**
* Challenges an authentication method for registration.
* @param authMethodDetails The authentication method details to challenge.
* @returns Promise that resolves to AuthMethodRegistrationChallengeMethodResult.
* @warning This API is experimental. It may be changed in the future without notice. Do not use in production applications.
*/
async challengeAuthMethod(authMethodDetails) {
return this.challengeAuthMethodInternal(authMethodDetails);
}
}
/**
* State indicating that verification is required for the challenged authentication method.
*/
class AuthMethodVerificationRequiredState extends AuthMethodRegistrationState {
constructor() {
super(...arguments);
/**
* The type of the state.
*/
this.stateType = AUTH_METHOD_VERIFICATION_REQUIRED_STATE_TYPE;
}
/**
* Gets the length of the expected verification code.
* @returns The code length.
* @warning This API is experimental. It may be changed in the future without notice. Do not use in production applications.
*/
getCodeLength() {
return this.stateParameters.codeLength;
}
/**
* Gets the channel through which the challenge was sent.
* @returns The challenge channel (e.g., "email").
* @warning This API is experimental. It may be changed in the future without notice. Do not use in production applications.
*/
getChannel() {
return this.stateParameters.challengeChannel;
}
/**
* Gets the target label indicating where the challenge was sent.
* @returns The challenge target label (e.g., masked email address).
* @warning This API is experimental. It may be changed in the future without notice. Do not use in production applications.
*/
getSentTo() {
return this.stateParameters.challengeTargetLabel;
}
/**
* Submits the verification challenge to complete the authentication method registration.
* @param code The verification code entered by the user.
* @returns Promise that resolves to AuthMethodRegistrationSubmitChallengeResult.
* @warning This API is experimental. It may be changed in the future without notice. Do not use in production applications.
*/
async submitChallenge(code) {
try {
this.ensureCodeIsValid(code, this.getCodeLength());
this.stateParameters.logger.verbose("084cxu", this.stateParameters.correlationId);
const submitParams = {
correlationId: this.stateParameters.correlationId,
continuationToken: this.stateParameters.continuationToken ?? "",
scopes: this.stateParameters.scopes ?? [],
grantType: GrantType.OOB,
challenge: code,
username: this.stateParameters.username,
claims: this.stateParameters.claims,
};
const result = await this.stateParameters.jitClient.submitChallenge(submitParams);
this.stateParameters.logger.verbose("0hi8xc", this.stateParameters.correlationId);
const accountInfo = new CustomAuthAccountData(result.authenticationResult.account, this.stateParameters.config, this.stateParameters.cacheClient, this.stateParameters.logger, this.stateParameters.correlationId);
return new AuthMethodRegistrationSubmitChallengeResult(new AuthMethodRegistrationCompletedState(), accountInfo);
}
catch (error) {
this.stateParameters.logger.errorPii(`0njepo ${error}`, this.stateParameters.correlationId);
return AuthMethodRegistrationSubmitChallengeResult.createWithError(error);
}
}
/**
* Challenges a different authentication method for registration.
* @param authMethodDetails The authentication method details to challenge.
* @returns Promise that resolves to AuthMethodRegistrationChallengeMethodResult.
* @warning This API is experimental. It may be changed in the future without notice. Do not use in production applications.
*/
async challengeAuthMethod(authMethodDetails) {
return this.challengeAuthMethodInternal(authMethodDetails);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Error that occurred during MFA challenge request.
*/
class MfaRequestChallengeError extends AuthActionErrorBase {
/**
* Checks if the input for MFA challenge is incorrect.
* @returns true if the input is incorrect, false otherwise.
*/
isInvalidInput() {
return this.isInvalidInputError();
}
/**
* Checks if the error is due to the verification contact (e.g., phone number or email) being blocked. Consider contacting customer support for assistance.
* @returns true if the error is due to the verification contact being blocked, false otherwise.
*/
isVerificationContactBlocked() {
return this.isVerificationContactBlockedError();
}
}
/**
* Error that occurred during MFA challenge submission.
*/
class MfaSubmitChallengeError extends AuthActionErrorBase {
/**
* Checks if the submitted challenge code (e.g., OTP code) is incorrect.
* @returns true if the challenge code is invalid, false otherwise.
*/
isIncorrectChallenge() {
return this.isInvalidCodeError();
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* State indicating that the MFA flow has failed.
*/
class MfaFailedState extends AuthFlowStateBase {
constructor() {
super(...arguments);
/**
* The type of the state.
*/
this.stateType = MFA_FAILED_STATE_TYPE;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Result of submitting an MFA challenge.
*/
class MfaSubmitChallengeResult extends AuthFlowResultBase {
/**
* Creates an MfaSubmitChallengeResult with an error.
* @param error The error that occurred.
* @returns The MfaSubmitChallengeResult with error.
*/
static createWithError(error) {
const result = new MfaSubmitChallengeResult(new MfaFailedState());
result.error = new MfaSubmitChallengeError(MfaSubmitChallengeResult.createErrorData(error));
return result;
}
/**
* Checks if the MFA flow is completed successfully.
* @returns true if completed, false otherwise.
* @warning This API is experimental. It may be changed in the future without notice. Do not use in production applications.
*/
isCompleted() {
return this.state.stateType === MFA_COMPLETED_STATE_TYPE;
}
/**
* Checks if the result is in a failed state.
* @returns true if the result is failed, false otherwise.
* @warning This API is experimental. It may be changed in the future without notice. Do not use in production applications.
*/
isFailed() {
return this.state.stateType === MFA_FAILED_STATE_TYPE;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Result of requesting an MFA challenge.
* Uses base state type to avoid circular dependencies.
*/
class MfaRequestChallengeResult extends AuthFlowResultBase {
/**
* Creates an MfaRequestChallengeResult with an error.
* @param error The error that occurred.
* @returns The MfaRequestChallengeResult with error.
*/
static createWithError(error) {
const result = new MfaRequestChallengeResult(new MfaFailedState());
result.error = new MfaRequestChallengeError(MfaRequestChallengeResult.createErrorData(error));
return result;
}
/**
* Checks if the result indicates that verification is required.
* @returns true if verification is required, false otherwise.
* @warning This API is experimental. It may be changed in the future without notice. Do not use in production applications.
*/
isVerificationRequired() {
return this.state.stateType === MFA_VERIFICATION_REQUIRED_STATE_TYPE;
}
/**
* Checks if the result is in a failed state.
* @returns true if the result is failed, false otherwise.
* @warning This API is experimental. It may be changed in the future without notice. Do not use in production applications.
*/
isFailed() {
return this.state.stateType === MFA_FAILED_STATE_TYPE;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* State indicating that the MFA flow has completed successfully.
*/
class MfaCompletedState extends AuthFlowStateBase {
constructor() {
super(...arguments);
/**
* The type of the state.
*/
this.stateType = MFA_COMPLETED_STATE_TYPE;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class MfaState extends AuthFlowActionRequiredStateBase {
/**
* Requests an MFA challenge for a specific authentication method.
* @param authMethodId The authentication method ID to use for the challenge.
* @returns Promise that resolves to MfaRequestChallengeResult.
* @warning This API is experimental. It may be changed in the future without notice. Do not use in production applications.
*/
async requestChallenge(authMethodId) {
try {
ensureArgumentIsNotEmptyString("authMethodId", authMethodId);
this.stateParameters.logger.verbose(`1cnvk7 ${authMethodId}`, this.stateParameters.correlationId);
const requestParams = {
correlationId: this.stateParameters.correlationId,
continuationToken: this.stateParameters.continuationToken ?? "",
challengeType: this.stateParameters.config.customAuth.challengeTypes ?? [],
authMethodId: authMethodId,
};
const result = await this.stateParameters.mfaClient.requestChallenge(requestParams);
this.stateParameters.logger.verbose("0rb7r9", this.stateParameters.correlationId);
return new MfaRequestChallengeResult(new MfaVerificationRequiredState({
correlationId: result.correlationId,
continuationToken: result.continuationToken,
config: this.stateParameters.config,
logger: this.stateParameters.logger,
mfaClient: this.stateParameters.mfaClient,
cacheClient: this.stateParameters.cacheClient,
challengeChannel: result.challengeChannel,
challengeTargetLabel: result.challengeTargetLabel,
codeLength: result.codeLength,
selectedAuthMethodId: authMethodId,
scopes: this.stateParameters.scopes ?? [],
}));
}
catch (error) {
this.stateParameters.logger.errorPii(`0bt3wx ${error}`, this.stateParameters.correlationId);
return MfaRequestChallengeResult.createWithError(error);
}
}
}
/**
* State indicating that MFA is required and awaiting user action.
* This state allows the developer to pause execution before sending the code to the user's email.
*/
class MfaAwaitingState extends MfaState {
constructor() {
super(...arguments);
/**
* The type of the state.
*/
this.stateType = MFA_AWAITING_STATE_TYPE;
}
/**
* Gets the available authentication methods for MFA.
* @returns Array of available authentication methods.
* @warning This API is experimental. It may be changed in the future without notice. Do not use in production applications.
*/
getAuthMethods() {
return this.stateParameters.authMethods;
}
}
/**
* State indicating that MFA verification is required.
* The challenge has been sent and the user needs to provide the code.
*/
class MfaVerificationRequiredState extends MfaState {
constructor() {
super(...arguments);
/**
* The type of the state.
*/
this.stateType = MFA_VERIFICATION_REQUIRED_STATE_TYPE;
}
/**
* Gets the length of the code that the user needs to provide.
* @returns The expected code length.
* @warning This API is experimental. It may be changed in the future without notice. Do not use in production applications.
*/
getCodeLength() {
return this.stateParameters.codeLength;
}
/**
* Gets the channel through which the challenge was sent.
* @returns The challenge channel (e.g., "email").
* @warning This API is experimental. It may be changed in the future without notice. Do not use in production applications.
*/
getChannel() {
return this.stateParameters.challengeChannel;
}
/**
* Gets the target label indicating where the challenge was sent.
* @returns The challenge target label (e.g., masked email address).
* @warning This API is experimental. It may be changed in the future without notice. Do not use in production applications.
*/
getSentTo() {
return this.stateParameters.challengeTargetLabel;
}
/**
* Submits the MFA challenge (e.g., OTP code) to complete the authentication.
* @param challenge The challenge code (e.g., OTP code) entered by the user.
* @returns Promise that resolves to MfaSubmitChallengeResult.
* @warning This API is experimental. It may be changed in the future without notice. Do not use in production applications.
*/
async submitChallenge(challenge) {
try {
this.ensureCodeIsValid(challenge, this.getCodeLength());
this.stateParameters.logger.verbose("1pi02n", this.stateParameters.correlationId);
const submitParams = {
correlationId: this.stateParameters.correlationId,
continuationToken: this.stateParameters.continuationToken ?? "",
scopes: this.stateParameters.scopes ?? [],
challenge: challenge,
};
const result = await this.stateParameters.mfaClient.submitChallenge(submitParams);
this.stateParameters.logger.verbose("0ddwwn", this.stateParameters.correlationId);
const accountInfo = new CustomAuthAccountData(result.authenticationResult.account, this.stateParameters.config, this.stateParameters.cacheClient, this.stateParameters.logger, this.stateParameters.correlationId);
return new MfaSubmitChallengeResult(new MfaCompletedState(), accountInfo);
}
catch (error) {
this.stateParameters.logger.errorPii(`01ok2b ${error}`, this.stateParameters.correlationId);
return MfaSubmitChallengeResult.createWithError(error);
}
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Represents the completed state of the sign-in operation.
* This state indicates that the sign-in process has finished successfully.
*/
class SignInCompletedState extends AuthFlowStateBase {
constructor() {
super(...arguments);
/**
* The type of the state.
*/
this.stateType = SIGN_IN_COMPLETED_STATE_TYPE;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Base state handler for sign-in flow.
*/
class SignInState extends AuthFlowActionRequiredStateBase {
/*
* Creates a new SignInState.
* @param stateParameters - The state parameters for sign-in.
*/
constructor(stateParameters) {
super(stateParameters);
ensureArgumentIsNotEmptyString("username", stateParameters.username, stateParameters.correlationId);
ensureArgumentIsNotEmptyString("continuationToken", stateParameters.continuationToken, stateParameters.correlationId);
}
/**
* Handles the result of a sign-in attempt.
* @param result - The result of the sign-in attempt.
* @param scopes - The scopes requested for the sign-in.
* @returns An object containing the next state and account information, if applicable.
*/
handleSignInResult(result, scopes) {
const correlationId = result.correlationId || this.stateParameters.correlationId;
if (result.type === SIGN_IN_COMPLETED_RESULT_TYPE) {
// Sign-in completed - return SignInCompletedState
this.stateParameters.logger.verbose("1wz8ns", correlationId);
const accountInfo = new CustomAuthAccountData(result.authenticationResult.account, this.stateParameters.config, this.stateParameters.cacheClient, this.stateParameters.logger, correlationId);
return {
state: new SignInCompletedState(),
accountInfo: accountInfo,
};
}
else if (result.type === SIGN_IN_JIT_REQUIRED_RESULT_TYPE) {
// JIT is required - return AuthMethodRegistrationRequiredState
this.stateParameters.logger.verbose("0fiacy", correlationId);
return {
state: new AuthMethodRegistrationRequiredState({
correlationId: correlationId,
continuationToken: result.continuationToken,
logger: this.stateParameters.logger,
config: this.stateParameters.config,
jitClient: this.stateParameters.jitClient,
cacheClient: this.stateParameters.cacheClient,
authMethods: result.authMethods,
username: this.stateParameters.username,
scopes: scopes ?? [],
claims: this.stateParameters.claims,
}),
};
}
else if (result.type === SIGN_IN_MFA_REQUIRED_RESULT_TYPE) {
// MFA is required - return MfaAwaitingState
this.stateParameters.logger.verbose("0ql59l", correlationId);
return {
state: new MfaAwaitingState({
correlationId: correlationId,
continuationToken: result.continuationToken,
logger: this.stateParameters.logger,
config: this.stateParameters.config,
mfaClient: this.stateParameters.mfaClient,
cacheClient: this.stateParameters.cacheClient,
scopes: scopes ?? [],
authMethods: result.authMethods ?? [],
}),
};
}
else {
// Unexpected result type
const unexpectedResult = result;
const error = new Error(`Unexpected result type: ${unexpectedResult.type}`);
return {
state: new SignInFailedState(),
error: error,
};
}
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Sign-in code required state.
*/
class SignInCodeRequiredState extends SignInState {
constructor() {
super(...arguments);
/**
* The type of the state.
*/
this.stateType = SIGN_IN_CODE_REQUIRED_STATE_TYPE;
}
/**
* Once user configures email one-time passcode as a authentication method in Microsoft Entra, a one-time passcode will be sent to the user’s email.
* Submit this one-time passcode to continue sign-in flow.
* @param {string} code - The code to submit.
* @returns {Promise<SignInSubmitCodeResult>} The result of the operation.
*/
async submitCode(code) {
try {
this.ensureCodeIsValid(code, this.stateParameters.codeLength);
const submitCodeParams = {
clientId: this.stateParameters.config.auth.clientId,
correlationId: this.stateParameters.correlationId,
challengeType: this.stateParameters.config.customAuth.challengeTypes ?? [],
scopes: this.stateParameters.scopes ?? [],
continuationToken: this.stateParameters.continuationToken ?? "",
code: code,
username: this.stateParameters.username,
claims: this.stateParameters.claims,
};
this.stateParameters.logger.verbose("0gosr6", this.stateParameters.correlationId);
const submitCodeResult = await this.stateParameters.signInClient.submitCode(submitCodeParams);
this.stateParameters.logger.verbose("14jm6w", this.stateParameters.correlationId);
const nextState = this.handleSignInResult(submitCodeResult, this.stateParameters.scopes);
if (nextState.error) {
return SignInSubmitCodeResult.createWithError(nextState.error);
}
return new SignInSubmitCodeResult(nextState.state, nextState.accountInfo);
}
catch (error) {
this.stateParameters.logger.errorPii(`05uiw3 ${error}`, this.stateParameters.correlationId);
return SignInSubmitCodeResult.createWithError(error);
}
}
/**
* Resends the another one-time passcode for sign-in flow if the previous one hasn't been verified.
* @returns {Promise<SignInResendCodeResult>} The result of the operation.
*/
async resendCode() {
try {
const submitCodeParams = {
clientId: this.stateParameters.config.auth.clientId,
correlationId: this.stateParameters.correlationId,
challengeType: this.stateParameters.config.customAuth.challengeTypes ?? [],
continuationToken: this.stateParameters.continuationToken ?? "",
username: this.stateParameters.username,
};
this.stateParameters.logger.verbose("0g09c3", this.stateParameters.correlationId);
const result = await this.stateParameters.signInClient.resendCode(submitCodeParams);
this.stateParameters.logger.verbose("03fy3t", this.stateParameters.correlationId);
return new SignInResendCodeResult(new SignInCodeRequiredState({
correlationId: result.correlationId,
continuationToken: result.continuationToken,
logger: this.stateParameters.logger,
config: this.stateParameters.config,
signInClient: this.stateParameters.signInClient,
cacheClient: this.stateParameters.cacheClient,
jitClient: this.stateParameters.jitClient,
mfaClient: this.stateParameters.mfaClient,
username: this.stateParameters.username,
codeLength: result.codeLength,
scopes: this.stateParameters.scopes,
}));
}
catch (error) {
return SignInResendCodeResult.createWithError(error);
}
}
/**
* Gets the sent code length.
* @returns {number} The length of the code.
*/
getCodeLength() {
return this.stateParameters.codeLength;
}
/**
* Gets the scopes to request.
* @returns {string[] | undefined} The scopes to request.
*/
getScopes() {
return this.stateParameters.scopes;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Result of a sign-in submit password operation.
*/
class SignInSubmitPasswordResult extends AuthFlowResultBase {
static createWithError(error) {
const result = new SignInSubmitPasswordResult(new SignInFailedState());
result.error = new SignInSubmitPasswordError(SignInSubmitPasswordResult.createErrorData(error));
return result;
}
/**
* Checks if the result is in a failed state.
*/
isFailed() {
return this.state.stateType === SIGN_IN_FAILED_STATE_TYPE;
}
/**
* Checks if the result is in a completed state.
*/
isCompleted() {
return this.state.stateType === SIGN_IN_COMPLETED_STATE_TYPE;
}
/**
* Checks if the result requires authentication method registration.
* @warning This API is experimental. It may be changed in the future without notice. Do not use in production applications.
*/
isAuthMethodRegistrationRequired() {
return (this.state.stateType ===
AUTH_METHOD_REGISTRATION_REQUIRED_STATE_TYPE);
}
/**
* Checks if the result requires MFA.
* @warning This API is experimental. It may be changed in the future without notice. Do not use in production applications.
*/
isMfaRequired() {
return this.state.stateType === MFA_AWAITING_STATE_TYPE;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Sign-in password required state.
*/
class SignInPasswordRequiredState extends SignInState {
constructor() {
super(...arguments);
/**
* The type of the state.
*/
this.stateType = SIGN_IN_PASSWORD_REQUIRED_STATE_TYPE;
}
/**
* Once user configures email with password as a authentication method in Microsoft Entra, user submits a password to continue sign-in flow.
* @param {string} password - The password to submit.
* @returns {Promise<SignInSubmitPasswordResult>} The result of the operation.
*/
async submitPassword(password) {
try {
this.ensurePasswordIsNotEmpty(password);
const submitPasswordParams = {
clientId: this.stateParameters.config.auth.clientId,
correlationId: this.stateParameters.correlationId,
challengeType: this.stateParameters.config.customAuth.challengeTypes ?? [],
scopes: this.stateParameters.scopes ?? [],
continuationToken: this.stateParameters.continuationToken ?? "",
password: password,
username: this.stateParameters.username,
claims: this.stateParameters.claims,
};
this.stateParameters.logger.verbose("1dm2kj", this.stateParameters.correlationId);
const submitPasswordResult = await this.stateParameters.signInClient.submitPassword(submitPasswordParams);
this.stateParameters.logger.verbose("1e0esa", this.stateParameters.correlationId);
const nextState = this.handleSignInResult(submitPasswordResult, this.stateParameters.scopes);
if (nextState.error) {
return SignInSubmitPasswordResult.createWithError(nextState.error);
}
return new SignInSubmitPasswordResult(nextState.state, nextState.accountInfo);
}
catch (error) {
this.stateParameters.logger.errorPii(`0jy3yf ${error}`, this.stateParameters.correlationId);
return SignInSubmitPasswordResult.createWithError(error);
}
}
/**
* Gets the scopes to request.
* @returns {string[] | undefined} The scopes to request.
*/
getScopes() {
return this.stateParameters.scopes;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Result of resending code in a sign-up operation.
*/
class SignUpResendCodeResult extends AuthFlowResultBase {
/**
* Creates a new instance of SignUpResendCodeResult.
* @param state The state of the result.
*/
constructor(state) {
super(state);
}
/**
* Creates a new instance of SignUpResendCodeResult with an error.
* @param error The error that occurred.
* @returns {SignUpResendCodeResult} A new instance of SignUpResendCodeResult with the error set.
*/
static createWithError(error) {
const result = new SignUpResendCodeResult(new SignUpFailedState());
result.error = new SignUpResendCodeError(SignUpResendCodeResult.createErrorData(error));
return result;
}
/**
* Checks if the result is in a failed state.
*/
isFailed() {
return this.state.stateType === SIGN_UP_FAILED_STATE_TYPE;
}
/**
* Checks if the result is in a code required state.
*/
isCodeRequired() {
return this.state.stateType === SIGN_UP_CODE_REQUIRED_STATE_TYPE;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Result of a sign-up operation that requires a code.
*/
class SignUpSubmitCodeResult extends AuthFlowResultBase {
/**
* Creates a new instance of SignUpSubmitCodeResult.
* @param state The state of the result.
*/
constructor(state) {
super(state);
}
/**
* Creates a new instance of SignUpSubmitCodeResult with an error.
* @param error The error that occurred.
* @returns {SignUpSubmitCodeResult} A new instance of SignUpSubmitCodeResult with the error set.
*/
static createWithError(error) {
const result = new SignUpSubmitCodeResult(new SignUpFailedState());
result.error = new SignUpSubmitCodeError(SignUpSubmitCodeResult.createErrorData(error));
return result;
}
/**
* Checks if the result is in a failed state.
*/
isFailed() {
return this.state.stateType === SIGN_UP_FAILED_STATE_TYPE;
}
/**
* Checks if the result is in a password required state.
*/
isPasswordRequired() {
return this.state.stateType === SIGN_UP_PASSWORD_REQUIRED_STATE_TYPE;
}
/**
* Checks if the result is in an attributes required state.
*/
isAttributesRequired() {
return this.state.stateType === SIGN_UP_ATTRIBUTES_REQUIRED_STATE_TYPE;
}
/**
* Checks if the result is in a completed state.
*/
isCompleted() {
return this.state.stateType === SIGN_UP_COMPLETED_STATE_TYPE;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Base state handler for sign-up flow.
*/
class SignUpState extends AuthFlowActionRequiredStateBase {
/*
* Creates a new SignUpState.
* @param stateParameters - The state parameters for sign-up.
*/
constructor(stateParameters) {
super(stateParameters);
ensureArgumentIsNotEmptyString("username", stateParameters.username, stateParameters.correlationId);
ensureArgumentIsNotEmptyString("continuationToken", stateParameters.continuationToken, stateParameters.correlationId);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Result of a sign-up operation that requires a password.
*/
class SignUpSubmitPasswordResult extends AuthFlowResultBase {
/**
* Creates a new instance of SignUpSubmitPasswordResult.
* @param state The state of the result.
*/
constructor(state) {
super(state);
}
/**
* Creates a new instance of SignUpSubmitPasswordResult with an error.
* @param error The error that occurred.
* @returns {SignUpSubmitPasswordResult} A new instance of SignUpSubmitPasswordResult with the error set.
*/
static createWithError(error) {
const result = new SignUpSubmitPasswordResult(new SignUpFailedState());
result.error = new SignUpSubmitPasswordError(SignUpSubmitPasswordResult.createErrorData(error));
return result;
}
/**
* Checks if the result is in a failed state.
*/
isFailed() {
return this.state.stateType === SIGN_UP_FAILED_STATE_TYPE;
}
/**
* Checks if the result is in an attributes required state.
*/
isAttributesRequired() {
return this.state.stateType === SIGN_UP_ATTRIBUTES_REQUIRED_STATE_TYPE;
}
/**
* Checks if the result is in a completed state.
*/
isCompleted() {
return this.state.stateType === SIGN_UP_COMPLETED_STATE_TYPE;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Result of a sign-up operation that requires attributes.
*/
class SignUpSubmitAttributesResult extends AuthFlowResultBase {
/**
* Creates a new instance of SignUpSubmitAttributesResult.
* @param state The state of the result.
*/
constructor(state) {
super(state);
}
/**
* Creates a new instance of SignUpSubmitAttributesResult with an error.
* @param error The error that occurred.
* @returns {SignUpSubmitAttributesResult} A new instance of SignUpSubmitAttributesResult with the error set.
*/
static createWithError(error) {
const result = new SignUpSubmitAttributesResult(new SignUpFailedState());
result.error = new SignUpSubmitAttributesError(SignUpSubmitAttributesResult.createErrorData(error));
return result;
}
/**
* Checks if the result is in a failed state.
*/
isFailed() {
return this.state.stateType === SIGN_UP_FAILED_STATE_TYPE;
}
/**
* Checks if the result is in a completed state.
*/
isCompleted() {
return this.state.stateType === SIGN_UP_COMPLETED_STATE_TYPE;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Sign-in continuation state.
*/
class SignInContinuationState extends SignInState {
constructor() {
super(...arguments);
/**
* The type of the state.
*/
this.stateType = SIGN_IN_CONTINUATION_STATE_TYPE;
}
/**
* Initiates the sign-in flow with continuation token.
* @param {SignInWithContinuationTokenInputs} signInWithContinuationTokenInputs - The result of the operation.
* @returns {Promise<SignInResult>} The result of the operation.
*/
async signIn(signInWithContinuationTokenInputs) {
try {
if (signInWithContinuationTokenInputs?.claims) {
ensureArgumentIsJSONString("signInWithContinuationTokenInputs.claims", signInWithContinuationTokenInputs.claims, this.stateParameters.correlationId);
}
const continuationTokenParams = {
clientId: this.stateParameters.config.auth.clientId,
correlationId: this.stateParameters.correlationId,
challengeType: this.stateParameters.config.customAuth.challengeTypes ?? [],
scopes: signInWithContinuationTokenInputs?.scopes ?? [],
continuationToken: this.stateParameters.continuationToken ?? "",
username: this.stateParameters.username,
signInScenario: this.stateParameters.signInScenario,
claims: signInWithContinuationTokenInputs?.claims,
};
this.stateParameters.logger.verbose("1lhjo6", this.stateParameters.correlationId);
const signInResult = await this.stateParameters.signInClient.signInWithContinuationToken(continuationTokenParams);
this.stateParameters.logger.verbose("0su211", this.stateParameters.correlationId);
const nextState = this.handleSignInResult(signInResult, signInWithContinuationTokenInputs?.scopes);
if (nextState.error) {
return SignInResult.createWithError(nextState.error);
}
return new SignInResult(nextState.state, nextState.accountInfo);
}
catch (error) {
this.stateParameters.logger.errorPii(`03tyr8 ${error}`, this.stateParameters.correlationId);
return SignInResult.createWithError(error);
}
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Represents the state of a sign-up operation that has been completed successfully.
*/
class SignUpCompletedState extends SignInContinuationState {
constructor() {
super(...arguments);
/**
* The type of the state.
*/
this.stateType = SIGN_UP_COMPLETED_STATE_TYPE;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Sign-up attributes required state.
*/
class SignUpAttributesRequiredState extends SignUpState {
constructor() {
super(...arguments);
/**
* The type of the state.
*/
this.stateType = SIGN_UP_ATTRIBUTES_REQUIRED_STATE_TYPE;
}
/**
* Submits attributes to continue sign-up flow.
* This methods is used to submit required attributes.
* These attributes, built in or custom, were configured in the Microsoft Entra admin center by the tenant administrator.
* @param {UserAccountAttributes} attributes - The attributes to submit.
* @returns {Promise<SignUpSubmitAttributesResult>} The result of the operation.
*/
async submitAttributes(attributes) {
if (!attributes || Object.keys(attributes).length === 0) {
this.stateParameters.logger.error("1jcv37", this.stateParameters.correlationId);
return Promise.resolve(SignUpSubmitAttributesResult.createWithError(new InvalidArgumentError("attributes", this.stateParameters.correlationId)));
}
try {
this.stateParameters.logger.verbose("0zl1ym", this.stateParameters.correlationId);
const result = await this.stateParameters.signUpClient.submitAttributes({
clientId: this.stateParameters.config.auth.clientId,
correlationId: this.stateParameters.correlationId,
challengeType: this.stateParameters.config.customAuth.challengeTypes ??
[],
continuationToken: this.stateParameters.continuationToken ?? "",
attributes: attributes,
username: this.stateParameters.username,
});
this.stateParameters.logger.verbose("0i07tr", this.stateParameters.correlationId);
if (result.type === SIGN_UP_COMPLETED_RESULT_TYPE) {
// Sign-up completed
this.stateParameters.logger.verbose("0fw1nl", this.stateParameters.correlationId);
return new SignUpSubmitAttributesResult(new SignUpCompletedState({
correlationId: result.correlationId,
continuationToken: result.continuationToken,
logger: this.stateParameters.logger,
config: this.stateParameters.config,
signInClient: this.stateParameters.signInClient,
cacheClient: this.stateParameters.cacheClient,
jitClient: this.stateParameters.jitClient,
mfaClient: this.stateParameters.mfaClient,
username: this.stateParameters.username,
signInScenario: SignInScenario.SignInAfterSignUp,
}));
}
return SignUpSubmitAttributesResult.createWithError(new UnexpectedError("Unknown sign-up result type.", this.stateParameters.correlationId));
}
catch (error) {
this.stateParameters.logger.errorPii(`1wde3l ${error}`, this.stateParameters.correlationId);
return SignUpSubmitAttributesResult.createWithError(error);
}
}
/**
* Gets the required attributes for sign-up.
* @returns {UserAttribute[]} The required attributes for sign-up.
*/
getRequiredAttributes() {
return this.stateParameters.requiredAttributes;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Sign-up password required state.
*/
class SignUpPasswordRequiredState extends SignUpState {
constructor() {
super(...arguments);
/**
* The type of the state.
*/
this.stateType = SIGN_UP_PASSWORD_REQUIRED_STATE_TYPE;
}
/**
* Submits a password for sign-up.
* @param {string} password - The password to submit.
* @returns {Promise<SignUpSubmitPasswordResult>} The result of the operation.
*/
async submitPassword(password) {
try {
this.ensurePasswordIsNotEmpty(password);
this.stateParameters.logger.verbose("1biha3", this.stateParameters.correlationId);
const result = await this.stateParameters.signUpClient.submitPassword({
clientId: this.stateParameters.config.auth.clientId,
correlationId: this.stateParameters.correlationId,
challengeType: this.stateParameters.config.customAuth.challengeTypes ??
[],
continuationToken: this.stateParameters.continuationToken ?? "",
password: password,
username: this.stateParameters.username,
});
this.stateParameters.logger.verbose("06wmh7", this.stateParameters.correlationId);
if (result.type === SIGN_UP_ATTRIBUTES_REQUIRED_RESULT_TYPE) {
// Attributes required
this.stateParameters.logger.verbose("0jd56g", this.stateParameters.correlationId);
return new SignUpSubmitPasswordResult(new SignUpAttributesRequiredState({
correlationId: result.correlationId,
continuationToken: result.continuationToken,
logger: this.stateParameters.logger,
config: this.stateParameters.config,
signInClient: this.stateParameters.signInClient,
signUpClient: this.stateParameters.signUpClient,
cacheClient: this.stateParameters.cacheClient,
jitClient: this.stateParameters.jitClient,
mfaClient: this.stateParameters.mfaClient,
username: this.stateParameters.username,
requiredAttributes: result.requiredAttributes,
}));
}
else if (result.type === SIGN_UP_COMPLETED_RESULT_TYPE) {
// Sign-up completed
this.stateParameters.logger.verbose("0fw1nl", this.stateParameters.correlationId);
return new SignUpSubmitPasswordResult(new SignUpCompletedState({
correlationId: result.correlationId,
continuationToken: result.continuationToken,
logger: this.stateParameters.logger,
config: this.stateParameters.config,
signInClient: this.stateParameters.signInClient,
cacheClient: this.stateParameters.cacheClient,
jitClient: this.stateParameters.jitClient,
mfaClient: this.stateParameters.mfaClient,
username: this.stateParameters.username,
signInScenario: SignInScenario.SignInAfterSignUp,
}));
}
return SignUpSubmitPasswordResult.createWithError(new UnexpectedError("Unknown sign-up result type.", this.stateParameters.correlationId));
}
catch (error) {
this.stateParameters.logger.errorPii(`1adqe5 ${error}`, this.stateParameters.correlationId);
return SignUpSubmitPasswordResult.createWithError(error);
}
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Sign-up code required state.
*/
class SignUpCodeRequiredState extends SignUpState {
constructor() {
super(...arguments);
/**
* The type of the state.
*/
this.stateType = SIGN_UP_CODE_REQUIRED_STATE_TYPE;
}
/**
* Submit one-time passcode to continue sign-up flow.
* @param {string} code - The code to submit.
* @returns {Promise<SignUpSubmitCodeResult>} The result of the operation.
*/
async submitCode(code) {
try {
this.ensureCodeIsValid(code, this.stateParameters.codeLength);
this.stateParameters.logger.verbose("1nedbh", this.stateParameters.correlationId);
const result = await this.stateParameters.signUpClient.submitCode({
clientId: this.stateParameters.config.auth.clientId,
correlationId: this.stateParameters.correlationId,
challengeType: this.stateParameters.config.customAuth.challengeTypes ?? [],
continuationToken: this.stateParameters.continuationToken ?? "",
code: code,
username: this.stateParameters.username,
});
this.stateParameters.logger.verbose("0okwn9", this.stateParameters.correlationId);
if (result.type === SIGN_UP_PASSWORD_REQUIRED_RESULT_TYPE) {
// Password required
this.stateParameters.logger.verbose("098u8y", this.stateParameters.correlationId);
return new SignUpSubmitCodeResult(new SignUpPasswordRequiredState({
correlationId: result.correlationId,
continuationToken: result.continuationToken,
logger: this.stateParameters.logger,
config: this.stateParameters.config,
signInClient: this.stateParameters.signInClient,
signUpClient: this.stateParameters.signUpClient,
cacheClient: this.stateParameters.cacheClient,
jitClient: this.stateParameters.jitClient,
mfaClient: this.stateParameters.mfaClient,
username: this.stateParameters.username,
}));
}
else if (result.type === SIGN_UP_ATTRIBUTES_REQUIRED_RESULT_TYPE) {
// Attributes required
this.stateParameters.logger.verbose("0jd56g", this.stateParameters.correlationId);
return new SignUpSubmitCodeResult(new SignUpAttributesRequiredState({
correlationId: result.correlationId,
continuationToken: result.continuationToken,
logger: this.stateParameters.logger,
config: this.stateParameters.config,
signInClient: this.stateParameters.signInClient,
signUpClient: this.stateParameters.signUpClient,
cacheClient: this.stateParameters.cacheClient,
jitClient: this.stateParameters.jitClient,
mfaClient: this.stateParameters.mfaClient,
username: this.stateParameters.username,
requiredAttributes: result.requiredAttributes,
}));
}
else if (result.type === SIGN_UP_COMPLETED_RESULT_TYPE) {
// Sign-up completed
this.stateParameters.logger.verbose("0fw1nl", this.stateParameters.correlationId);
return new SignUpSubmitCodeResult(new SignUpCompletedState({
correlationId: result.correlationId,
continuationToken: result.continuationToken,
logger: this.stateParameters.logger,
config: this.stateParameters.config,
signInClient: this.stateParameters.signInClient,
cacheClient: this.stateParameters.cacheClient,
jitClient: this.stateParameters.jitClient,
mfaClient: this.stateParameters.mfaClient,
username: this.stateParameters.username,
signInScenario: SignInScenario.SignInAfterSignUp,
}));
}
return SignUpSubmitCodeResult.createWithError(new UnexpectedError("Unknown sign-up result type.", this.stateParameters.correlationId));
}
catch (error) {
this.stateParameters.logger.errorPii(`1y64s9 ${error}`, this.stateParameters.correlationId);
return SignUpSubmitCodeResult.createWithError(error);
}
}
/**
* Resends the another one-time passcode for sign-up flow if the previous one hasn't been verified.
* @returns {Promise<SignUpResendCodeResult>} The result of the operation.
*/
async resendCode() {
try {
this.stateParameters.logger.verbose("087lh9", this.stateParameters.correlationId);
const result = await this.stateParameters.signUpClient.resendCode({
clientId: this.stateParameters.config.auth.clientId,
challengeType: this.stateParameters.config.customAuth.challengeTypes ?? [],
username: this.stateParameters.username,
correlationId: this.stateParameters.correlationId,
continuationToken: this.stateParameters.continuationToken ?? "",
});
this.stateParameters.logger.verbose("0eub4o", this.stateParameters.correlationId);
return new SignUpResendCodeResult(new SignUpCodeRequiredState({
correlationId: result.correlationId,
continuationToken: result.continuationToken,
logger: this.stateParameters.logger,
config: this.stateParameters.config,
signInClient: this.stateParameters.signInClient,
signUpClient: this.stateParameters.signUpClient,
cacheClient: this.stateParameters.cacheClient,
jitClient: this.stateParameters.jitClient,
mfaClient: this.stateParameters.mfaClient,
username: this.stateParameters.username,
codeLength: result.codeLength,
codeResendInterval: result.interval,
}));
}
catch (error) {
this.stateParameters.logger.errorPii(`04co5l ${error}`, this.stateParameters.correlationId);
return SignUpResendCodeResult.createWithError(error);
}
}
/**
* Gets the sent code length.
* @returns {number} The length of the code.
*/
getCodeLength() {
return this.stateParameters.codeLength;
}
/**
* Gets the interval in seconds for the code to be resent.
* @returns {number} The interval in seconds for the code to be resent.
*/
getCodeResendInterval() {
return this.stateParameters.codeResendInterval;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Result of resending code in a reset password operation.
*/
class ResetPasswordResendCodeResult extends AuthFlowResultBase {
/**
* Creates a new instance of ResetPasswordResendCodeResult.
* @param state The state of the result.
*/
constructor(state) {
super(state);
}
/**
* Creates a new instance of ResetPasswordResendCodeResult with an error.
* @param error The error that occurred.
* @returns {ResetPasswordResendCodeResult} A new instance of ResetPasswordResendCodeResult with the error set.
*/
static createWithError(error) {
const result = new ResetPasswordResendCodeResult(new ResetPasswordFailedState());
result.error = new ResetPasswordResendCodeError(ResetPasswordResendCodeResult.createErrorData(error));
return result;
}
/**
* Checks if the result is in a failed state.
*/
isFailed() {
return this.state.stateType === RESET_PASSWORD_FAILED_STATE_TYPE;
}
/**
* Checks if the result is in a code required state.
*/
isCodeRequired() {
return this.state.stateType === RESET_PASSWORD_CODE_REQUIRED_STATE_TYPE;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Result of a reset password operation that requires a code.
*/
class ResetPasswordSubmitCodeResult extends AuthFlowResultBase {
/**
* Creates a new instance of ResetPasswordSubmitCodeResult.
* @param state The state of the result.
*/
constructor(state) {
super(state);
}
/**
* Creates a new instance of ResetPasswordSubmitCodeResult with an error.
* @param error The error that occurred.
* @returns {ResetPasswordSubmitCodeResult} A new instance of ResetPasswordSubmitCodeResult with the error set.
*/
static createWithError(error) {
const result = new ResetPasswordSubmitCodeResult(new ResetPasswordFailedState());
result.error = new ResetPasswordSubmitCodeError(ResetPasswordSubmitCodeResult.createErrorData(error));
return result;
}
/**
* Checks if the result is in a failed state.
*/
isFailed() {
return this.state.stateType === RESET_PASSWORD_FAILED_STATE_TYPE;
}
/**
* Checks if the result is in a password required state.
*/
isPasswordRequired() {
return (this.state.stateType === RESET_PASSWORD_PASSWORD_REQUIRED_STATE_TYPE);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Base state handler for reset password operation.
*/
class ResetPasswordState extends AuthFlowActionRequiredStateBase {
/*
* Creates a new state for reset password operation.
* @param stateParameters - The state parameters for reset-password.
*/
constructor(stateParameters) {
super(stateParameters);
ensureArgumentIsNotEmptyString("username", this.stateParameters.username, this.stateParameters.correlationId);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Result of a reset password operation that requires a password.
*/
class ResetPasswordSubmitPasswordResult extends AuthFlowResultBase {
/**
* Creates a new instance of ResetPasswordSubmitPasswordResult.
* @param state The state of the result.
*/
constructor(state) {
super(state);
}
static createWithError(error) {
const result = new ResetPasswordSubmitPasswordResult(new ResetPasswordFailedState());
result.error = new ResetPasswordSubmitPasswordError(ResetPasswordSubmitPasswordResult.createErrorData(error));
return result;
}
/**
* Checks if the result is in a failed state.
*/
isFailed() {
return this.state.stateType === RESET_PASSWORD_FAILED_STATE_TYPE;
}
/**
* Checks if the result is in a completed state.
*/
isCompleted() {
return this.state.stateType === RESET_PASSWORD_COMPLETED_STATE_TYPE;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Represents the state that indicates the successful completion of a password reset operation.
*/
class ResetPasswordCompletedState extends SignInContinuationState {
constructor() {
super(...arguments);
/**
* The type of the state.
*/
this.stateType = RESET_PASSWORD_COMPLETED_STATE_TYPE;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Reset password password required state.
*/
class ResetPasswordPasswordRequiredState extends ResetPasswordState {
constructor() {
super(...arguments);
/**
* The type of the state.
*/
this.stateType = RESET_PASSWORD_PASSWORD_REQUIRED_STATE_TYPE;
}
/**
* Submits a new password for reset password flow.
* @param {string} password - The password to submit.
* @returns {Promise<ResetPasswordSubmitPasswordResult>} The result of the operation.
*/
async submitNewPassword(password) {
try {
this.ensurePasswordIsNotEmpty(password);
this.stateParameters.logger.verbose("01ecin", this.stateParameters.correlationId);
const result = await this.stateParameters.resetPasswordClient.submitNewPassword({
clientId: this.stateParameters.config.auth.clientId,
correlationId: this.stateParameters.correlationId,
challengeType: this.stateParameters.config.customAuth
.challengeTypes ?? [],
continuationToken: this.stateParameters.continuationToken ?? "",
newPassword: password,
username: this.stateParameters.username,
});
this.stateParameters.logger.verbose("1hgnje", this.stateParameters.correlationId);
return new ResetPasswordSubmitPasswordResult(new ResetPasswordCompletedState({
correlationId: result.correlationId,
continuationToken: result.continuationToken,
logger: this.stateParameters.logger,
config: this.stateParameters.config,
username: this.stateParameters.username,
signInClient: this.stateParameters.signInClient,
cacheClient: this.stateParameters.cacheClient,
jitClient: this.stateParameters.jitClient,
mfaClient: this.stateParameters.mfaClient,
signInScenario: SignInScenario.SignInAfterPasswordReset,
}));
}
catch (error) {
this.stateParameters.logger.errorPii(`0stjo2 ${error}`, this.stateParameters.correlationId);
return ResetPasswordSubmitPasswordResult.createWithError(error);
}
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Reset password code required state.
*/
class ResetPasswordCodeRequiredState extends ResetPasswordState {
constructor() {
super(...arguments);
/**
* The type of the state.
*/
this.stateType = RESET_PASSWORD_CODE_REQUIRED_STATE_TYPE;
}
/**
* Submits a one-time passcode that the customer user received in their email in order to continue password reset flow.
* @param {string} code - The code to submit.
* @returns {Promise<ResetPasswordSubmitCodeResult>} The result of the operation.
*/
async submitCode(code) {
try {
this.ensureCodeIsValid(code, this.stateParameters.codeLength);
this.stateParameters.logger.verbose("0eno3c", this.stateParameters.correlationId);
const result = await this.stateParameters.resetPasswordClient.submitCode({
clientId: this.stateParameters.config.auth.clientId,
correlationId: this.stateParameters.correlationId,
challengeType: this.stateParameters.config.customAuth.challengeTypes ??
[],
continuationToken: this.stateParameters.continuationToken ?? "",
code: code,
username: this.stateParameters.username,
});
this.stateParameters.logger.verbose("1pdlyx", this.stateParameters.correlationId);
return new ResetPasswordSubmitCodeResult(new ResetPasswordPasswordRequiredState({
correlationId: result.correlationId,
continuationToken: result.continuationToken,
logger: this.stateParameters.logger,
config: this.stateParameters.config,
resetPasswordClient: this.stateParameters.resetPasswordClient,
signInClient: this.stateParameters.signInClient,
cacheClient: this.stateParameters.cacheClient,
jitClient: this.stateParameters.jitClient,
mfaClient: this.stateParameters.mfaClient,
username: this.stateParameters.username,
}));
}
catch (error) {
this.stateParameters.logger.errorPii(`1wtelk ${error}`, this.stateParameters.correlationId);
return ResetPasswordSubmitCodeResult.createWithError(error);
}
}
/**
* Resends another one-time passcode if the previous one hasn't been verified
* @returns {Promise<ResetPasswordResendCodeResult>} The result of the operation.
*/
async resendCode() {
try {
this.stateParameters.logger.verbose("13fdb0", this.stateParameters.correlationId);
const result = await this.stateParameters.resetPasswordClient.resendCode({
clientId: this.stateParameters.config.auth.clientId,
challengeType: this.stateParameters.config.customAuth.challengeTypes ??
[],
username: this.stateParameters.username,
correlationId: this.stateParameters.correlationId,
continuationToken: this.stateParameters.continuationToken ?? "",
});
this.stateParameters.logger.verbose("01cakn", this.stateParameters.correlationId);
return new ResetPasswordResendCodeResult(new ResetPasswordCodeRequiredState({
correlationId: result.correlationId,
continuationToken: result.continuationToken,
logger: this.stateParameters.logger,
config: this.stateParameters.config,
resetPasswordClient: this.stateParameters.resetPasswordClient,
signInClient: this.stateParameters.signInClient,
cacheClient: this.stateParameters.cacheClient,
jitClient: this.stateParameters.jitClient,
mfaClient: this.stateParameters.mfaClient,
username: this.stateParameters.username,
codeLength: result.codeLength,
}));
}
catch (error) {
this.stateParameters.logger.errorPii(`1vyfic ${error}`, this.stateParameters.correlationId);
return ResetPasswordResendCodeResult.createWithError(error);
}
}
/**
* Gets the sent code length.
* @returns {number} The length of the code.
*/
getCodeLength() {
return this.stateParameters.codeLength;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* acquireTokenSilent API (msal-browser and msal-node).
* Used to silently acquire a new access token (from the cache or the network).
*/
const AcquireTokenSilent = "acquireTokenSilent";
/**
* acquireTokenByCode API (msal-browser and msal-node).
* Used to acquire tokens by trading an authorization code against the token endpoint.
*/
const AcquireTokenByCode = "acquireTokenByCode";
/**
* acquireTokenPopup (msal-browser).
* Used to acquire a new access token interactively through pop ups
*/
const AcquireTokenPopup = "acquireTokenPopup";
/**
* acquireTokenPreRedirect (msal-browser).
* First part of the redirect flow.
* Used to acquire a new access token interactively through redirects.
*/
const AcquireTokenPreRedirect = "acquireTokenPreRedirect";
/**
* acquireTokenRedirect (msal-browser).
* Second part of the redirect flow.
* Used to acquire a new access token interactively through redirects.
*/
const AcquireTokenRedirect = "acquireTokenRedirect";
/**
* ssoSilent API (msal-browser).
* Used to silently acquire an authorization code and set of tokens using a hidden iframe.
*/
const SsoSilent = "ssoSilent";
// Initialize client application
const InitializeClientApplication = "initializeClientApplication";
// Update cache storage
const LocalStorageUpdated = "localStorageUpdated";
/**
* SSO capability verification call (msal-browser).
* Fire-and-forget SSO verification call made after interactive authentication completes.
*/
const SsoCapable = "ssoCapable";
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const PREFIX = "msal";
const BROWSER_PREFIX = "browser";
const CACHE_KEY_SEPARATOR = "|";
const CREDENTIAL_SCHEMA_VERSION = 3;
const ACCOUNT_SCHEMA_VERSION = 3;
const LOG_LEVEL_CACHE_KEY = `${PREFIX}.${BROWSER_PREFIX}.log.level`;
const LOG_PII_CACHE_KEY = `${PREFIX}.${BROWSER_PREFIX}.log.pii`;
const VERSION_CACHE_KEY = `${PREFIX}.version`;
const ACCOUNT_KEYS = "account.keys";
const TOKEN_KEYS = "token.keys";
const SSO_CAPABLE = `${PREFIX}.${BROWSER_PREFIX}.sso.capable`;
function getAccountKeysCacheKey(schema = ACCOUNT_SCHEMA_VERSION) {
if (schema < 1) {
return `${PREFIX}.${ACCOUNT_KEYS}`;
}
return `${PREFIX}.${schema}.${ACCOUNT_KEYS}`;
}
function getTokenKeysCacheKey(clientId, schema = CREDENTIAL_SCHEMA_VERSION) {
if (schema < 1) {
return `${PREFIX}.${TOKEN_KEYS}.${clientId}`;
}
return `${PREFIX}.${schema}.${TOKEN_KEYS}.${clientId}`;
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
// Cookie life calculation (hours * minutes * seconds * ms)
const COOKIE_LIFE_MULTIPLIER = 24 * 60 * 60 * 1000;
const SameSiteOptions = {
Lax: "Lax",
None: "None",
};
class CookieStorage {
initialize() {
return Promise.resolve();
}
getItem(key) {
const name = encodeURIComponent(key);
const cookieList = document.cookie.split(";");
for (let i = 0; i < cookieList.length; i++) {
const cookie = cookieList[i].trim();
const eqIndex = cookie.indexOf("=");
const rawKey = eqIndex === -1 ? cookie : cookie.substring(0, eqIndex);
if (rawKey === name) {
const rawValue = eqIndex === -1 ? "" : cookie.substring(eqIndex + 1);
try {
return decodeURIComponent(rawValue);
}
catch {
return rawValue;
}
}
}
return "";
}
getUserData() {
throw createClientAuthError(methodNotImplemented, "");
}
setItem(key, value, cookieLifeDays, secure = true, sameSite = SameSiteOptions.Lax) {
let cookieStr = `${encodeURIComponent(key)}=${encodeURIComponent(value)};path=/;SameSite=${sameSite};`;
if (cookieLifeDays) {
const expireTime = getCookieExpirationTime(cookieLifeDays);
cookieStr += `expires=${expireTime};`;
}
if (secure || sameSite === SameSiteOptions.None) {
// SameSite None requires Secure flag
cookieStr += "Secure;";
}
document.cookie = cookieStr;
}
async setUserData(_key, _value, correlationId) {
return Promise.reject(createClientAuthError(methodNotImplemented, correlationId));
}
removeItem(key) {
// Setting expiration to -1 removes it
this.setItem(key, "", -1);
}
getKeys() {
const cookieList = document.cookie.split(";");
const keys = [];
cookieList.forEach((cookie) => {
const trimmed = cookie.trim();
const eqIndex = trimmed.indexOf("=");
const rawKey = eqIndex === -1 ? trimmed : trimmed.substring(0, eqIndex);
try {
keys.push(decodeURIComponent(rawKey));
}
catch {
// Skip cookies with malformed percent-encoded sequences in the key
}
});
return keys;
}
containsKey(key) {
return this.getKeys().includes(key);
}
decryptData() {
// Cookie storage does not support encryption, so this method is a no-op
return Promise.resolve(null);
}
}
/**
* Get cookie expiration time
* @param cookieLifeDays
*/
function getCookieExpirationTime(cookieLifeDays) {
const today = new Date();
const expr = new Date(today.getTime() + cookieLifeDays * COOKIE_LIFE_MULTIPLIER);
return expr.toUTCString();
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Returns a list of cache keys for all known accounts
* @param storage
* @returns
*/
function getAccountKeys(storage, schemaVersion) {
const accountKeys = storage.getItem(getAccountKeysCacheKey(schemaVersion));
if (accountKeys) {
return JSON.parse(accountKeys);
}
return [];
}
/**
* Returns a list of cache keys for all known tokens
* @param clientId
* @param storage
* @returns
*/
function getTokenKeys(clientId, storage, schemaVersion) {
const item = storage.getItem(getTokenKeysCacheKey(clientId, schemaVersion));
if (item) {
const tokenKeys = JSON.parse(item);
if (tokenKeys &&
tokenKeys.hasOwnProperty("idToken") &&
tokenKeys.hasOwnProperty("accessToken") &&
tokenKeys.hasOwnProperty("refreshToken")) {
return tokenKeys;
}
}
return {
idToken: [],
accessToken: [],
refreshToken: [],
};
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
function isEncrypted(data) {
return (data.hasOwnProperty("id") &&
data.hasOwnProperty("nonce") &&
data.hasOwnProperty("data"));
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const ENCRYPTION_KEY = "msal.cache.encryption";
const BROADCAST_CHANNEL_NAME$1 = "msal.broadcast.cache";
class LocalStorage {
constructor(clientId, logger, performanceClient) {
if (!window.localStorage) {
throw createBrowserConfigurationAuthError(storageNotSupported, "");
}
this.memoryStorage = new MemoryStorage();
this.initialized = false;
this.clientId = clientId;
this.logger = logger;
this.performanceClient = performanceClient;
this.broadcast = new BroadcastChannel(BROADCAST_CHANNEL_NAME$1);
}
async initialize(correlationId) {
const cookies = new CookieStorage();
const cookieString = cookies.getItem(ENCRYPTION_KEY);
let parsedCookie = { key: "", id: "" };
if (cookieString) {
try {
parsedCookie = JSON.parse(cookieString);
}
catch (e) { }
}
if (parsedCookie.key && parsedCookie.id) {
// Encryption key already exists, import
const baseKey = invoke(base64DecToArr, Base64Decode, this.logger, this.performanceClient, correlationId)(parsedCookie.key);
this.encryptionCookie = {
id: parsedCookie.id,
key: await invokeAsync(generateHKDF, GenerateHKDF, this.logger, this.performanceClient, correlationId)(baseKey),
};
}
else {
// Encryption key doesn't exist or is invalid, generate a new one
const id = createNewGuid();
const baseKey = await invokeAsync(generateBaseKey, GenerateBaseKey, this.logger, this.performanceClient, correlationId)();
const keyStr = invoke(urlEncodeArr, UrlEncodeArr, this.logger, this.performanceClient, correlationId)(new Uint8Array(baseKey));
this.encryptionCookie = {
id: id,
key: await invokeAsync(generateHKDF, GenerateHKDF, this.logger, this.performanceClient, correlationId)(baseKey),
};
const cookieData = {
id: id,
key: keyStr,
};
cookies.setItem(ENCRYPTION_KEY, JSON.stringify(cookieData), 0, // Expiration - 0 means cookie will be cleared at the end of the browser session
true, // Secure flag
SameSiteOptions.None // SameSite must be None to support iframed apps
);
}
await invokeAsync(this.importExistingCache.bind(this), ImportExistingCache, this.logger, this.performanceClient, correlationId)(correlationId);
// Register listener for cache updates in other tabs
this.broadcast.addEventListener("message", (event) => {
this.updateCache(event, correlationId).catch(() => {
this.logger.error("0ufnan", correlationId);
});
});
this.initialized = true;
}
getItem(key) {
return window.localStorage.getItem(key);
}
getUserData(key) {
if (!this.initialized) {
throw createBrowserAuthError(uninitializedPublicClientApplication, "");
}
return this.memoryStorage.getItem(key);
}
async decryptData(key, data, correlationId) {
if (!this.initialized || !this.encryptionCookie) {
throw createBrowserAuthError(uninitializedPublicClientApplication, "");
}
if (data.id !== this.encryptionCookie.id) {
// Data was encrypted with a different key. It must be removed because it is from a previous session.
this.performanceClient.incrementFields({ encryptedCacheExpiredCount: 1 }, correlationId);
return null;
}
const decryptedData = await invokeAsync(decrypt, Decrypt, this.logger, this.performanceClient, correlationId)(this.encryptionCookie.key, data.nonce, this.getContext(key), data.data);
if (!decryptedData) {
return null;
}
try {
return {
...JSON.parse(decryptedData),
lastUpdatedAt: data.lastUpdatedAt,
};
}
catch (e) {
this.performanceClient.incrementFields({ encryptedCacheCorruptionCount: 1 }, correlationId);
return null;
}
}
setItem(key, value) {
window.localStorage.setItem(key, value);
}
async setUserData(key, value, correlationId, timestamp, kmsi) {
if (!this.initialized || !this.encryptionCookie) {
throw createBrowserAuthError(uninitializedPublicClientApplication, "");
}
if (kmsi) {
this.setItem(key, value);
}
else {
const { data, nonce } = await invokeAsync(encrypt, Encrypt, this.logger, this.performanceClient, correlationId)(this.encryptionCookie.key, value, this.getContext(key));
const encryptedData = {
id: this.encryptionCookie.id,
nonce: nonce,
data: data,
lastUpdatedAt: timestamp,
};
this.setItem(key, JSON.stringify(encryptedData));
}
this.memoryStorage.setItem(key, value);
// Notify other frames to update their in-memory cache
this.broadcast.postMessage({
key: key,
value: value,
context: this.getBroadcastContext(key),
});
}
removeItem(key) {
const itemExists = this.containsKey(key) || this.memoryStorage.containsKey(key);
window.localStorage.removeItem(key);
this.memoryStorage.removeItem(key);
if (itemExists) {
this.broadcast.postMessage({
key: key,
value: null,
context: this.getBroadcastContext(key),
});
}
}
getKeys() {
return Object.keys(window.localStorage);
}
containsKey(key) {
return window.localStorage.hasOwnProperty(key);
}
/**
* Removes all known MSAL keys from the cache
*/
clear() {
// Removes all remaining MSAL cache items
this.memoryStorage.clear();
const accountKeys = getAccountKeys(this);
accountKeys.forEach((key) => this.removeItem(key));
const tokenKeys = getTokenKeys(this.clientId, this);
tokenKeys.idToken.forEach((key) => this.removeItem(key));
tokenKeys.accessToken.forEach((key) => this.removeItem(key));
tokenKeys.refreshToken.forEach((key) => this.removeItem(key));
// Clean up anything left
this.getKeys().forEach((cacheKey) => {
if (cacheKey.startsWith(PREFIX) ||
cacheKey.indexOf(this.clientId) !== -1) {
this.removeItem(cacheKey);
}
});
}
/**
* Helper to decrypt all known MSAL keys in localStorage and save them to inMemory storage
* @returns
*/
async importExistingCache(correlationId) {
if (!this.encryptionCookie) {
return;
}
let accountKeys = getAccountKeys(this);
accountKeys = await this.importArray(accountKeys, correlationId);
// Write valid account keys back to map
if (accountKeys.length) {
this.setItem(getAccountKeysCacheKey(), JSON.stringify(accountKeys));
}
else {
this.removeItem(getAccountKeysCacheKey());
}
const tokenKeys = getTokenKeys(this.clientId, this);
tokenKeys.idToken = await this.importArray(tokenKeys.idToken, correlationId);
tokenKeys.accessToken = await this.importArray(tokenKeys.accessToken, correlationId);
tokenKeys.refreshToken = await this.importArray(tokenKeys.refreshToken, correlationId);
// Write valid token keys back to map
if (tokenKeys.idToken.length ||
tokenKeys.accessToken.length ||
tokenKeys.refreshToken.length) {
this.setItem(getTokenKeysCacheKey(this.clientId), JSON.stringify(tokenKeys));
}
else {
this.removeItem(getTokenKeysCacheKey(this.clientId));
}
}
/**
* Helper to decrypt and save cache entries
* @param key
* @returns
*/
async getItemFromEncryptedCache(key, correlationId) {
if (!this.encryptionCookie) {
return null;
}
const rawCache = this.getItem(key);
if (!rawCache) {
return null;
}
let encObj;
try {
encObj = JSON.parse(rawCache);
}
catch (e) {
// Not a valid encrypted object, remove
return null;
}
if (!isEncrypted(encObj)) {
// Data is not encrypted
this.performanceClient.incrementFields({ unencryptedCacheCount: 1 }, correlationId);
return rawCache;
}
if (encObj.id !== this.encryptionCookie.id) {
// Data was encrypted with a different key. It must be removed because it is from a previous session.
this.performanceClient.incrementFields({ encryptedCacheExpiredCount: 1 }, correlationId);
return null;
}
this.performanceClient.incrementFields({ encryptedCacheCount: 1 }, correlationId);
return invokeAsync(decrypt, Decrypt, this.logger, this.performanceClient, correlationId)(this.encryptionCookie.key, encObj.nonce, this.getContext(key), encObj.data);
}
/**
* Helper to decrypt and save an array of cache keys
* @param arr
* @returns Array of keys successfully imported
*/
async importArray(arr, correlationId) {
const importedArr = [];
const promiseArr = [];
arr.forEach((key) => {
const promise = this.getItemFromEncryptedCache(key, correlationId).then((value) => {
if (value) {
this.memoryStorage.setItem(key, value);
importedArr.push(key);
}
else {
// If value is empty, unencrypted or expired remove
this.removeItem(key);
}
});
promiseArr.push(promise);
});
await Promise.all(promiseArr);
return importedArr;
}
getContext(key) {
return key.includes(this.clientId) ? this.clientId : "";
}
getBroadcastContext(key) {
const normalizedKey = key.toLowerCase();
const keySegments = normalizedKey.split(CACHE_KEY_SEPARATOR);
if (keySegments.length > 1) {
return keySegments[4] === this.clientId.toLowerCase()
? this.clientId
: "";
}
const credentialType = this.getCredentialType(normalizedKey);
if (credentialType) {
const ownerPrefix = `-${credentialType}-${this.clientId.toLowerCase()}-`;
return normalizedKey.includes(ownerPrefix) ? this.clientId : "";
}
return normalizedKey.includes(this.clientId.toLowerCase())
? this.clientId
: "";
}
getCredentialType(key) {
const normalizedKey = key.toLowerCase();
const keySegments = normalizedKey.split(CACHE_KEY_SEPARATOR);
const structuredCredentialType = keySegments[3];
return Object.values(CredentialType)
.map((type) => type.toLowerCase())
.find((type) => structuredCredentialType === type ||
normalizedKey.includes(`-${type}-`));
}
isFamilyRefreshToken(key, credentialType) {
if (credentialType !==
CredentialType.REFRESH_TOKEN.toLowerCase()) {
return false;
}
const normalizedKey = key.toLowerCase();
const keySegments = normalizedKey.split(CACHE_KEY_SEPARATOR);
return keySegments.length > 1
? keySegments[4] === THE_FAMILY_ID
: normalizedKey.includes(`-${credentialType}-${THE_FAMILY_ID}-`);
}
isContextValid(key, context) {
const credentialType = this.getCredentialType(key);
const isFamilyRefreshToken = credentialType && this.isFamilyRefreshToken(key, credentialType);
const isClientBoundCredential = !!credentialType && !isFamilyRefreshToken;
return ((!isClientBoundCredential || !!context) &&
context === this.getBroadcastContext(key));
}
async updateCache(event, correlationId) {
this.logger.trace("17cxcm", correlationId);
const perfMeasurement = this.performanceClient.startMeasurement(LocalStorageUpdated);
perfMeasurement.add({ isBackground: true });
const key = event.data?.key;
const context = event.data?.context;
if (typeof key !== "string" || !key) {
this.logger.error("0e10qr", correlationId);
perfMeasurement.end({ success: false, errorCode: "noKey" });
return;
}
if (typeof context !== "string") {
this.logger.error("16gtk4", correlationId);
perfMeasurement.end({
success: false,
errorCode: "noContext",
});
return;
}
if (!this.isContextValid(key, context)) {
this.logger.trace(`04rtdy ${context}`, correlationId);
/*
* Discarded rather than ended: this is expected routing, not a failure.
* BroadcastChannel has no server-side filtering, so every MSAL instance on
* the origin receives every message and drops the ones scoped to another
* clientId. With N instances sharing an origin each write produces N-1 of
* these no-ops, so emitting them scales O(N^2) - and because they were
* previously reported with success: false they bypassed both the 1% misc
* sampler and the observability trimming in the 1P telemetry reporter,
* shipping at full payload. On origins hosting many embedded first-party
* apps that dwarfed all other MSAL telemetry combined. These events carry
* no diagnostic value, so drop the measurement entirely. Genuine faults
* such as the noKey case above are still reported.
*/
perfMeasurement.discard();
return;
}
const persistedValue = this.getItem(key);
try {
const value = await this.getItemFromEncryptedCache(key, correlationId);
// A newer write or removal occurred while this entry was decrypted.
if (this.getItem(key) !== persistedValue) {
perfMeasurement.discard();
return;
}
if (!value) {
this.memoryStorage.removeItem(key);
this.logger.verbose("04ypih", correlationId);
}
else {
this.memoryStorage.setItem(key, value);
this.logger.verbose("1vzsgt", correlationId);
}
perfMeasurement.end({ success: true });
}
catch {
if (this.getItem(key) !== persistedValue) {
perfMeasurement.discard();
return;
}
this.memoryStorage.removeItem(key);
this.logger.error("0flmza", correlationId);
perfMeasurement.end({
success: false,
errorCode: "cacheUpdateFailed",
});
}
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class SessionStorage {
constructor() {
if (!window.sessionStorage) {
throw createBrowserConfigurationAuthError(storageNotSupported, "");
}
}
async initialize() {
// Session storage does not require initialization
}
getItem(key) {
return window.sessionStorage.getItem(key);
}
getUserData(key) {
return this.getItem(key);
}
setItem(key, value) {
window.sessionStorage.setItem(key, value);
}
async setUserData(key, value) {
this.setItem(key, value);
}
removeItem(key) {
window.sessionStorage.removeItem(key);
}
getKeys() {
return Object.keys(window.sessionStorage);
}
containsKey(key) {
return window.sessionStorage.hasOwnProperty(key);
}
decryptData() {
// Session storage does not support encryption, so this method is a no-op
return Promise.resolve(null);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const EventType = {
INITIALIZE_START: "msal:initializeStart",
INITIALIZE_END: "msal:initializeEnd",
ACTIVE_ACCOUNT_CHANGED: "msal:activeAccountChanged",
LOGIN_SUCCESS: "msal:loginSuccess",
ACQUIRE_TOKEN_START: "msal:acquireTokenStart",
BROKERED_REQUEST_START: "msal:brokeredRequestStart",
ACQUIRE_TOKEN_SUCCESS: "msal:acquireTokenSuccess",
BROKERED_REQUEST_SUCCESS: "msal:brokeredRequestSuccess",
ACQUIRE_TOKEN_FAILURE: "msal:acquireTokenFailure",
BROKERED_REQUEST_FAILURE: "msal:brokeredRequestFailure",
ACQUIRE_TOKEN_NETWORK_START: "msal:acquireTokenFromNetworkStart",
HANDLE_REDIRECT_START: "msal:handleRedirectStart",
HANDLE_REDIRECT_END: "msal:handleRedirectEnd",
POPUP_OPENED: "msal:popupOpened",
LOGOUT_START: "msal:logoutStart",
LOGOUT_SUCCESS: "msal:logoutSuccess",
LOGOUT_FAILURE: "msal:logoutFailure",
LOGOUT_END: "msal:logoutEnd",
RESTORE_FROM_BFCACHE: "msal:restoreFromBFCache",
BROKER_CONNECTION_ESTABLISHED: "msal:brokerConnectionEstablished",
};
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Utility function to remove an element from an array in place.
* @param array - The array from which to remove the element.
* @param element - The element to remove from the array.
*/
function removeElementFromArray(array, element) {
const index = array.indexOf(element);
if (index > -1) {
array.splice(index, 1);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Reason an old-schema cache entry was removed during migration.
*/
const MigrationRemovalReason = {
Invalid: "invalid",
TtlExpired: "ttlExpired",
DecryptFailed: "decryptFailed",
Expired: "expired",
};
/**
* This class implements the cache storage interface for MSAL through browser local or session storage.
*/
class BrowserCacheManager extends CacheManager {
constructor(clientId, cacheConfig, cryptoImpl, logger, performanceClient, eventHandler, staticAuthorityOptions, tokenBindingKeyManager = DEFAULT_TOKEN_BINDING_KEY_MANAGER) {
super(clientId, cryptoImpl, logger, performanceClient, staticAuthorityOptions, tokenBindingKeyManager);
this.cacheConfig = cacheConfig;
this.logger = logger;
this.internalStorage = new MemoryStorage();
this.browserStorage = getStorageImplementation(clientId, cacheConfig.cacheLocation, logger, performanceClient);
this.temporaryCacheStorage = getStorageImplementation(clientId, BrowserCacheLocation.SessionStorage, logger, performanceClient);
this.cookieStorage = new CookieStorage();
this.eventHandler = eventHandler;
}
async initialize(correlationId) {
this.performanceClient.addFields({
cacheLocation: this.cacheConfig.cacheLocation,
cacheRetentionDays: this.cacheConfig.cacheRetentionDays,
}, correlationId);
await this.browserStorage.initialize(correlationId);
await this.migrateExistingCache(correlationId);
this.trackVersionChanges(correlationId);
}
/**
* Migrates any existing cache data from previous versions of MSAL.js into the current cache structure.
*/
async migrateExistingCache(correlationId) {
let accountKeys = getAccountKeys(this.browserStorage);
let tokenKeys = getTokenKeys(this.clientId, this.browserStorage);
this.performanceClient.addFields({
preMigrateAcntCount: accountKeys.length,
preMigrateATCount: tokenKeys.accessToken.length,
preMigrateITCount: tokenKeys.idToken.length,
preMigrateRTCount: tokenKeys.refreshToken.length,
}, correlationId);
for (let i = 0; i < ACCOUNT_SCHEMA_VERSION; i++) {
const credentialSchema = i; // For now account and credential schemas are the same, but may diverge in future
await this.removeStaleAccounts(i, credentialSchema, correlationId);
}
// Must migrate idTokens first to ensure we have KMSI info for the rest
for (let i = 0; i < CREDENTIAL_SCHEMA_VERSION; i++) {
const accountSchema = i; // For now account and credential schemas are the same, but may diverge in future
await this.migrateIdTokens(i, accountSchema, correlationId);
}
const kmsiMap = this.getKMSIValues();
for (let i = 0; i < CREDENTIAL_SCHEMA_VERSION; i++) {
await this.migrateAccessTokens(i, kmsiMap, correlationId);
await this.migrateRefreshTokens(i, kmsiMap, correlationId);
}
accountKeys = getAccountKeys(this.browserStorage);
tokenKeys = getTokenKeys(this.clientId, this.browserStorage);
this.performanceClient.addFields({
postMigrateAcntCount: accountKeys.length,
postMigrateATCount: tokenKeys.accessToken.length,
postMigrateITCount: tokenKeys.idToken.length,
postMigrateRTCount: tokenKeys.refreshToken.length,
}, correlationId);
}
/**
* Parses entry, adds lastUpdatedAt if it doesn't exist, removes entry if expired or invalid
* @param key
* @param correlationId
* @returns
*/
async updateOldEntry(key, correlationId) {
const rawValue = this.browserStorage.getItem(key);
const parsedValue = this.validateAndParseJson(rawValue || "");
if (!parsedValue) {
this.browserStorage.removeItem(key);
return {
entry: null,
removalReason: MigrationRemovalReason.Invalid,
};
}
if (!parsedValue.lastUpdatedAt) {
// Add lastUpdatedAt to the existing v0 entry if it doesnt exist so we know when it's safe to remove it
parsedValue.lastUpdatedAt = Date.now().toString();
this.setItem(key, JSON.stringify(parsedValue), correlationId);
}
else if (isCacheExpired(parsedValue.lastUpdatedAt, this.cacheConfig.cacheRetentionDays)) {
this.browserStorage.removeItem(key);
return {
entry: null,
removalReason: MigrationRemovalReason.TtlExpired,
};
}
const wasEncrypted = isEncrypted(parsedValue);
const decryptedData = wasEncrypted
? await this.browserStorage.decryptData(key, parsedValue, correlationId)
: parsedValue;
if (!decryptedData) {
this.browserStorage.removeItem(key);
return {
entry: null,
removalReason: wasEncrypted
? MigrationRemovalReason.DecryptFailed
: MigrationRemovalReason.Invalid,
};
}
if (!isCredentialEntity(decryptedData)) {
this.browserStorage.removeItem(key);
return {
entry: null,
removalReason: MigrationRemovalReason.Invalid,
};
}
if ((isAccessTokenEntity(decryptedData) ||
isRefreshTokenEntity(decryptedData)) &&
decryptedData.expiresOn &&
isTokenExpired(decryptedData.expiresOn, DEFAULT_TOKEN_RENEWAL_OFFSET_SEC)) {
this.browserStorage.removeItem(key);
return {
entry: null,
removalReason: MigrationRemovalReason.Expired,
};
}
return { entry: decryptedData };
}
/**
* Remove accounts from the cache for older schema versions if they have not been updated in the last cacheRetentionDays
* @param accountSchema
* @param credentialSchema
* @param correlationId
* @returns
*/
async removeStaleAccounts(accountSchema, credentialSchema, correlationId) {
const accountKeysToCheck = getAccountKeys(this.browserStorage, accountSchema);
if (accountKeysToCheck.length === 0) {
return;
}
for (const accountKey of [...accountKeysToCheck]) {
this.performanceClient.incrementFields({ oldAcntCount: 1 }, correlationId);
const rawValue = this.browserStorage.getItem(accountKey);
const parsedValue = this.validateAndParseJson(rawValue || "");
if (!parsedValue) {
this.browserStorage.removeItem(accountKey);
this.performanceClient.incrementFields({ invalidAcntCount: 1 }, correlationId);
removeElementFromArray(accountKeysToCheck, accountKey);
continue;
}
if (!parsedValue.lastUpdatedAt) {
// Add lastUpdatedAt to the existing entry if it doesnt exist so we know when it's safe to remove it
parsedValue.lastUpdatedAt = Date.now().toString();
this.setItem(accountKey, JSON.stringify(parsedValue), correlationId);
continue;
}
else if (isCacheExpired(parsedValue.lastUpdatedAt, this.cacheConfig.cacheRetentionDays)) {
// Cache expired remove account and associated tokens
await this.removeAccountOldSchema(accountKey, parsedValue, credentialSchema, correlationId);
this.performanceClient.incrementFields({ ttlExpiredAcntCount: 1 }, correlationId);
removeElementFromArray(accountKeysToCheck, accountKey);
}
else if (isEncrypted(parsedValue)) {
// Remove accounts encrypted with a different key (session cookie expired/changed)
const decrypted = await this.browserStorage.decryptData(accountKey, parsedValue, correlationId);
if (!decrypted) {
this.browserStorage.removeItem(accountKey);
this.performanceClient.incrementFields({
decryptFailedAcntCount: 1,
}, correlationId);
removeElementFromArray(accountKeysToCheck, accountKey);
}
}
}
this.setAccountKeys(accountKeysToCheck, correlationId, accountSchema);
}
/**
* Remove the given account and all associated tokens from the cache
* @param accountKey
* @param rawObject
* @param credentialSchema
* @param correlationId
*/
async removeAccountOldSchema(accountKey, rawObject, credentialSchema, correlationId) {
const decryptedData = isEncrypted(rawObject)
? (await this.browserStorage.decryptData(accountKey, rawObject, correlationId))
: rawObject;
const homeAccountId = decryptedData?.homeAccountId;
if (homeAccountId) {
const tokenKeys = this.getTokenKeys(credentialSchema);
[...tokenKeys.idToken]
.filter((key) => key.includes(homeAccountId))
.forEach((key) => {
this.browserStorage.removeItem(key);
removeElementFromArray(tokenKeys.idToken, key);
});
[...tokenKeys.accessToken]
.filter((key) => key.includes(homeAccountId))
.forEach((key) => {
this.browserStorage.removeItem(key);
removeElementFromArray(tokenKeys.accessToken, key);
});
[...tokenKeys.refreshToken]
.filter((key) => key.includes(homeAccountId))
.forEach((key) => {
this.browserStorage.removeItem(key);
removeElementFromArray(tokenKeys.refreshToken, key);
});
this.setTokenKeys(tokenKeys, correlationId, credentialSchema);
}
this.browserStorage.removeItem(accountKey);
}
/**
* Gets key value pair mapping homeAccountId to KMSI value
* @returns
*/
getKMSIValues() {
const kmsiMap = {};
const tokenKeys = this.getTokenKeys().idToken;
for (const key of tokenKeys) {
const rawValue = this.browserStorage.getUserData(key);
if (rawValue) {
const idToken = JSON.parse(rawValue);
const claims = extractTokenClaims(idToken.secret, base64Decode, "");
if (claims) {
kmsiMap[idToken.homeAccountId] = isKmsi(claims);
}
}
}
return kmsiMap;
}
/**
* Migrates id tokens from the old schema to the new schema, also migrates associated account object if it doesn't already exist in the new schema
* @param credentialSchema
* @param accountSchema
* @param correlationId
* @returns
*/
async migrateIdTokens(credentialSchema, accountSchema, correlationId) {
const credentialKeysToMigrate = getTokenKeys(this.clientId, this.browserStorage, credentialSchema);
if (credentialKeysToMigrate.idToken.length === 0) {
return;
}
const currentCredentialKeys = getTokenKeys(this.clientId, this.browserStorage, CREDENTIAL_SCHEMA_VERSION);
const currentAccountKeys = getAccountKeys(this.browserStorage);
const previousAccountKeys = getAccountKeys(this.browserStorage, accountSchema);
for (const idTokenKey of [...credentialKeysToMigrate.idToken]) {
this.performanceClient.incrementFields({ oldITCount: 1 }, correlationId);
const result = await this.updateOldEntry(idTokenKey, correlationId);
const oldSchemaData = result.entry;
if (!oldSchemaData) {
switch (result.removalReason) {
case MigrationRemovalReason.TtlExpired:
this.performanceClient.incrementFields({ ttlExpiredITCount: 1 }, correlationId);
break;
case MigrationRemovalReason.DecryptFailed:
this.performanceClient.incrementFields({ decryptFailedITCount: 1 }, correlationId);
break;
case MigrationRemovalReason.Invalid:
this.performanceClient.incrementFields({ invalidITCount: 1 }, correlationId);
break;
}
removeElementFromArray(credentialKeysToMigrate.idToken, idTokenKey);
continue;
}
const currentAccountKey = currentAccountKeys.find((key) => key.includes(oldSchemaData.homeAccountId));
const previousAccountKey = previousAccountKeys.find((key) => key.includes(oldSchemaData.homeAccountId));
let account = null;
if (currentAccountKey) {
account = this.getAccount(currentAccountKey, correlationId);
}
else if (previousAccountKey) {
const rawValue = this.browserStorage.getItem(previousAccountKey);
const parsedValue = this.validateAndParseJson(rawValue || "");
account =
parsedValue && isEncrypted(parsedValue)
? (await this.browserStorage.decryptData(previousAccountKey, parsedValue, correlationId))
: parsedValue;
}
if (!account) {
// Don't migrate idToken if we don't have an account for it
this.performanceClient.incrementFields({ skipITMigrateCount: 1 }, correlationId);
continue;
}
const claims = extractTokenClaims(oldSchemaData.secret, base64Decode, correlationId);
const newIdTokenKey = this.generateCredentialKey(oldSchemaData);
const currentIdToken = this.getIdTokenCredential(newIdTokenKey, correlationId);
const oldTokenHasSignInState = Object.keys(claims).includes("signin_state");
const currentTokenHasSignInState = currentIdToken &&
Object.keys(extractTokenClaims(currentIdToken.secret, base64Decode, correlationId) || {}).includes("signin_state");
/**
* Only migrate if:
* 1. Token doesn't yet exist in current schema
* 2. Old schema token has been updated more recently than the current one AND migrating it won't result in loss of KMSI state
*/
if (!currentIdToken ||
(oldSchemaData.lastUpdatedAt > currentIdToken.lastUpdatedAt &&
(oldTokenHasSignInState || !currentTokenHasSignInState))) {
const tenantProfiles = account.tenantProfiles || [];
const tenantId = getTenantIdFromIdTokenClaims(claims) || account.realm;
if (tenantId &&
!tenantProfiles.find((tenantProfile) => {
return tenantProfile.tenantId === tenantId;
})) {
const newTenantProfile = buildTenantProfile(account.homeAccountId, account.localAccountId, tenantId, account.nativeAccountId, claims);
tenantProfiles.push(newTenantProfile);
}
account.tenantProfiles = tenantProfiles;
const newAccountKey = this.generateAccountKey(getAccountInfo(account));
const kmsi = isKmsi(claims);
await this.setUserData(newAccountKey, JSON.stringify(account), correlationId, account.lastUpdatedAt, kmsi);
if (!currentAccountKeys.includes(newAccountKey)) {
currentAccountKeys.push(newAccountKey);
}
await this.setUserData(newIdTokenKey, JSON.stringify(oldSchemaData), correlationId, oldSchemaData.lastUpdatedAt, kmsi);
this.performanceClient.incrementFields({ migratedITCount: 1 }, correlationId);
if (!currentCredentialKeys.idToken.includes(newIdTokenKey)) {
currentCredentialKeys.idToken.push(newIdTokenKey);
}
}
}
this.setTokenKeys(credentialKeysToMigrate, correlationId, credentialSchema);
this.setTokenKeys(currentCredentialKeys, correlationId);
this.setAccountKeys(currentAccountKeys, correlationId);
}
/**
* Migrates access tokens from old cache schema to current schema
* @param credentialSchema
* @param kmsiMap
* @param correlationId
* @returns
*/
async migrateAccessTokens(credentialSchema, kmsiMap, correlationId) {
const credentialKeysToMigrate = getTokenKeys(this.clientId, this.browserStorage, credentialSchema);
if (credentialKeysToMigrate.accessToken.length === 0) {
return;
}
const currentCredentialKeys = getTokenKeys(this.clientId, this.browserStorage, CREDENTIAL_SCHEMA_VERSION);
for (const accessTokenKey of [...credentialKeysToMigrate.accessToken]) {
this.performanceClient.incrementFields({ oldATCount: 1 }, correlationId);
const result = await this.updateOldEntry(accessTokenKey, correlationId);
const oldSchemaData = result.entry;
if (!oldSchemaData) {
switch (result.removalReason) {
case MigrationRemovalReason.TtlExpired:
this.performanceClient.incrementFields({ ttlExpiredATCount: 1 }, correlationId);
break;
case MigrationRemovalReason.DecryptFailed:
this.performanceClient.incrementFields({ decryptFailedATCount: 1 }, correlationId);
break;
case MigrationRemovalReason.Expired:
this.performanceClient.incrementFields({ expiredATCount: 1 }, correlationId);
break;
case MigrationRemovalReason.Invalid:
this.performanceClient.incrementFields({ invalidATCount: 1 }, correlationId);
break;
}
removeElementFromArray(credentialKeysToMigrate.accessToken, accessTokenKey);
continue;
}
if (!(oldSchemaData.homeAccountId in kmsiMap)) {
// Don't migrate tokens if we don't have an idToken for them
this.performanceClient.incrementFields({ skipATMigrateCount: 1 }, correlationId);
continue;
}
const newKey = this.generateCredentialKey(oldSchemaData);
const kmsi = kmsiMap[oldSchemaData.homeAccountId];
if (!currentCredentialKeys.accessToken.includes(newKey)) {
await this.setUserData(newKey, JSON.stringify(oldSchemaData), correlationId, oldSchemaData.lastUpdatedAt, kmsi);
this.performanceClient.incrementFields({ migratedATCount: 1 }, correlationId);
currentCredentialKeys.accessToken.push(newKey);
}
else {
const currentToken = this.getAccessTokenCredential(newKey, correlationId);
if (!currentToken ||
oldSchemaData.lastUpdatedAt > currentToken.lastUpdatedAt) {
// If the token already exists, only overwrite it if the old token has a more recent lastUpdatedAt
await this.setUserData(newKey, JSON.stringify(oldSchemaData), correlationId, oldSchemaData.lastUpdatedAt, kmsi);
this.performanceClient.incrementFields({ migratedATCount: 1 }, correlationId);
}
}
}
this.setTokenKeys(credentialKeysToMigrate, correlationId, credentialSchema);
this.setTokenKeys(currentCredentialKeys, correlationId);
}
/**
* Migrates refresh tokens from old cache schema to current schema
* @param credentialSchema
* @param kmsiMap
* @param correlationId
* @returns
*/
async migrateRefreshTokens(credentialSchema, kmsiMap, correlationId) {
const credentialKeysToMigrate = getTokenKeys(this.clientId, this.browserStorage, credentialSchema);
if (credentialKeysToMigrate.refreshToken.length === 0) {
return;
}
const currentCredentialKeys = getTokenKeys(this.clientId, this.browserStorage, CREDENTIAL_SCHEMA_VERSION);
for (const refreshTokenKey of [
...credentialKeysToMigrate.refreshToken,
]) {
this.performanceClient.incrementFields({ oldRTCount: 1 }, correlationId);
const result = await this.updateOldEntry(refreshTokenKey, correlationId);
const oldSchemaData = result.entry;
if (!oldSchemaData) {
switch (result.removalReason) {
case MigrationRemovalReason.TtlExpired:
this.performanceClient.incrementFields({ ttlExpiredRTCount: 1 }, correlationId);
break;
case MigrationRemovalReason.DecryptFailed:
this.performanceClient.incrementFields({ decryptFailedRTCount: 1 }, correlationId);
break;
case MigrationRemovalReason.Expired:
this.performanceClient.incrementFields({ expiredRTCount: 1 }, correlationId);
break;
case MigrationRemovalReason.Invalid:
this.performanceClient.incrementFields({ invalidRTCount: 1 }, correlationId);
break;
}
removeElementFromArray(credentialKeysToMigrate.refreshToken, refreshTokenKey);
continue;
}
if (!(oldSchemaData.homeAccountId in kmsiMap)) {
// Don't migrate tokens if we don't have an idToken for them
this.performanceClient.incrementFields({ skipRTMigrateCount: 1 }, correlationId);
continue;
}
const newKey = this.generateCredentialKey(oldSchemaData);
const kmsi = kmsiMap[oldSchemaData.homeAccountId];
if (!currentCredentialKeys.refreshToken.includes(newKey)) {
await this.setUserData(newKey, JSON.stringify(oldSchemaData), correlationId, oldSchemaData.lastUpdatedAt, kmsi);
this.performanceClient.incrementFields({ migratedRTCount: 1 }, correlationId);
currentCredentialKeys.refreshToken.push(newKey);
}
else {
const currentToken = this.getRefreshTokenCredential(newKey, correlationId);
if (!currentToken ||
oldSchemaData.lastUpdatedAt > currentToken.lastUpdatedAt) {
// If the token already exists, only overwrite it if the old token has a more recent lastUpdatedAt
await this.setUserData(newKey, JSON.stringify(oldSchemaData), correlationId, oldSchemaData.lastUpdatedAt, kmsi);
this.performanceClient.incrementFields({ migratedRTCount: 1 }, correlationId);
}
}
}
this.setTokenKeys(credentialKeysToMigrate, correlationId, credentialSchema);
this.setTokenKeys(currentCredentialKeys, correlationId);
}
/**
* Tracks upgrades and downgrades for telemetry and debugging purposes
*/
trackVersionChanges(correlationId) {
const previousVersion = this.browserStorage.getItem(VERSION_CACHE_KEY);
if (previousVersion) {
this.logger.info(`1wuc87 ${previousVersion}`, correlationId);
this.performanceClient.addGlobalFields({
previousLibraryVersion: previousVersion,
});
}
if (previousVersion !== version) {
this.setItem(VERSION_CACHE_KEY, version, correlationId);
}
}
/**
* Parses passed value as JSON object, JSON.parse() will throw an error.
* @param input
*/
validateAndParseJson(jsonValue) {
if (!jsonValue) {
return null;
}
try {
const parsedJson = JSON.parse(jsonValue);
/**
* There are edge cases in which JSON.parse will successfully parse a non-valid JSON object
* (e.g. JSON.parse will parse an escaped string into an unescaped string), so adding a type check
* of the parsed value is necessary in order to be certain that the string represents a valid JSON object.
*
*/
return parsedJson && typeof parsedJson === "object"
? parsedJson
: null;
}
catch (error) {
return null;
}
}
/**
* Helper to setItem in browser storage, with cleanup in case of quota errors
* @param key
* @param value
*/
setItem(key, value, correlationId) {
const tokenKeysCount = new Array(CREDENTIAL_SCHEMA_VERSION + 1).fill(0); // Array mapping schema version to number of token keys stored for that version
const accessTokenKeys = []; // Flat map of all access token keys stored, ordered by schema version
const maxRetries = 20;
for (let i = 0; i <= maxRetries; i++) {
// Attempt to store item in cache, if cache is full this call will throw and we'll attempt to clear space by removing access tokens from the cache one by one, starting with tokens stored by previous versions of MSAL.js
try {
this.browserStorage.setItem(key, value);
if (i > 0) {
// If any tokens were removed in order to store this item update the token keys array with the tokens removed
for (let schemaVersion = 0; schemaVersion <= CREDENTIAL_SCHEMA_VERSION; schemaVersion++) {
// Get the sum of all previous token counts to use as start index for this schema version
const startIndex = tokenKeysCount
.slice(0, schemaVersion)
.reduce((sum, count) => sum + count, 0);
if (startIndex >= i) {
// Done removing tokens
break;
}
const endIndex = i > startIndex + tokenKeysCount[schemaVersion]
? startIndex + tokenKeysCount[schemaVersion]
: i;
if (i > startIndex &&
tokenKeysCount[schemaVersion] > 0) {
this.removeAccessTokenKeys(accessTokenKeys.slice(startIndex, endIndex), correlationId, schemaVersion);
}
}
}
break; // If setItem succeeds, exit the loop
}
catch (e) {
const cacheError = createCacheError(e);
if (cacheError.errorCode ===
cacheQuotaExceeded &&
i < maxRetries) {
if (!accessTokenKeys.length) {
// If we are currently trying to set the token keys, use the value we're trying to set
for (let i = 0; i <= CREDENTIAL_SCHEMA_VERSION; i++) {
if (key ===
getTokenKeysCacheKey(this.clientId, i)) {
const tokenKeys = JSON.parse(value).accessToken;
accessTokenKeys.push(...tokenKeys);
tokenKeysCount[i] = tokenKeys.length;
}
else {
const tokenKeys = this.getTokenKeys(i).accessToken;
accessTokenKeys.push(...tokenKeys);
tokenKeysCount[i] = tokenKeys.length;
}
}
}
if (accessTokenKeys.length <= i) {
// Nothing to remove, rethrow the error
throw cacheError;
}
// When cache quota is exceeded, start removing access tokens until we can successfully set the item
this.removeAccessToken(accessTokenKeys[i], correlationId, false // Don't save token keys yet, do it at the end
);
}
else {
// If the error is not a quota exceeded error, rethrow it
throw cacheError;
}
}
}
}
/**
* Helper to setUserData in browser storage, with cleanup in case of quota errors
* @param key
* @param value
* @param correlationId
*/
async setUserData(key, value, correlationId, timestamp, kmsi) {
const tokenKeysCount = new Array(CREDENTIAL_SCHEMA_VERSION + 1).fill(0); // Array mapping schema version to number of token keys stored for that version
const accessTokenKeys = []; // Flat map of all access token keys stored, ordered by schema version
const maxRetries = 20;
for (let i = 0; i <= maxRetries; i++) {
try {
// Attempt to store item in cache, if cache is full this call will throw and we'll attempt to clear space by removing access tokens from the cache one by one, starting with tokens stored by previous versions of MSAL.js
await invokeAsync(this.browserStorage.setUserData.bind(this.browserStorage), SetUserData, this.logger, this.performanceClient, correlationId)(key, value, correlationId, timestamp, kmsi);
if (i > 0) {
// If any tokens were removed in order to store this item update the token keys array with the tokens removed
for (let schemaVersion = 0; schemaVersion <= CREDENTIAL_SCHEMA_VERSION; schemaVersion++) {
// Get the sum of all previous token counts to use as start index for this schema version
const startIndex = tokenKeysCount
.slice(0, schemaVersion)
.reduce((sum, count) => sum + count, 0);
if (startIndex >= i) {
// Done removing tokens
break;
}
const endIndex = i > startIndex + tokenKeysCount[schemaVersion]
? startIndex + tokenKeysCount[schemaVersion]
: i;
if (i > startIndex &&
tokenKeysCount[schemaVersion] > 0) {
this.removeAccessTokenKeys(accessTokenKeys.slice(startIndex, endIndex), correlationId, schemaVersion);
}
}
}
break; // If setItem succeeds, exit the loop
}
catch (e) {
const cacheError = createCacheError(e);
if (cacheError.errorCode ===
cacheQuotaExceeded &&
i < maxRetries) {
if (!accessTokenKeys.length) {
// If we are currently trying to set the token keys, use the value we're trying to set
for (let i = 0; i <= CREDENTIAL_SCHEMA_VERSION; i++) {
const tokenKeys = this.getTokenKeys(i).accessToken;
accessTokenKeys.push(...tokenKeys);
tokenKeysCount[i] = tokenKeys.length;
}
}
if (accessTokenKeys.length <= i) {
// Nothing left to remove, rethrow the error
throw cacheError;
}
// When cache quota is exceeded, start removing access tokens until we can successfully set the item
this.removeAccessToken(accessTokenKeys[i], correlationId, false // Don't save token keys yet, do it at the end
);
}
else {
// If the error is not a quota exceeded error, rethrow it
throw cacheError;
}
}
}
}
/**
* Reads account from cache, deserializes it into an account entity and returns it.
* If account is not found from the key, returns null and removes key from map.
* @param accountKey
* @returns
*/
getAccount(accountKey, correlationId) {
this.logger.trace("1lfvm6", correlationId);
const serializedAccount = this.browserStorage.getUserData(accountKey);
if (!serializedAccount) {
this.removeAccountKeyFromMap(accountKey, correlationId);
return null;
}
const parsedAccount = this.validateAndParseJson(serializedAccount);
if (!parsedAccount ||
!isAccountEntity(parsedAccount)) {
return null;
}
const account = CacheManager.toObject({}, parsedAccount);
this.performanceClient.addFields({
accountCachedBy: apiIdToName(account.cachedByApiId),
}, correlationId);
return account;
}
/**
* set account entity in the platform cache
* @param account
*/
async setAccount(account, correlationId, kmsi, apiId) {
this.logger.trace("1bz3wr", correlationId);
const key = this.generateAccountKey(getAccountInfo(account));
const timestamp = Date.now().toString();
account.lastUpdatedAt = timestamp;
account.cachedByApiId = apiId;
await this.setUserData(key, JSON.stringify(account), correlationId, timestamp, kmsi);
this.addAccountKeyToMap(key, correlationId);
this.performanceClient.addFields({ kmsi: kmsi }, correlationId);
}
setAccountKeys(accountKeys, correlationId, schemaVersion = ACCOUNT_SCHEMA_VERSION) {
if (accountKeys.length === 0) {
this.removeItem(getAccountKeysCacheKey(schemaVersion));
}
else {
this.setItem(getAccountKeysCacheKey(schemaVersion), JSON.stringify(accountKeys), correlationId);
}
}
/**
* Returns the array of account keys currently cached
* @returns
*/
getAccountKeys() {
return getAccountKeys(this.browserStorage);
}
/**
* Add a new account to the key map
* @param key
*/
addAccountKeyToMap(key, correlationId) {
this.logger.trace("0rb85k", correlationId);
this.logger.tracePii(`1l9bdo ${key}`, correlationId);
const accountKeys = this.getAccountKeys();
if (accountKeys.indexOf(key) === -1) {
// Only add key if it does not already exist in the map
accountKeys.push(key);
this.setItem(getAccountKeysCacheKey(), JSON.stringify(accountKeys), correlationId);
this.logger.verbose("0xia39", correlationId);
return true;
}
else {
this.logger.verbose("0161kk", correlationId);
return false;
}
}
/**
* Remove an account from the key map
* @param key
*/
removeAccountKeyFromMap(key, correlationId) {
this.logger.trace("1jpigu", correlationId);
this.logger.tracePii(`1xzspl ${key}`, correlationId);
const accountKeys = this.getAccountKeys();
const removalIndex = accountKeys.indexOf(key);
if (removalIndex > -1) {
accountKeys.splice(removalIndex, 1);
this.setAccountKeys(accountKeys, correlationId);
}
else {
this.logger.trace("1dytu2", correlationId);
}
}
/**
* Extends inherited removeAccount function to include removal of the account key from the map
* @param key
*/
removeAccount(account, correlationId) {
const activeAccount = this.getActiveAccount(correlationId);
if (activeAccount?.homeAccountId === account.homeAccountId &&
activeAccount?.environment === account.environment) {
this.setActiveAccount(null, correlationId);
}
super.removeAccount(account, correlationId);
this.removeAccountKeyFromMap(this.generateAccountKey(account), correlationId);
// Remove all other associated cache items
this.browserStorage.getKeys().forEach((key) => {
if (key.includes(account.homeAccountId) &&
key.includes(account.environment)) {
this.browserStorage.removeItem(key);
}
});
}
/**
* Removes given idToken from the cache and from the key map
* @param key
*/
removeIdToken(key, correlationId) {
super.removeIdToken(key, correlationId);
const tokenKeys = this.getTokenKeys();
const idRemoval = tokenKeys.idToken.indexOf(key);
if (idRemoval > -1) {
this.logger.info("05udv9", correlationId);
tokenKeys.idToken.splice(idRemoval, 1);
this.setTokenKeys(tokenKeys, correlationId);
}
}
/**
* Removes given accessToken from the cache and from the key map
* @param key
*/
removeAccessToken(key, correlationId, updateTokenKeys = true) {
super.removeAccessToken(key, correlationId);
updateTokenKeys && this.removeAccessTokenKeys([key], correlationId);
}
/**
* Remove access token key from the key map
* @param key
* @param correlationId
* @param tokenKeys
*/
removeAccessTokenKeys(keys, correlationId, schemaVersion = CREDENTIAL_SCHEMA_VERSION) {
this.logger.trace("17o18n", correlationId);
const tokenKeys = this.getTokenKeys(schemaVersion);
let keysRemoved = 0;
keys.forEach((key) => {
const accessRemoval = tokenKeys.accessToken.indexOf(key);
if (accessRemoval > -1) {
tokenKeys.accessToken.splice(accessRemoval, 1);
keysRemoved++;
}
});
if (keysRemoved > 0) {
this.logger.info(`15i5d5 ${keysRemoved}`, correlationId);
this.setTokenKeys(tokenKeys, correlationId, schemaVersion);
return;
}
}
/**
* Removes given refreshToken from the cache and from the key map
* @param key
*/
removeRefreshToken(key, correlationId) {
super.removeRefreshToken(key, correlationId);
const tokenKeys = this.getTokenKeys();
const refreshRemoval = tokenKeys.refreshToken.indexOf(key);
if (refreshRemoval > -1) {
this.logger.info("1f4fq3", correlationId);
tokenKeys.refreshToken.splice(refreshRemoval, 1);
this.setTokenKeys(tokenKeys, correlationId);
}
}
/**
* Gets the keys for the cached tokens associated with this clientId
* @returns
*/
getTokenKeys(schemaVersion = CREDENTIAL_SCHEMA_VERSION) {
return getTokenKeys(this.clientId, this.browserStorage, schemaVersion);
}
/**
* Sets the token keys in the cache
* @param tokenKeys
* @param correlationId
* @returns
*/
setTokenKeys(tokenKeys, correlationId, schemaVersion = CREDENTIAL_SCHEMA_VERSION) {
if (tokenKeys.idToken.length === 0 &&
tokenKeys.accessToken.length === 0 &&
tokenKeys.refreshToken.length === 0) {
// If no keys left, remove the map
this.removeItem(getTokenKeysCacheKey(this.clientId, schemaVersion));
return;
}
else {
this.setItem(getTokenKeysCacheKey(this.clientId, schemaVersion), JSON.stringify(tokenKeys), correlationId);
}
}
/**
* generates idToken entity from a string
* @param idTokenKey
*/
getIdTokenCredential(idTokenKey, correlationId) {
const value = this.browserStorage.getUserData(idTokenKey);
if (!value) {
this.logger.trace("1jukz6", correlationId);
this.removeIdToken(idTokenKey, correlationId);
return null;
}
const parsedIdToken = this.validateAndParseJson(value);
if (!parsedIdToken || !isIdTokenEntity(parsedIdToken)) {
this.logger.trace("1jukz6", correlationId);
return null;
}
this.logger.trace("01ju66", correlationId);
return parsedIdToken;
}
/**
* set IdToken credential to the platform cache
* @param idToken
*/
async setIdTokenCredential(idToken, correlationId, kmsi) {
this.logger.trace("13hjll", correlationId);
const idTokenKey = this.generateCredentialKey(idToken);
const timestamp = Date.now().toString();
idToken.lastUpdatedAt = timestamp;
await this.setUserData(idTokenKey, JSON.stringify(idToken), correlationId, timestamp, kmsi);
const tokenKeys = this.getTokenKeys();
if (tokenKeys.idToken.indexOf(idTokenKey) === -1) {
this.logger.info("07jy92", correlationId);
tokenKeys.idToken.push(idTokenKey);
this.setTokenKeys(tokenKeys, correlationId);
}
}
/**
* generates accessToken entity from a string
* @param key
*/
getAccessTokenCredential(accessTokenKey, correlationId) {
const value = this.browserStorage.getUserData(accessTokenKey);
if (!value) {
this.logger.trace("0bqvx8", correlationId);
this.removeAccessTokenKeys([accessTokenKey], correlationId);
return null;
}
const parsedAccessToken = this.validateAndParseJson(value);
if (!parsedAccessToken ||
!isAccessTokenEntity(parsedAccessToken)) {
this.logger.trace("0bqvx8", correlationId);
return null;
}
this.logger.trace("1o81rl", correlationId);
return parsedAccessToken;
}
/**
* Set accessToken credential to the platform cache
* @param accessToken - the access token entity to cache
*/
async setAccessTokenCredential(accessToken, correlationId, kmsi, additionalCacheKeyHash) {
this.logger.trace("1pondb", correlationId);
const accessTokenKey = this.generateCredentialKey(accessToken, additionalCacheKeyHash);
const timestamp = Date.now().toString();
accessToken.lastUpdatedAt = timestamp;
await this.setUserData(accessTokenKey, JSON.stringify(accessToken), correlationId, timestamp, kmsi);
const tokenKeys = this.getTokenKeys();
const index = tokenKeys.accessToken.indexOf(accessTokenKey);
if (index !== -1) {
tokenKeys.accessToken.splice(index, 1); // Remove existing key before pushing to the end
}
this.logger.trace(`1onhey ${index === -1 ? "added to" : "updated in"}`, correlationId);
tokenKeys.accessToken.push(accessTokenKey);
this.setTokenKeys(tokenKeys, correlationId);
}
/**
* generates refreshToken entity from a string
* @param refreshTokenKey
*/
getRefreshTokenCredential(refreshTokenKey, correlationId) {
const value = this.browserStorage.getUserData(refreshTokenKey);
if (!value) {
this.logger.trace("0jlizt", correlationId);
this.removeRefreshToken(refreshTokenKey, correlationId);
return null;
}
const parsedRefreshToken = this.validateAndParseJson(value);
if (!parsedRefreshToken ||
!isRefreshTokenEntity(parsedRefreshToken)) {
this.logger.trace("0jlizt", correlationId);
return null;
}
this.logger.trace("0nokxi", correlationId);
return parsedRefreshToken;
}
/**
* set refreshToken credential to the platform cache
* @param refreshToken
*/
async setRefreshTokenCredential(refreshToken, correlationId, kmsi) {
this.logger.trace("0tcg8d", correlationId);
const refreshTokenKey = this.generateCredentialKey(refreshToken);
const timestamp = Date.now().toString();
refreshToken.lastUpdatedAt = timestamp;
await this.setUserData(refreshTokenKey, JSON.stringify(refreshToken), correlationId, timestamp, kmsi);
const tokenKeys = this.getTokenKeys();
if (tokenKeys.refreshToken.indexOf(refreshTokenKey) === -1) {
this.logger.info("0eckjs", correlationId);
tokenKeys.refreshToken.push(refreshTokenKey);
this.setTokenKeys(tokenKeys, correlationId);
}
}
/**
* fetch appMetadata entity from the platform cache
* @param appMetadataKey
* @param correlationId
*/
getAppMetadata(appMetadataKey, correlationId) {
const value = this.browserStorage.getItem(appMetadataKey);
if (!value) {
this.logger.trace("1q101h", correlationId);
return null;
}
const parsedMetadata = this.validateAndParseJson(value);
if (!parsedMetadata ||
!isAppMetadataEntity(appMetadataKey, parsedMetadata)) {
this.logger.trace("1q101h", correlationId);
return null;
}
this.logger.trace("19pvg2", correlationId);
return parsedMetadata;
}
/**
* set appMetadata entity to the platform cache
* @param appMetadata
* @param correlationId
*/
setAppMetadata(appMetadata, correlationId) {
this.logger.trace("0cyma6", correlationId);
const appMetadataKey = generateAppMetadataKey(appMetadata);
this.setItem(appMetadataKey, JSON.stringify(appMetadata), correlationId);
}
/**
* fetch server telemetry entity from the platform cache
* @param serverTelemetryKey
* @param correlationId
*/
getServerTelemetry(serverTelemetryKey, correlationId) {
const value = this.browserStorage.getItem(serverTelemetryKey);
if (!value) {
this.logger.trace("0jk19c", correlationId);
return null;
}
const parsedEntity = this.validateAndParseJson(value);
if (!parsedEntity ||
!isServerTelemetryEntity(serverTelemetryKey, parsedEntity)) {
this.logger.trace("0jk19c", correlationId);
return null;
}
this.logger.trace("12jguk", correlationId);
return parsedEntity;
}
/**
* set server telemetry entity to the platform cache
* @param serverTelemetryKey
* @param serverTelemetry
*/
setServerTelemetry(serverTelemetryKey, serverTelemetry, correlationId) {
this.logger.trace("1poh61", correlationId);
this.setItem(serverTelemetryKey, JSON.stringify(serverTelemetry), correlationId);
}
/**
*
*/
getAuthorityMetadata(key, correlationId) {
const value = this.internalStorage.getItem(key);
if (!value) {
this.logger.trace("1r39oe", correlationId);
return null;
}
const parsedMetadata = this.validateAndParseJson(value);
if (parsedMetadata &&
isAuthorityMetadataEntity(key, parsedMetadata)) {
this.logger.trace("1ohvk3", correlationId);
return parsedMetadata;
}
return null;
}
/**
*
*/
getAuthorityMetadataKeys() {
const allKeys = this.internalStorage.getKeys();
return allKeys.filter((key) => {
return this.isAuthorityMetadata(key);
});
}
/**
* Sets wrapper metadata in memory
* @param wrapperSKU
* @param wrapperVersion
*/
setWrapperMetadata(wrapperSKU, wrapperVersion) {
this.internalStorage.setItem(InMemoryCacheKeys.WRAPPER_SKU, wrapperSKU);
this.internalStorage.setItem(InMemoryCacheKeys.WRAPPER_VER, wrapperVersion);
}
/**
* Returns wrapper metadata from in-memory storage
*/
getWrapperMetadata() {
const sku = this.internalStorage.getItem(InMemoryCacheKeys.WRAPPER_SKU) || "";
const version = this.internalStorage.getItem(InMemoryCacheKeys.WRAPPER_VER) || "";
return [sku, version];
}
/**
*
* @param key
* @param entity
* @param correlationId
*/
setAuthorityMetadata(key, entity, correlationId) {
this.logger.trace("07w8n2", correlationId);
this.internalStorage.setItem(key, JSON.stringify(entity));
}
/**
* Gets the active account
*/
getActiveAccount(correlationId) {
const activeAccountKeyFilters = this.generateCacheKey(PersistentCacheKeys.ACTIVE_ACCOUNT_FILTERS);
const activeAccountValueFilters = this.browserStorage.getItem(activeAccountKeyFilters);
if (!activeAccountValueFilters) {
this.logger.trace("08gw0e", correlationId);
return null;
}
const activeAccountValueObj = this.validateAndParseJson(activeAccountValueFilters);
if (activeAccountValueObj) {
this.logger.trace("1t3ch7", correlationId);
return this.getAccountInfoFilteredBy({
homeAccountId: activeAccountValueObj.homeAccountId,
localAccountId: activeAccountValueObj.localAccountId,
tenantId: activeAccountValueObj.tenantId,
}, correlationId);
}
this.logger.trace("0me1up", correlationId);
return null;
}
/**
* Sets the active account's localAccountId in cache
* @param account
*/
setActiveAccount(account, correlationId) {
const activeAccountKey = this.generateCacheKey(PersistentCacheKeys.ACTIVE_ACCOUNT_FILTERS);
if (account) {
this.logger.verbose("0rsj80", correlationId);
const activeAccountValue = {
homeAccountId: account.homeAccountId,
localAccountId: account.localAccountId,
tenantId: account.tenantId,
};
this.setItem(activeAccountKey, JSON.stringify(activeAccountValue), correlationId);
}
else {
this.logger.verbose("1bp5z5", correlationId);
this.browserStorage.removeItem(activeAccountKey);
}
this.eventHandler.emitEvent(EventType.ACTIVE_ACCOUNT_CHANGED, correlationId);
}
/**
* fetch throttling entity from the platform cache
* @param throttlingCacheKey
* @param correlationId
*/
getThrottlingCache(throttlingCacheKey, correlationId) {
const value = this.browserStorage.getItem(throttlingCacheKey);
if (!value) {
this.logger.trace("1h4wa6", correlationId);
return null;
}
const parsedThrottlingCache = this.validateAndParseJson(value);
if (!parsedThrottlingCache ||
!isThrottlingEntity(throttlingCacheKey, parsedThrottlingCache)) {
this.logger.trace("1h4wa6", correlationId);
return null;
}
this.logger.trace("0of6n8", correlationId);
return parsedThrottlingCache;
}
/**
* set throttling entity to the platform cache
* @param throttlingCacheKey
* @param throttlingCache
*/
setThrottlingCache(throttlingCacheKey, throttlingCache, correlationId) {
this.logger.trace("0wfgh6", correlationId);
this.setItem(throttlingCacheKey, JSON.stringify(throttlingCache), correlationId);
}
/**
* Gets cache item with given key.
* @param cacheKey
* @param correlationId
* @param generateKey
*/
getTemporaryCache(cacheKey, correlationId, generateKey) {
this.logger.trace("1ordf8", correlationId);
const key = generateKey ? this.generateCacheKey(cacheKey) : cacheKey;
return this.temporaryCacheStorage.getItem(key);
}
/**
* Sets the cache item with the key and value given.
* @param key
* @param value
*/
setTemporaryCache(cacheKey, value, generateKey) {
const key = generateKey ? this.generateCacheKey(cacheKey) : cacheKey;
this.temporaryCacheStorage.setItem(key, value);
}
/**
* Removes the cache item with the given key.
* @param key
*/
removeItem(key) {
this.browserStorage.removeItem(key);
}
/**
* Removes the temporary cache item with the given key.
* @param key
*/
removeTemporaryItem(key) {
this.temporaryCacheStorage.removeItem(key);
}
/**
* Gets all keys in window.
*/
getKeys() {
return this.browserStorage.getKeys();
}
/**
* Clears all cache entries created by MSAL.
*/
clear(correlationId) {
// Removes all accounts and their credentials
this.removeAllAccounts(correlationId);
this.removeAppMetadata(correlationId);
// Remove temp storage first to make sure any cookies are cleared
this.temporaryCacheStorage.getKeys().forEach((cacheKey) => {
if (cacheKey.indexOf(PREFIX) !== -1 ||
cacheKey.indexOf(this.clientId) !== -1) {
this.removeTemporaryItem(cacheKey);
}
});
// Removes all remaining MSAL cache items
this.browserStorage.getKeys().forEach((cacheKey) => {
if (cacheKey.indexOf(PREFIX) !== -1 ||
cacheKey.indexOf(this.clientId) !== -1) {
this.browserStorage.removeItem(cacheKey);
}
});
this.internalStorage.clear();
}
/**
* Prepend msal.<client-id> to each key
* @param key
* @param addInstanceId
*/
generateCacheKey(key) {
if (StringUtils.startsWith(key, PREFIX)) {
return key;
}
return `${PREFIX}.${this.clientId}.${key}`;
}
/**
* Generate Credential Key. All changes to the key REQUIRE a schema version update.
* Cache Key: msal.<schema_version>|<home_account_id>|<environment>|<credential_type>|<client_id or familyId>|<realm>|<scopes>|<scheme>|<additional_cache_key_components_hash>
*
* @param credentialEntity
* @param hash - optional precomputed hash of additionalCacheKeyComponents
* @returns
*/
generateCredentialKey(credential, additionalCacheKeyHash) {
const familyId = (credential.credentialType ===
CredentialType.REFRESH_TOKEN &&
credential.familyId) ||
credential.clientId;
const scheme = credential.tokenType &&
credential.tokenType.toLowerCase() !==
AuthenticationScheme.BEARER.toLowerCase()
? credential.tokenType.toLowerCase()
: "";
const credentialKey = [
`${PREFIX}.${CREDENTIAL_SCHEMA_VERSION}`,
credential.homeAccountId,
credential.environment,
credential.credentialType,
familyId,
credential.realm || "",
credential.target || "",
scheme,
];
// Append precomputed component-hash segment.
if (credential.additionalCacheKeyComponents &&
Object.keys(credential.additionalCacheKeyComponents).length > 0 &&
additionalCacheKeyHash) {
credentialKey.push(additionalCacheKeyHash);
}
return credentialKey.join(CACHE_KEY_SEPARATOR).toLowerCase();
}
/**
* Cache Key: msal.<schema_version>.<home_account_id>.<environment>.<tenant_id>
* @param account
* @returns
*/
generateAccountKey(account) {
const homeTenantId = account.homeAccountId.split(".")[1];
const accountKey = [
`${PREFIX}.${ACCOUNT_SCHEMA_VERSION}`,
account.homeAccountId,
account.environment,
homeTenantId || account.tenantId || "",
];
return accountKey.join(CACHE_KEY_SEPARATOR).toLowerCase();
}
/**
* Reset all temporary cache items
* @param correlationId
*/
resetRequestCache(correlationId) {
this.logger.trace("0h0ynu", correlationId);
this.removeTemporaryItem(this.generateCacheKey(TemporaryCacheKeys.REQUEST_PARAMS));
this.removeTemporaryItem(this.generateCacheKey(TemporaryCacheKeys.VERIFIER));
this.removeTemporaryItem(this.generateCacheKey(TemporaryCacheKeys.ORIGIN_URI));
this.removeTemporaryItem(this.generateCacheKey(TemporaryCacheKeys.URL_HASH));
this.removeTemporaryItem(this.generateCacheKey(TemporaryCacheKeys.NATIVE_REQUEST));
this.setInteractionInProgress(false, undefined);
}
cacheAuthorizeRequest(authCodeRequest, correlationId, codeVerifier) {
this.logger.trace("1tzef5", correlationId);
const encodedValue = base64Encode(JSON.stringify(authCodeRequest));
this.setTemporaryCache(TemporaryCacheKeys.REQUEST_PARAMS, encodedValue, true);
if (codeVerifier) {
const encodedVerifier = base64Encode(codeVerifier);
this.setTemporaryCache(TemporaryCacheKeys.VERIFIER, encodedVerifier, true);
}
}
/**
* Gets the token exchange parameters from the cache. Throws an error if nothing is found.
* @param correlationId
*/
getCachedRequest(correlationId) {
this.logger.trace("0uen20", correlationId);
// Get token request from cache and parse as TokenExchangeParameters.
const encodedTokenRequest = this.getTemporaryCache(TemporaryCacheKeys.REQUEST_PARAMS, correlationId, true);
if (!encodedTokenRequest) {
throw createBrowserAuthError(noTokenRequestCacheError, "");
}
const encodedVerifier = this.getTemporaryCache(TemporaryCacheKeys.VERIFIER, correlationId, true);
let parsedRequest;
let verifier = "";
try {
parsedRequest = JSON.parse(base64Decode(encodedTokenRequest));
if (encodedVerifier) {
verifier = base64Decode(encodedVerifier);
}
}
catch (e) {
this.logger.errorPii(`0ewsey ${encodedTokenRequest}`, correlationId);
this.logger.error(`0tvdic ${e}`, correlationId);
throw createBrowserAuthError(unableToParseTokenRequestCacheError, "");
}
return [parsedRequest, verifier];
}
/**
* Gets cached native request for redirect flows
* @param correlationId
*/
getCachedNativeRequest() {
this.logger.trace("1yxcdm", "");
const cachedRequest = this.getTemporaryCache(TemporaryCacheKeys.NATIVE_REQUEST, "", true);
if (!cachedRequest) {
this.logger.trace("0mnxd4", "");
return null;
}
const parsedRequest = this.validateAndParseJson(cachedRequest);
if (!parsedRequest) {
this.logger.error("0rrkip", "");
return null;
}
return parsedRequest;
}
isInteractionInProgress(matchClientId) {
const clientId = this.getInteractionInProgress()?.clientId;
if (matchClientId) {
return clientId === this.clientId;
}
else {
return !!clientId;
}
}
getInteractionInProgress() {
const key = `${PREFIX}.${TemporaryCacheKeys.INTERACTION_STATUS_KEY}`;
const value = this.getTemporaryCache(key, "", false);
try {
return value ? JSON.parse(value) : null;
}
catch (e) {
// Remove interaction and other temp keys if interaction status can't be parsed
this.logger.error("0jjyys", "");
this.removeTemporaryItem(key);
this.resetRequestCache("");
clearHash(window);
return null;
}
}
setInteractionInProgress(inProgress, type = INTERACTION_TYPE.SIGNIN, allowOverride = false, correlationId = "") {
// Ensure we don't overwrite interaction in progress for a different clientId
const key = `${PREFIX}.${TemporaryCacheKeys.INTERACTION_STATUS_KEY}`;
if (inProgress) {
const existingInteraction = this.getInteractionInProgress();
if (existingInteraction) {
if (allowOverride) {
this.logger.warning(`1pmscr ${existingInteraction.clientId} ${existingInteraction.type}`, correlationId);
// Cancel any active bridge monitor from the previous interaction
cancelPendingBridgeResponse(this.logger, correlationId);
// Clear existing interaction to allow new one
this.removeTemporaryItem(key);
}
else {
throw createBrowserAuthError(interactionInProgress, "");
}
}
// Set new interaction
this.setTemporaryCache(key, JSON.stringify({ clientId: this.clientId, type }), false);
}
else if (!inProgress &&
this.getInteractionInProgress()?.clientId === this.clientId) {
this.removeTemporaryItem(key);
}
}
/**
* Builds credential entities from AuthenticationResult object and saves the resulting credentials to the cache
* @param result
* @param request
*/
async hydrateCache(result, request) {
const idTokenEntity = createIdTokenEntity(result.account.homeAccountId, result.account.environment, result.idToken, this.clientId, result.tenantId);
/**
* meta data for cache stores time in seconds from epoch
* AuthenticationResult returns expiresOn and extExpiresOn in milliseconds (as a Date object which is in ms)
* We need to map these for the cache when building tokens from AuthenticationResult
*
* The next MSAL VFuture should map these both to same value if possible
*/
const accessTokenEntity = createAccessTokenEntity(result.account.homeAccountId, result.account.environment, result.accessToken, this.clientId, result.tenantId, result.scopes.join(" "),
// Access token expiresOn stored in seconds, converting from AuthenticationResult expiresOn stored as Date
result.expiresOn
? toSecondsFromDate(result.expiresOn)
: 0, result.extExpiresOn
? toSecondsFromDate(result.extExpiresOn)
: 0, base64Decode, request.correlationId || "", undefined, // refreshOn
result.tokenType, undefined, // userAssertionHash
request.sshKid);
if (request.resource) {
accessTokenEntity.resource = request.resource;
}
const cacheRecord = {
idToken: idTokenEntity,
accessToken: accessTokenEntity,
};
return this.saveCacheRecord(cacheRecord, result.correlationId, isKmsi(extractTokenClaims(result.idToken, base64Decode, result.correlationId)), ApiId.hydrateCache);
}
/**
* saves a cache record
* @param cacheRecord {CacheRecord}
* @param storeInCache {?StoreInCache}
* @param correlationId {?string} correlation id
*/
async saveCacheRecord(cacheRecord, correlationId, kmsi, apiId, storeInCache) {
try {
await super.saveCacheRecord(cacheRecord, correlationId, kmsi, apiId, storeInCache);
}
catch (e) {
if (e instanceof CacheError &&
this.performanceClient &&
correlationId) {
try {
const tokenKeys = this.getTokenKeys();
this.performanceClient.addFields({
cacheRtCount: tokenKeys.refreshToken.length,
cacheIdCount: tokenKeys.idToken.length,
cacheAtCount: tokenKeys.accessToken.length,
}, correlationId);
}
catch (e) { }
}
throw e;
}
}
}
/**
* Returns a window storage class implementing the IWindowStorage interface that corresponds to the configured cacheLocation.
* @param cacheLocation
*/
function getStorageImplementation(clientId, cacheLocation, logger, performanceClient) {
try {
switch (cacheLocation) {
case BrowserCacheLocation.LocalStorage:
return new LocalStorage(clientId, logger, performanceClient);
case BrowserCacheLocation.SessionStorage:
return new SessionStorage();
case BrowserCacheLocation.MemoryStorage:
default:
break;
}
}
catch (e) {
logger.error(e, "");
}
return new MemoryStorage();
}
const DEFAULT_BROWSER_CACHE_MANAGER = (clientId, logger, performanceClient, eventHandler, staticAuthorityOptions, tokenBindingKeyManager = DEFAULT_TOKEN_BINDING_KEY_MANAGER) => {
const cacheOptions = {
cacheLocation: BrowserCacheLocation.MemoryStorage,
cacheRetentionDays: 5,
};
return new BrowserCacheManager(clientId, cacheOptions, DEFAULT_CRYPTO_IMPLEMENTATION, logger, performanceClient, eventHandler, staticAuthorityOptions, tokenBindingKeyManager);
};
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Returns all the accounts in the cache that match the optional filter. If no filter is provided, all accounts are returned.
* @param accountFilter - (Optional) filter to narrow down the accounts returned
* @returns Array of AccountInfo objects in cache
*/
function getAllAccounts(logger, browserStorage, isInBrowser, correlationId, accountFilter) {
logger.verbose("1yd030", correlationId);
return isInBrowser
? browserStorage.getAllAccounts(accountFilter, correlationId)
: [];
}
/**
* Returns the first account found in the cache that matches the account filter passed in.
* @param accountFilter
* @returns The first account found in the cache matching the provided filter or null if no account could be found.
*/
function getAccount(accountFilter, logger, browserStorage, correlationId) {
logger.trace("0u7b90", correlationId);
const account = browserStorage.getAccountInfoFilteredBy(accountFilter, correlationId);
if (account) {
logger.verbose("0btgll", correlationId);
return account;
}
else {
logger.verbose("0ltaj5", correlationId);
return null;
}
}
/**
* Sets the account to use as the active account. If no account is passed to the acquireToken APIs, then MSAL will use this active account.
* @param account
*/
function setActiveAccount(account, browserStorage, correlationId) {
browserStorage.setActiveAccount(account, correlationId);
}
/**
* Gets the currently active account
*/
function getActiveAccount(browserStorage, correlationId) {
return browserStorage.getActiveAccount(correlationId);
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const BROADCAST_CHANNEL_NAME = "msal.broadcast.event";
class EventHandler {
constructor(logger) {
this.eventCallbacks = new Map();
this.logger = logger || new Logger({}, name, version);
if (typeof BroadcastChannel !== "undefined") {
this.broadcastChannel = new BroadcastChannel(BROADCAST_CHANNEL_NAME);
}
this.invokeCrossTabCallbacks = this.invokeCrossTabCallbacks.bind(this);
}
/**
* Adds event callbacks to array
* @param callback - callback to be invoked when an event is raised
* @param eventTypes - list of events that this callback will be invoked for, if not provided callback will be invoked for all events
* @param callbackId - Identifier for the callback, used to locate and remove the callback when no longer required
*/
addEventCallback(callback, eventTypes, callbackId) {
if (typeof window !== "undefined") {
const id = callbackId || createGuid();
if (this.eventCallbacks.has(id)) {
this.logger.error(`1578i0 ${id}`, "");
return null;
}
this.eventCallbacks.set(id, [callback, eventTypes || []]);
this.logger.verbose(`1cnec4 ${id}`, "");
return id;
}
return null;
}
/**
* Removes callback with provided id from callback array
* @param callbackId
*/
removeEventCallback(callbackId) {
this.eventCallbacks.delete(callbackId);
this.logger.verbose(`12zotd ${callbackId}`, "");
}
/**
* Emits events by calling callback with event message
* @param eventType
* @param interactionType
* @param payload
* @param error
*/
emitEvent(eventType, correlationId, interactionType, payload, error) {
const message = {
eventType: eventType,
interactionType: interactionType || null,
payload: payload || null,
error: error || null,
correlationId: correlationId,
timestamp: Date.now(),
};
switch (eventType) {
case EventType.LOGIN_SUCCESS:
case EventType.LOGOUT_SUCCESS:
case EventType.ACTIVE_ACCOUNT_CHANGED:
// Send event to other open tabs / MSAL instances on same domain
this.broadcastChannel?.postMessage(message);
}
// Emit event to callbacks registered in this instance
this.invokeCallbacks(message);
}
/**
* Invoke registered callbacks
* @param message
*/
invokeCallbacks(message) {
this.eventCallbacks.forEach(([callback, eventTypes], callbackId) => {
if (eventTypes.length === 0 ||
eventTypes.includes(message.eventType)) {
this.logger.verbose(`15jpwk ${callbackId} ${message.eventType}`, "");
callback.apply(null, [message]);
}
});
}
/**
* Wrapper around invokeCallbacks to handle broadcast events received from other tabs/instances
* @param event
*/
invokeCrossTabCallbacks(event) {
const message = event.data;
this.invokeCallbacks(message);
}
/**
* Listen for events broadcasted from other tabs/instances
*/
subscribeCrossTab() {
this.broadcastChannel?.addEventListener("message", this.invokeCrossTabCallbacks);
}
/**
* Unsubscribe from broadcast events
*/
unsubscribeCrossTab() {
this.broadcastChannel?.removeEventListener("message", this.invokeCrossTabCallbacks);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* postMessage envelope type used to relay an auth response from a popup-relay
* page (see `runPopupRelay`) back to the embedded frame that opened it. See
* {@link BrowserAuthOptions.popupRelayUri}.
*
* Kept dependency-free so both the relay-page entry (`./index.js`) and the
* client-side helpers (`./relayClient.js`) can import it without either bundle
* pulling in the other's dependencies.
*
* @internal
*/
const POPUP_RELAY_RESPONSE_TYPE = "msal:popup-relay-response:v1";
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Builds the URL of the popup-relay page to open. The action the relay page
* must perform (GET navigation or POST form) is carried in the page's hash
* (client-side only, never sent to a server), keyed by the per-request
* library-state `id` so the relay page can listen on the right BroadcastChannel
* and echo the id back. The relay URI is resolved against the app origin, so it
* must be same-origin as the embedded frame. See `runPopupRelay`.
*
* @internal
*/
function buildPopupRelayUrl(popupRelayUri, id, action, correlationId) {
const req = { id, ...action };
const target = new URL(popupRelayUri, window.location.origin);
/*
* The relay page must be same-origin as the embedded frame: the response is
* relayed back via postMessage and only accepted from this origin, and a
* cross-origin page would also receive the relayed /authorize request. Fail
* fast with a clear error instead of silently relaying to (and timing out
* against) the wrong origin.
*/
if (target.origin !== window.location.origin) {
throw createBrowserAuthError(popupRelayUnsupportedFlow, correlationId, "popup_relay_cross_origin");
}
const hashParams = new URLSearchParams();
hashParams.set("req", JSON.stringify(req));
target.hash = hashParams.toString();
return target.toString();
}
/**
* Waits for the popup-relay page to relay the raw auth response back to the
* embedded frame via postMessage. Used in place of `waitForBridgeResponse`
* when `auth.popupRelayUri` is configured, because third-party storage
* partitioning blocks the BroadcastChannel the redirect bridge uses from
* reaching the embedded frame.
*
* The response is accepted only from the popup window we opened, on our own
* origin (the relay page is same-origin as the embedded frame), and only when
* it carries the matching per-request library-state id.
*
* @internal
*/
async function waitForPopupRelayResponse(timeoutMs, logger, request, popupWindow, performanceClient) {
return new Promise((resolve, reject) => {
const correlationId = request.correlationId;
logger.verbose("1d05g9", correlationId);
performanceClient.addFields({ redirectBridgeTimeoutMs: timeoutMs }, correlationId);
const { libraryState } = parseRequestState(base64Decode, request.state || "", correlationId);
const expectedId = libraryState.id;
const expectedOrigin = window.location.origin;
let settled = false;
const cleanup = () => {
window.removeEventListener("message", onMessage);
clearTimeout(timeoutId);
clearInterval(closedPoll);
};
const onMessage = (event) => {
if (event.origin !== expectedOrigin ||
event.source !== popupWindow) {
return;
}
const data = event.data;
if (!data ||
data.type !== POPUP_RELAY_RESPONSE_TYPE ||
data.id !== expectedId) {
return;
}
if (settled) {
return;
}
settled = true;
cleanup();
if (data.error) {
reject(createBrowserAuthError(data.error, correlationId));
}
else if (data.payload) {
resolve(data.payload);
}
else {
reject(createBrowserAuthError(redirectBridgeEmptyResponse, correlationId));
}
};
window.addEventListener("message", onMessage);
const timeoutId = window.setTimeout(() => {
if (settled) {
return;
}
settled = true;
cleanup();
reject(createBrowserAuthError(timedOut, correlationId, "popup_relay_timeout"));
}, timeoutMs);
const closedPoll = window.setInterval(() => {
if (popupWindow.closed && !settled) {
settled = true;
cleanup();
reject(createBrowserAuthError(userCancelled, correlationId));
}
}, 500);
});
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Extracts the BrowserStateObject from the state string.
* @param browserCrypto
* @param state
*/
function extractBrowserRequestState(browserCrypto, state, correlationId) {
if (!state) {
return null;
}
try {
const requestStateObj = parseRequestState(browserCrypto.base64Decode, state, correlationId);
return requestStateObj.libraryState.meta;
}
catch (e) {
throw createClientAuthError(invalidState, correlationId);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
function deserializeResponse(responseString, responseLocation, logger, correlationId) {
// Deserialize hash fragment response parameters.
const serverParams = getDeserializedResponse(responseString);
if (!serverParams) {
if (!stripLeadingHashOrQuery(responseString)) {
// Hash or Query string is empty
logger.error(`18h0l1 ${responseLocation} ${responseLocation}`, correlationId);
throw createBrowserAuthError(hashEmptyError, correlationId);
}
else {
logger.error(`13pl0s ${responseLocation} ${responseLocation}`, correlationId);
logger.errorPii(`1097vx ${responseLocation} ${responseString}`, correlationId);
throw createBrowserAuthError(hashDoesNotContainKnownProperties, correlationId);
}
}
return serverParams;
}
/**
* Returns the interaction type that the response object belongs to
*/
function validateInteractionType(response, browserCrypto, interactionType, correlationId) {
if (!response.state) {
throw createBrowserAuthError(noStateInHash, correlationId);
}
const platformStateObj = extractBrowserRequestState(browserCrypto, response.state, correlationId);
if (!platformStateObj) {
throw createBrowserAuthError(unableToParseState, correlationId);
}
if (platformStateObj.interactionType !== interactionType) {
throw createBrowserAuthError(stateInteractionTypeMismatch, correlationId);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Abstract class which defines operations for a browser interaction handling class.
*/
class InteractionHandler {
constructor(authCodeModule, storageImpl, authCodeRequest, logger, performanceClient) {
this.authModule = authCodeModule;
this.browserStorage = storageImpl;
this.authCodeRequest = authCodeRequest;
this.logger = logger;
this.performanceClient = performanceClient;
}
/**
* Function to handle response parameters from hash.
* @param locationHash
*/
async handleCodeResponse(response, request, apiId) {
let authCodeResponse;
try {
authCodeResponse = getAuthorizationCodePayload(response, request.state, request.correlationId);
}
catch (e) {
if (e instanceof ServerError &&
e.subError === userCancelled) {
// Translate server error caused by user closing native prompt to corresponding first class MSAL error
throw createBrowserAuthError(userCancelled, request.correlationId);
}
else {
throw e;
}
}
return invokeAsync(this.handleCodeResponseFromServer.bind(this), HandleCodeResponseFromServer, this.logger, this.performanceClient, request.correlationId)(authCodeResponse, request, apiId);
}
/**
* Process auth code response from AAD
* @param authCodeResponse
* @param request
* @param validateNonce
* @returns
*/
async handleCodeResponseFromServer(authCodeResponse, request, apiId, validateNonce = true) {
this.logger.trace("0mf2hb", request.correlationId);
// Assign code to request
this.authCodeRequest.code = authCodeResponse.code;
// Nonce validation not needed when redirect not involved (e.g. hybrid spa, renewing token via rt)
if (validateNonce) {
// TODO: Assigning "response nonce" to "request nonce" is confusing. Refactor the function doing validation to accept request nonce directly
authCodeResponse.nonce = request.nonce || undefined;
}
authCodeResponse.state = request.state;
// Add CCS parameters if available
if (authCodeResponse.client_info) {
this.authCodeRequest.clientInfo = authCodeResponse.client_info;
}
else {
const ccsCred = this.createCcsCredentials(request);
if (ccsCred) {
this.authCodeRequest.ccsCredential = ccsCred;
}
}
// Acquire token with retrieved code.
const tokenResponse = (await invokeAsync(this.authModule.acquireToken.bind(this.authModule), AuthClientAcquireToken, this.logger, this.performanceClient, request.correlationId)(this.authCodeRequest, apiId, authCodeResponse));
return tokenResponse;
}
/**
* Build ccs creds if available
*/
createCcsCredentials(request) {
if (request.account) {
return {
credential: request.account.homeAccountId,
type: CcsCredentialType.HOME_ACCOUNT_ID,
};
}
else if (request.loginHint) {
return {
credential: request.loginHint,
type: CcsCredentialType.UPN,
};
}
return null;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Token types supported by the platform broker request contract.
*/
const PlatformAuthTokenType = {
DPOP_WITH_PROOF: "dpop+proof",
};
const PROOF_OF_POSSESSION_TOKEN_TYPES = [
AuthenticationScheme.POP,
AuthenticationScheme.DPOP,
PlatformAuthTokenType.DPOP_WITH_PROOF,
];
/**
* Returns whether a platform broker token type requires proof request metadata.
*/
function isProofOfPossessionTokenType(tokenType) {
return (tokenType !== undefined &&
PROOF_OF_POSSESSION_TOKEN_TYPES.includes(tokenType));
}
/**
* Adds canonical proof request fields to the broker no-cache property bag.
*/
function createPlatformAuthExtraParametersNoCache(extraParametersNoCache, isProofOfPossessionRequest, resourceRequestMethod, resourceRequestUri, dpopNonce) {
if (!isProofOfPossessionRequest) {
return extraParametersNoCache;
}
return {
...extraParametersNoCache,
...(resourceRequestMethod && {
pop_method: resourceRequestMethod,
}),
...(resourceRequestUri && {
pop_url: resourceRequestUri,
}),
...(dpopNonce && {
pop_nonce: dpopNonce,
}),
};
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const contentError = "ContentError";
const pageException = "PageException";
const userSwitch = "user_switch";
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
// Status Codes that can be thrown by WAM
const USER_INTERACTION_REQUIRED = "USER_INTERACTION_REQUIRED";
const USER_CANCEL = "USER_CANCEL";
const NO_NETWORK = "NO_NETWORK";
const DISABLED = "DISABLED";
const ACCOUNT_UNAVAILABLE = "ACCOUNT_UNAVAILABLE";
const UI_NOT_ALLOWED = "UI_NOT_ALLOWED";
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const INVALID_METHOD_ERROR = -2147186943;
class NativeAuthError extends AuthError {
constructor(errorCode, correlationId, description, ext) {
super(errorCode, correlationId, description || getDefaultErrorMessage(errorCode));
Object.setPrototypeOf(this, NativeAuthError.prototype);
this.name = "NativeAuthError";
this.ext = ext;
}
}
/**
* These errors should result in a fallback to the 'standard' browser based auth flow.
*/
function isFatalNativeAuthError(error) {
if (error.ext &&
error.ext.status &&
error.ext.status === DISABLED) {
return true;
}
if (error.ext &&
error.ext.error &&
error.ext.error === INVALID_METHOD_ERROR) {
return true;
}
switch (error.errorCode) {
case contentError:
case pageException:
return true;
default:
return false;
}
}
/**
* Create the appropriate error object based on the WAM status code.
* @param code
* @param description
* @param ext
* @returns
*/
function createNativeAuthError(code, correlationId, description, ext) {
let error;
if (ext && ext.status) {
switch (ext.status) {
case ACCOUNT_UNAVAILABLE:
error = createInteractionRequiredAuthError(nativeAccountUnavailable, correlationId, getDefaultErrorMessage(code));
break;
case USER_INTERACTION_REQUIRED:
error = new InteractionRequiredAuthError(code, correlationId, description);
break;
case USER_CANCEL:
error = createBrowserAuthError(userCancelled, correlationId);
break;
case NO_NETWORK:
error = createBrowserAuthError(noNetworkConnectivity, correlationId);
break;
case UI_NOT_ALLOWED:
error = createInteractionRequiredAuthError(uiNotAllowed, correlationId);
break;
default:
error = new NativeAuthError(code, correlationId, description, ext);
}
return error;
}
error = new NativeAuthError(code, correlationId, description, ext);
return error;
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class SilentCacheClient extends StandardInteractionClient {
/**
* Returns unexpired tokens from the cache, if available
* @param silentRequest
*/
async acquireToken(silentRequest) {
// Telemetry manager only used to increment cacheHits here
const serverTelemetryManager = initializeServerTelemetryManager(ApiId.acquireTokenSilent_silentFlow, this.config.auth.clientId, this.correlationId, this.browserStorage, this.logger, undefined, this.config.system.serverTelemetryEnabled);
const clientConfig = await invokeAsync(this.getClientConfiguration.bind(this), StandardInteractionClientGetClientConfiguration, this.logger, this.performanceClient, this.correlationId)({
serverTelemetryManager,
requestAuthority: silentRequest.authority,
requestAzureCloudOptions: silentRequest.azureCloudOptions,
account: silentRequest.account,
});
const silentAuthClient = new SilentFlowClient(clientConfig, this.performanceClient);
this.logger.verbose("0wa871", this.correlationId);
try {
const response = await invokeAsync(silentAuthClient.acquireCachedToken.bind(silentAuthClient), SilentFlowClientAcquireCachedToken, this.logger, this.performanceClient, silentRequest.correlationId)(silentRequest);
const authResponse = response[0];
this.performanceClient.addFields({
fromCache: true,
}, silentRequest.correlationId);
return authResponse;
}
catch (error) {
if (error instanceof BrowserAuthError &&
error.errorCode === cryptoKeyNotFound) {
this.logger.verbose("06wena", this.correlationId);
}
throw error;
}
}
/**
* API to silenty clear the browser cache.
* @param logoutRequest
*/
logout(logoutRequest) {
this.logger.verbose("1rkurh", this.correlationId);
const validLogoutRequest = this.initializeLogoutRequest(logoutRequest);
return clearCacheOnLogout(this.browserStorage, this.browserCrypto, this.logger, this.correlationId, validLogoutRequest.account);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class PlatformAuthInteractionClient extends BaseInteractionClient {
constructor(config, browserStorage, browserCrypto, logger, eventHandler, navigationClient, apiId, performanceClient, provider, accountId, nativeStorageImpl, correlationId, tokenBindingKeyManager) {
super(config, browserStorage, browserCrypto, logger, eventHandler, navigationClient, performanceClient, correlationId, provider, tokenBindingKeyManager);
this.apiId = apiId;
this.accountId = accountId;
this.platformAuthProvider = provider;
this.nativeStorageManager = nativeStorageImpl;
this.silentCacheClient = new SilentCacheClient(config, this.nativeStorageManager, browserCrypto, logger, eventHandler, navigationClient, performanceClient, correlationId, provider, this.tokenBindingKeyManager);
const extensionName = this.platformAuthProvider.getExtensionName();
this.skus = ServerTelemetryManager.makeExtraSkuString({
libraryName: BrowserConstants.MSAL_SKU,
libraryVersion: version,
extensionName: extensionName,
extensionVersion: this.platformAuthProvider.getExtensionVersion(),
});
}
/**
* Adds SKUs to request extra query parameters
* @param request {PlatformAuthRequest}
* @private
*/
addRequestSKUs(request) {
request.extraParameters = {
...request.extraParameters,
[X_CLIENT_EXTRA_SKU]: this.skus,
};
}
/**
* Acquire token from native platform via browser extension
* @param request
*/
async acquireToken(request, cacheLookupPolicy) {
this.logger.trace("03qeos", this.correlationId);
// start the perf measurement
const nativeATMeasurement = this.performanceClient.startMeasurement(NativeInteractionClientAcquireToken, this.correlationId);
const reqTimestamp = nowSeconds();
const serverTelemetryManager = initializeServerTelemetryManager(this.apiId, this.config.auth.clientId, this.correlationId, this.browserStorage, this.logger, undefined, this.config.system.serverTelemetryEnabled);
// initialize native request (statically builds the request; does not contact the broker)
let nativeRequest;
try {
nativeRequest = await invokeAsync(this.initializePlatformRequest.bind(this), PlatformAuthInteractionClientInitializeRequest, this.logger, this.performanceClient, this.correlationId)(request);
}
catch (e) {
/*
* Request initialization (e.g. PoP token generation or authority
* resolution) failed before the broker was contacted, so end the
* measurement here to avoid an orphaned sub-measurement.
* Broker was never engaged, so this was not a native broker outcome.
*/
nativeATMeasurement.add({
isNativeBroker: false,
});
nativeATMeasurement.end({
success: false,
}, e);
throw e;
}
// check if the tokens can be retrieved from internal cache
try {
const result = await this.acquireTokensFromCache(this.accountId, nativeRequest);
// Served from the native internal cache; token did not come directly from the broker
nativeATMeasurement.add({
isNativeBroker: false,
});
nativeATMeasurement.end({
success: true,
fromCache: true,
});
return result;
}
catch (e) {
if (cacheLookupPolicy === CacheLookupPolicy.AccessToken) {
this.logger.info("0eitbc", this.correlationId);
nativeATMeasurement.add({
isNativeBroker: false,
});
nativeATMeasurement.end({
success: false,
});
throw e;
}
// continue with a native call for any and all errors
this.logger.info("0957j1", this.correlationId);
}
// dispatch the request to the broker
try {
const validatedResponse = await this.platformAuthProvider.sendMessage(nativeRequest);
const result = await invokeAsync(this.handleNativeResponse.bind(this), PlatformAuthHandleNativeResponse, this.logger, this.performanceClient, this.correlationId)(validatedResponse, nativeRequest, reqTimestamp, request.storeInCache);
nativeATMeasurement.end({
success: true,
requestId: result.requestId,
});
serverTelemetryManager.clearNativeBrokerErrorCode();
return result;
}
catch (e) {
if (e instanceof NativeAuthError) {
serverTelemetryManager.setNativeBrokerErrorCode(e.errorCode);
}
nativeATMeasurement.end({
success: false,
}, e);
this.setBrokerErrorTelemetry(e);
throw e;
}
}
/**
* Records platform-broker error telemetry on the root event for the current
* correlationId. `isNativeBroker` is set optimistically to true because the
* broker was engaged; when the caller subsequently falls back to a web flow
* that succeeds, the root success measurement overrides it to false via
* `result.fromPlatformBroker`. Terminal broker errors (no fallback) retain
* true. `brokerErrorName`/`brokerErrorCode` are recorded when the error is an `AuthError`.
* @param error error thrown by the broker interaction
*/
setBrokerErrorTelemetry(error) {
if (error instanceof AuthError) {
this.performanceClient.addFields({
isNativeBroker: true,
brokerErrorName: error.name,
brokerErrorCode: error.errorCode,
}, this.correlationId);
}
}
/**
* Creates silent flow request
* @param request
* @param cachedAccount
* @returns CommonSilentFlowRequest
*/
createSilentCacheRequest(request, cachedAccount) {
const silentRequest = {
authority: request.authority,
correlationId: this.correlationId,
scopes: ScopeSet.fromString(request.scope, this.correlationId).asArray(),
account: cachedAccount,
forceRefresh: false,
resource: request.extraParameters?.resource,
};
// Preserve FMI partition semantics for silent cache filtering.
if (request.attributeTokens) {
silentRequest.attributeTokens = request.attributeTokens.split(" ");
}
return silentRequest;
}
/**
* Fetches the tokens from the cache if un-expired
* @param nativeAccountId
* @param request
* @returns authenticationResult
*/
async acquireTokensFromCache(nativeAccountId, request) {
if (!nativeAccountId) {
this.logger.warning("1ndf3e", this.correlationId);
throw createClientAuthError(noAccountFound, this.correlationId);
}
// fetch the account from browser cache
const account = this.browserStorage.getBaseAccountInfo({
nativeAccountId,
}, this.correlationId);
if (!account) {
throw createClientAuthError(noAccountFound, this.correlationId);
}
// leverage silent flow for cached tokens retrieval
try {
const silentRequest = this.createSilentCacheRequest(request, account);
const result = await this.silentCacheClient.acquireToken(silentRequest);
const idToken = this.browserStorage.getIdToken(account, this.correlationId, this.browserStorage.getTokenKeys(), account.tenantId);
const idTokenClaims = extractTokenClaims(idToken?.secret || "", base64Decode, this.correlationId);
const fullAccount = updateAccountTenantProfileData(account, undefined, // tenantProfile optional
idTokenClaims, idToken?.secret);
return {
...result,
idToken: idToken?.secret || "",
idTokenClaims: idTokenClaims,
account: fullAccount,
};
}
catch (e) {
throw e;
}
}
/**
* Acquires a token from native platform then redirects to the redirectUri instead of returning the response
* @param {RedirectRequest} request
* @param {InProgressPerformanceEvent} rootMeasurement
* @param {HandleRedirectPromiseOptions} options
*/
async acquireTokenRedirect(request, rootMeasurement, options) {
this.logger.trace("0luikq", this.correlationId);
const nativeRequest = await invokeAsync(this.initializePlatformRequest.bind(this), PlatformAuthInteractionClientInitializeRequest, this.logger, this.performanceClient, this.correlationId)(request);
const navigateToLoginRequestUrl = options?.navigateToLoginRequestUrl ?? true;
try {
await this.platformAuthProvider.sendMessage(nativeRequest);
}
catch (e) {
// Only throw fatal errors here to allow application to fallback to regular redirect. Otherwise proceed and the error will be thrown in handleRedirectPromise
if (e instanceof NativeAuthError) {
const serverTelemetryManager = initializeServerTelemetryManager(this.apiId, this.config.auth.clientId, this.correlationId, this.browserStorage, this.logger, undefined, this.config.system.serverTelemetryEnabled);
serverTelemetryManager.setNativeBrokerErrorCode(e.errorCode);
if (isFatalNativeAuthError(e)) {
/*
* Fatal error on redirect initiate always falls back to a
* regular web redirect, so this request did not complete
* natively. Token telemetry for the eventual outcome lands
* in handleRedirectPromise (phase 2).
*/
this.setBrokerErrorTelemetry(e);
throw e;
}
}
}
this.browserStorage.setTemporaryCache(TemporaryCacheKeys.NATIVE_REQUEST, JSON.stringify({
...nativeRequest,
storeInCache: request.storeInCache,
}), true);
const navigationOptions = {
apiId: ApiId.acquireTokenRedirect,
timeout: this.config.system.redirectNavigationTimeout,
noHistory: false,
};
const redirectUri = navigateToLoginRequestUrl
? UrlString.getAbsoluteUrl(request.redirectStartPage || window.location.href, getCurrentUri(), this.correlationId)
: getRedirectUri(request.redirectUri, this.config.auth.redirectUri, this.logger, this.correlationId);
rootMeasurement.end({ success: true });
await this.navigationClient.navigateExternal(redirectUri, navigationOptions); // Need to treat this as external to ensure handleRedirectPromise is run again
}
/**
* If the previous page called native platform for a token using redirect APIs, send the same request again and return the response
* @param performanceClient {IPerformanceClient?}
* @param correlationId {string?} correlation identifier
*/
async handleRedirectPromise() {
this.logger.trace("1c5lhw", this.correlationId);
if (!this.browserStorage.isInteractionInProgress(true)) {
this.logger.info("0le6uv", this.correlationId);
return null;
}
// remove prompt from the request to prevent WAM from prompting twice
const cachedRequest = this.browserStorage.getCachedNativeRequest();
if (!cachedRequest) {
this.logger.verbose("0a6zjb", this.correlationId);
this.performanceClient?.addFields({
errorCode: "no_cached_request",
}, this.correlationId);
return null;
}
/*
* storeInCache is a client-side cache directive persisted alongside the cached
* request (not a broker-contract parameter), so extract it here before resending.
*/
const { prompt, storeInCache, ...request } = cachedRequest;
if (prompt) {
this.logger.verbose("0ac34v", this.correlationId);
}
this.browserStorage.removeItem(this.browserStorage.generateCacheKey(TemporaryCacheKeys.NATIVE_REQUEST));
const reqTimestamp = nowSeconds();
try {
this.logger.verbose("003x5a", this.correlationId);
const response = await this.platformAuthProvider.sendMessage(request);
const authResult = await invokeAsync(this.handleNativeResponse.bind(this), PlatformAuthHandleNativeResponse, this.logger, this.performanceClient, this.correlationId)(response, request, reqTimestamp, storeInCache);
const serverTelemetryManager = initializeServerTelemetryManager(this.apiId, this.config.auth.clientId, this.correlationId, this.browserStorage, this.logger, undefined, this.config.system.serverTelemetryEnabled);
serverTelemetryManager.clearNativeBrokerErrorCode();
return authResult;
}
catch (e) {
this.setBrokerErrorTelemetry(e);
throw e;
}
}
/**
* Logout from native platform via browser extension
* @param request
*/
logout() {
this.logger.trace("0u2sjm", this.correlationId);
return Promise.reject("Logout not implemented yet");
}
/**
* Transform response from native platform into AuthenticationResult object which will be returned to the end user
* @param response
* @param request
* @param reqTimestamp
*/
async handleNativeResponse(response, request, reqTimestamp, storeInCache) {
this.logger.trace("1bojln", this.correlationId);
// generate identifiers
const idTokenClaims = extractTokenClaims(response.id_token, base64Decode, this.correlationId);
const homeAccountIdentifier = this.createHomeAccountIdentifier(response, idTokenClaims);
const cachedhomeAccountId = this.browserStorage.getAccountInfoFilteredBy({
nativeAccountId: request.accountId,
}, this.correlationId)?.homeAccountId;
// add exception for double brokering, please note this is temporary and will be fortified in future
if (request.extraParameters?.child_client_id &&
response.account.id !== request.accountId) {
this.logger.info("1ub1in", this.correlationId);
}
else if (homeAccountIdentifier !== cachedhomeAccountId &&
response.account.id !== request.accountId) {
// User switch in native broker prompt is not supported. All users must first sign in through web flow to ensure server state is in sync
throw createNativeAuthError(userSwitch, this.correlationId);
}
// Get the preferred_cache domain for the given authority
const authority = await getDiscoveredAuthority(this.config, this.correlationId, this.performanceClient, this.browserStorage, this.logger, request.authority);
const baseAccount = buildAccountToCache(this.browserStorage, authority, homeAccountIdentifier, base64Decode, this.correlationId, idTokenClaims, response.client_info, authority.getPreferredCache(), // environment
idTokenClaims.tid, undefined, // auth code payload
response.account.id, this.logger, this.performanceClient);
// Ensure expires_in is in number format
response.expires_in = Number(response.expires_in);
// generate authenticationResult
const result = await invokeAsync(this.generateAuthenticationResult.bind(this), NativeGenerateAuthResult, this.logger, this.performanceClient, this.correlationId)(response, request, idTokenClaims, baseAccount, authority.canonicalAuthority, reqTimestamp);
// cache accounts and tokens in the appropriate storage
await invokeAsync(this.cacheAccount.bind(this), PlatformAuthCacheAccount, this.logger, this.performanceClient, this.correlationId)(baseAccount, isKmsi(idTokenClaims));
await invokeAsync(this.cacheNativeTokens.bind(this), PlatformAuthCacheNativeTokens, this.logger, this.performanceClient, this.correlationId)(response, request, homeAccountIdentifier, idTokenClaims, result.tenantId, reqTimestamp, authority.getPreferredCache(), // environment
storeInCache);
return result;
}
/**
* creates an homeAccountIdentifier for the account
* @param response
* @param idTokenObj
* @returns
*/
createHomeAccountIdentifier(response, idTokenClaims) {
// Save account in browser storage
const homeAccountIdentifier = generateHomeAccountId(response.client_info || "", AuthorityType.Default, this.logger, this.browserCrypto, this.correlationId, idTokenClaims);
return homeAccountIdentifier;
}
/**
* Helper to generate scopes
* @param response
* @param request
* @returns
*/
generateScopes(requestScopes, responseScopes) {
return responseScopes
? ScopeSet.fromString(responseScopes, this.correlationId)
: ScopeSet.fromString(requestScopes, this.correlationId);
}
/**
* If PoP token is requesred, records the PoP token if returned from the WAM, else generates one in the browser
* @param request
* @param response
*/
async generatePopAccessToken(response, request) {
if (request.tokenType === AuthenticationScheme.POP &&
request.signPopToken) {
/**
* This code prioritizes SHR returned from the native layer. In case of error/SHR not calculated from WAM and the AT
* is still received, SHR is calculated locally
*/
// Check if native layer returned an SHR token
if (response.shr) {
this.logger.trace("0coqhu", this.correlationId);
return response.shr;
}
// Generate SHR in msal js if WAM does not compute it when POP is enabled
const popTokenGenerator = new PopTokenGenerator(this.browserCrypto, this.tokenBindingKeyManager, this.performanceClient);
const shrParameters = {
resourceRequestMethod: request.resourceRequestMethod,
resourceRequestUri: request.resourceRequestUri,
shrClaims: request.shrClaims,
shrNonce: request.shrNonce,
correlationId: this.correlationId,
};
/**
* KeyID must be present in the native request from when the PoP key was generated in order for
* PopTokenGenerator to query the full key for signing
*/
if (!request.keyId) {
throw createClientAuthError(keyIdMissing, this.correlationId);
}
return popTokenGenerator.signPopToken(response.access_token, request.keyId, shrParameters);
}
else {
return response.access_token;
}
}
/**
* Generates authentication result
* @param response
* @param request
* @param idTokenObj
* @param accountEntity
* @param authority
* @param reqTimestamp
* @returns
*/
async generateAuthenticationResult(response, request, idTokenClaims, accountEntity, authority, reqTimestamp) {
// Add Native Broker fields to Telemetry
const mats = this.addTelemetryFromNativeResponse(response.properties.MATS);
// If scopes not returned in server response, use request scopes
const responseScopes = this.generateScopes(request.scope, response.scope);
const accountProperties = response.account.properties || {};
const uid = accountProperties["UID"] ||
idTokenClaims.oid ||
idTokenClaims.sub ||
"";
const tid = accountProperties["TenantId"] || idTokenClaims.tid || "";
const accountInfo = updateAccountTenantProfileData(getAccountInfo(accountEntity), undefined, // tenantProfile optional
idTokenClaims, response.id_token);
/**
* In pairwise broker flows, this check prevents the broker's native account id
* from being returned over the embedded app's account id.
*/
if (accountInfo.nativeAccountId !== response.account.id) {
accountInfo.nativeAccountId = response.account.id;
// Also update the matching tenant profile (source of truth)
const targetTenantId = tid || accountInfo.tenantId;
const tenantProfile = accountInfo.tenantProfiles?.get(targetTenantId);
if (tenantProfile) {
tenantProfile.nativeAccountId = response.account.id;
}
}
// generate PoP token as needed
const responseAccessToken = await this.generatePopAccessToken(response, request);
const tokenType = request.tokenType === AuthenticationScheme.POP
? AuthenticationScheme.POP
: AuthenticationScheme.BEARER;
const result = {
authority: authority,
uniqueId: uid,
tenantId: tid,
scopes: responseScopes.asArray(),
account: accountInfo,
idToken: response.id_token,
idTokenClaims: idTokenClaims,
accessToken: responseAccessToken,
fromCache: mats ? this.isResponseFromCache(mats) : false,
// Request timestamp and NativeResponse expires_in are in seconds, converting to Date for AuthenticationResult
expiresOn: toDateFromSeconds(reqTimestamp + response.expires_in),
tokenType: tokenType,
correlationId: this.correlationId,
state: response.state,
fromPlatformBroker: true,
...(request.extraParameters?.resource && {
resource: request.extraParameters.resource,
}),
};
return result;
}
/**
* cache the account entity in browser storage
* @param accountEntity
*/
async cacheAccount(accountEntity, kmsi) {
// Store the account info and hence `nativeAccountId` in browser cache
await this.browserStorage.setAccount(accountEntity, this.correlationId, kmsi, this.apiId);
// Remove any existing cached tokens for this account in browser storage
this.browserStorage.removeAccountContext(getAccountInfo(accountEntity), this.correlationId);
}
/**
* Stores the access_token and id_token in inmemory storage
* @param response
* @param request
* @param homeAccountIdentifier
* @param idTokenObj
* @param responseAccessToken
* @param tenantId
* @param reqTimestamp
*/
async cacheNativeTokens(response, request, homeAccountIdentifier, idTokenClaims, tenantId, reqTimestamp, environment, storeInCache) {
const cachedIdToken = createIdTokenEntity(homeAccountIdentifier, environment, response.id_token || "", request.clientId, idTokenClaims.tid || "");
// cache accessToken in inmemory storage
const expiresIn = request.tokenType === AuthenticationScheme.POP
? SHR_NONCE_VALIDITY
: (typeof response.expires_in === "string"
? parseInt(response.expires_in, 10)
: response.expires_in) || 0;
const tokenExpirationSeconds = reqTimestamp + expiresIn;
const responseScopes = this.generateScopes(response.scope, request.scope);
const additionalCacheKeyComponents = request.attributeTokens
? {
attribute_tokens: request.attributeTokens,
}
: undefined;
const cachedAccessToken = createAccessTokenEntity(homeAccountIdentifier, environment, response.access_token, request.clientId, idTokenClaims.tid || tenantId, responseScopes.printScopes(), tokenExpirationSeconds, 0, base64Decode, request.correlationId, undefined, request.tokenType, undefined, request.keyId, additionalCacheKeyComponents);
if (request.extraParameters?.resource) {
cachedAccessToken.resource = request.extraParameters.resource;
}
// save idtoken credential in configured browser storage
if (!!cachedIdToken && storeInCache?.idToken !== false) {
await this.browserStorage.setIdTokenCredential(cachedIdToken, this.correlationId, isKmsi(idTokenClaims));
}
// save access token credential in memory storage
const nativeCacheRecord = {
accessToken: cachedAccessToken,
};
return this.nativeStorageManager.saveCacheRecord(nativeCacheRecord, this.correlationId, isKmsi(idTokenClaims), this.apiId, storeInCache);
}
getExpiresInValue(tokenType, expiresIn) {
return tokenType === AuthenticationScheme.POP
? SHR_NONCE_VALIDITY
: (typeof expiresIn === "string"
? parseInt(expiresIn, 10)
: expiresIn) || 0;
}
addTelemetryFromNativeResponse(matsResponse) {
const mats = this.getMATSFromResponse(matsResponse);
if (!mats) {
return null;
}
this.performanceClient.addFields({
extensionId: this.platformAuthProvider.getExtensionId(),
extensionVersion: this.platformAuthProvider.getExtensionVersion(),
matsBrokerVersion: mats.broker_version,
matsAccountJoinOnStart: mats.account_join_on_start,
matsAccountJoinOnEnd: mats.account_join_on_end,
matsDeviceJoin: mats.device_join,
matsPromptBehavior: mats.prompt_behavior,
matsApiErrorCode: mats.api_error_code,
matsUiVisible: mats.ui_visible,
matsSilentCode: mats.silent_code,
matsSilentBiSubCode: mats.silent_bi_sub_code,
matsSilentMessage: mats.silent_message,
matsSilentStatus: mats.silent_status,
matsHttpStatus: mats.http_status,
matsHttpEventCount: mats.http_event_count,
}, this.correlationId);
return mats;
}
/**
* Gets MATS telemetry from native response
* @param response
* @returns
*/
getMATSFromResponse(matsResponse) {
if (matsResponse) {
try {
return JSON.parse(matsResponse);
}
catch (e) {
this.logger.error("0b3l57", this.correlationId);
}
}
return null;
}
/**
* Returns whether or not response came from native cache
* @param response
* @returns
*/
isResponseFromCache(mats) {
if (typeof mats.is_cached === "undefined") {
this.logger.verbose("1okqev", this.correlationId);
return false;
}
return !!mats.is_cached;
}
/**
* Translates developer provided request object into NativeRequest object
* @param request
*/
async initializePlatformRequest(request) {
this.logger.trace("1xdm2a", this.correlationId);
const canonicalAuthority = await this.getCanonicalAuthority(request);
// ignore config claims if skipBrokerClaims is set to true and this is a brokered authentication flow
const configClaims = request.skipBrokerClaims && !!request.embeddedClientId
? undefined
: this.config.auth.clientCapabilities;
/*
* scopes are expected to be received by the native broker as "scope" and will be added to the request below. Other properties that should be dropped from the request to the native broker can be included in the object destructuring here.
* attributeTokens is destructured out because PlatformAuthRequest represents it as a pre-serialized string, not the caller-provided Array<string>.
*/
const { scopes, claims, extraParametersNoCache, dpopNonce } = request;
const scopeSet = new ScopeSet([...(scopes || []), ...OIDC_DEFAULT_SCOPES], this.correlationId);
const mergedClaims = buildMergedClaims(claims, configClaims?.length ? configClaims : undefined);
const hasAttributeTokens = !!request.attributeTokens?.length;
this.performanceClient?.addFields({
hasAttributeTokens,
}, this.correlationId);
const validatedRequest = {
claims: mergedClaims,
accountId: this.accountId,
clientId: this.config.auth.clientId,
authority: canonicalAuthority.urlString,
scope: scopeSet.printScopes(),
redirectUri: getRedirectUri(request.redirectUri, this.config.auth.redirectUri, this.logger, this.correlationId),
prompt: this.getPrompt(request.prompt),
correlationId: this.correlationId,
isSts: false,
tokenType: request.authenticationScheme,
windowTitleSubstring: document.title,
nonce: request.nonce,
state: request.state,
loginHint: request.loginHint,
extraParameters: {
...request.extraParameters,
...(request.resource && { resource: request.resource }), // resource is set for MCP scenarios
},
extendedExpiryToken: false,
keyId: request.popKid,
resourceRequestMethod: request.resourceRequestMethod,
resourceRequestUri: request.resourceRequestUri,
shrClaims: request.shrClaims,
shrNonce: request.shrNonce,
extraParametersNoCache: createPlatformAuthExtraParametersNoCache(extraParametersNoCache, isProofOfPossessionTokenType(request.authenticationScheme), request.resourceRequestMethod, request.resourceRequestUri, dpopNonce),
};
if (hasAttributeTokens) {
validatedRequest.attributeTokens =
serializeAttributeTokens(request.attributeTokens);
}
// Check for PoP token requests: signPopToken should only be set to true if popKid is not set
if (validatedRequest.signPopToken && !!request.popKid) {
throw createBrowserAuthError(invalidPopTokenRequest, this.correlationId);
}
this.handleExtraBrokerParams(validatedRequest, request.embeddedClientId);
validatedRequest.extraParameters =
validatedRequest.extraParameters || {};
validatedRequest.extraParameters.telemetry =
PlatformAuthConstants.MATS_TELEMETRY;
if (request.authenticationScheme === AuthenticationScheme.POP) {
// add POP request type
const shrParameters = {
resourceRequestUri: request.resourceRequestUri,
resourceRequestMethod: request.resourceRequestMethod,
shrClaims: request.shrClaims,
shrNonce: request.shrNonce,
correlationId: this.correlationId,
};
const popTokenGenerator = new PopTokenGenerator(this.browserCrypto, this.tokenBindingKeyManager, this.performanceClient);
// generate reqCnf if not provided in the request
let reqCnfData;
if (!validatedRequest.keyId) {
const generatedReqCnfData = await invokeAsync(popTokenGenerator.generateCnf.bind(popTokenGenerator), PopTokenGenerateCnf, this.logger, this.performanceClient, this.correlationId)(shrParameters, this.logger);
reqCnfData = generatedReqCnfData.reqCnfString;
validatedRequest.keyId = generatedReqCnfData.kid;
validatedRequest.signPopToken = true;
}
else {
reqCnfData = this.browserCrypto.base64UrlEncode(JSON.stringify({ kid: validatedRequest.keyId }));
validatedRequest.signPopToken = false;
}
// SPAs require whole string to be passed to broker
validatedRequest.reqCnf = reqCnfData;
}
this.addRequestSKUs(validatedRequest);
return validatedRequest;
}
async getCanonicalAuthority(request) {
const requestAuthority = request.authority || this.config.auth.authority;
const { azureCloudOptions, account } = request;
if (account) {
// validate authority
await getDiscoveredAuthority(this.config, this.correlationId, this.performanceClient, this.browserStorage, this.logger, requestAuthority, azureCloudOptions, undefined, // requestExtraQueryParameters
account);
}
const canonicalAuthority = new UrlString(requestAuthority, this.correlationId);
canonicalAuthority.validateAsUri();
return canonicalAuthority;
}
getPrompt(prompt) {
// If request is silent, prompt is always none
switch (this.apiId) {
case ApiId.ssoSilent:
case ApiId.acquireTokenSilent_silentFlow:
this.logger.trace("12n1y2", this.correlationId);
return PromptValue.NONE;
}
// Prompt not provided, request may proceed and native broker decides if it needs to prompt
if (!prompt) {
this.logger.trace("0uid1p", this.correlationId);
return undefined;
}
// If request is interactive, check if prompt provided is allowed to go directly to native broker
switch (prompt) {
case PromptValue.NONE:
case PromptValue.CONSENT:
case PromptValue.LOGIN:
this.logger.trace("0i0hco", this.correlationId);
return prompt;
default:
this.logger.trace(`0w3tpw ${prompt}`, this.correlationId);
throw createBrowserAuthError(nativePromptNotSupported, this.correlationId);
}
}
/**
* Handles extra broker request parameters
* @param request {PlatformAuthRequest}
* @private
*/
handleExtraBrokerParams(request, embeddedClientId) {
const hasExtraBrokerParams = request.extraParameters &&
request.extraParameters.hasOwnProperty(BROKER_CLIENT_ID) &&
request.extraParameters.hasOwnProperty(BROKER_REDIRECT_URI) &&
request.extraParameters.hasOwnProperty(CLIENT_ID);
if (!embeddedClientId && !hasExtraBrokerParams) {
return;
}
let child_client_id = "";
const child_redirect_uri = request.redirectUri;
if (embeddedClientId) {
request.redirectUri = this.config.auth.redirectUri;
child_client_id = embeddedClientId;
}
else if (request.extraParameters) {
request.redirectUri =
request.extraParameters[BROKER_REDIRECT_URI];
child_client_id =
request.extraParameters[CLIENT_ID];
}
const {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
[BROKER_CLIENT_ID]: _brkClientId,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
[BROKER_REDIRECT_URI]: _brkRedirectUri,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
[CLIENT_ID]: _clientId, ...remainingExtraParameters } = request.extraParameters || {};
request.extraParameters = {
...remainingExtraParameters,
child_client_id,
child_redirect_uri,
};
this.performanceClient?.addFields({
embeddedClientId: child_client_id,
embeddedRedirectUri: child_redirect_uri,
}, this.correlationId);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const clientDataAccountTypeMapping = new Map([
["e", "AAD"],
["m", "MSA"],
]);
/**
* Parses the clientdata response parameter from the /authorize endpoint.
*
* Logically, the clientdata value is URL-encoded and pipe-delimited:
* urlencoded(account_type | error | sub_error | cloud_instance | caller_data_boundary)
*
* In normal browser flows, this value may already have been URL-decoded
* (e.g. by URLSearchParams). This function will only apply decodeURIComponent
* when the string appears to contain percent-encoded sequences to avoid
* double-decoding.
*
* @param clientdata - The raw clientdata string from the authorize response
* @returns Parsed ClientData object, or null if the input is empty/invalid
*/
function parseClientData(clientdata) {
if (!clientdata) {
return null;
}
try {
// Only decode when the string appears to contain percent-encoded sequences
const shouldDecode = /%(?:[0-9A-Fa-f]{2})/.test(clientdata);
const decoded = shouldDecode
? decodeURIComponent(clientdata)
: clientdata;
const parts = decoded.split("|");
if (parts.length < 5) {
return null;
}
return {
accountType: clientDataAccountTypeMapping.get(parts[0]?.trim() || "") || "",
error: parts[1]?.trim() || "",
subError: parts[2]?.trim() || "",
cloudInstance: parts[3]?.trim() || "",
callerDataBoundary: parts[4]?.trim() || "",
};
}
catch {
return null;
}
}
/**
* Instruments account type, error, and suberror from clientdata
*/
function instrumentClientData(response, correlationId, performanceClient) {
const parsed = parseClientData(response.clientdata);
parsed?.accountType &&
performanceClient.addFields({ accountType: parsed.accountType }, correlationId);
parsed?.error &&
performanceClient.addFields({ serverErrorNo: parsed.error }, correlationId);
parsed?.subError &&
performanceClient.addFields({ serverSubErrorNo: parsed.subError }, correlationId);
}
/**
* Returns map of parameters that are applicable to all calls to /authorize whether using PKCE or EAR
* @param config
* @param authority
* @param request
* @param logger
* @param performanceClient
* @returns
*/
async function getStandardParameters(config, authority, request, logger, performanceClient) {
const parameters = getStandardAuthorizeRequestParameters({ ...config.auth, authority: authority }, request, logger, performanceClient);
addLibraryInfo(parameters, {
sku: BrowserConstants.MSAL_SKU,
version: version,
os: "",
cpu: "",
});
if (config.system.protocolMode !== ProtocolMode.OIDC) {
addApplicationTelemetry(parameters, config.telemetry.application);
}
if (request.platformBroker) {
// signal ests that this is a WAM call
addNativeBroker(parameters);
// instrument JS-platform bridge specific fields
performanceClient.addFields({
isPlatformAuthorizeRequest: true,
}, request.correlationId);
// pass the req_cnf for POP
if (request.authenticationScheme ===
AuthenticationScheme.POP &&
request.reqCnf) {
addPopToken(parameters, request.reqCnf);
}
}
if (request.authenticationScheme === AuthenticationScheme.DPOP &&
request.dpopJkt) {
parameters.set(DPOP_JKT, request.dpopJkt);
}
instrumentBrokerParams(parameters, request.correlationId, performanceClient);
return parameters;
}
/**
* Gets the full /authorize URL with request parameters when using Auth Code + PKCE
* @param config
* @param authority
* @param request
* @param logger
* @param performanceClient
* @returns
*/
async function getAuthCodeRequestUrl(config, authority, request, logger, performanceClient) {
if (!request.codeChallenge) {
throw createClientConfigurationError(pkceParamsMissing, request.correlationId);
}
const parameters = await invokeAsync(getStandardParameters, GetStandardParams, logger, performanceClient, request.correlationId)(config, authority, request, logger, performanceClient);
addResponseType(parameters, OAuthResponseType.CODE);
addCodeChallengeParams(parameters, request.codeChallenge, S256_CODE_CHALLENGE_METHOD);
// Merge extraQueryParameters and extraParameters to be appended to request URL
addExtraParameters(parameters, {
...request.extraQueryParameters,
...request.extraParameters,
});
return getAuthorizeUrl(authority, parameters);
}
/**
* Builds the action URL + POST-body fields for the EAR /authorize form.
*/
async function getEARFormData(config, authority, request, logger, performanceClient) {
if (!request.earJwk) {
throw createBrowserAuthError(earJwkEmpty, request.correlationId);
}
const parameters = await getStandardParameters(config, authority, request, logger, performanceClient);
addResponseType(parameters, OAuthResponseType.IDTOKEN_TOKEN_REFRESHTOKEN);
addEARParameters(parameters, request.earJwk);
// Also add codeChallenge as backup in case EAR is not supported
addCodeChallengeParams(parameters, request.codeChallenge, S256_CODE_CHALLENGE_METHOD);
addExtraParameters(parameters, {
...request.extraParameters,
});
const queryParams = new Map();
addExtraParameters(queryParams, request.extraQueryParameters || {});
// Add correlationId to query params so gateway can propagate it to IDPs
addCorrelationId(queryParams, request.correlationId);
const action = getAuthorizeUrl(authority, queryParams);
return { action, fields: Object.fromEntries(parameters) };
}
/**
* Gets the form that will be posted to /authorize with request parameters when using EAR
*/
async function getEARForm(frame, config, authority, request, logger, performanceClient) {
const { action, fields } = await getEARFormData(config, authority, request, logger, performanceClient);
return createForm(frame, action, fields);
}
/**
* Builds the action URL + POST-body fields for the auth-code /authorize form.
*/
async function getCodeFormData(config, authority, request, logger, performanceClient) {
const parameters = await getStandardParameters(config, authority, request, logger, performanceClient);
addResponseType(parameters, OAuthResponseType.CODE);
addCodeChallengeParams(parameters, request.codeChallenge, request.codeChallengeMethod || S256_CODE_CHALLENGE_METHOD);
// Add extraParameters to the request body
addExtraParameters(parameters, {
...request.extraParameters,
});
// Add extraQueryParameters to be appended to request URL
const queryParams = new Map();
addExtraParameters(queryParams, request.extraQueryParameters || {});
// Add correlationId to query params so gateway can propagate it to IDPs
addCorrelationId(queryParams, request.correlationId);
const action = getAuthorizeUrl(authority, queryParams);
return { action, fields: Object.fromEntries(parameters) };
}
/**
* Gets the form that will be posted to /authorize with request parameters when using POST method
*/
async function getCodeForm(frame, config, authority, request, logger, performanceClient) {
const { action, fields } = await getCodeFormData(config, authority, request, logger, performanceClient);
return createForm(frame, action, fields);
}
/**
* Creates a POST `<form>` in the provided document with the given auth
* parameters as hidden inputs, targeting `action`. Shared by the popup auth
* flows (`getEARForm` / `getCodeForm`) and the popup-relay page
* (`runPopupRelay`) so the form is built one way only.
*
* @param frame - document to create the form in
* @param action - form action (the /authorize URL)
* @param fields - POST-body fields
* @internal
*/
function createForm(frame, action, fields) {
const form = frame.createElement("form");
form.method = "post";
form.action = action;
Object.keys(fields).forEach((name) => {
const input = frame.createElement("input");
input.hidden = true;
input.name = name;
input.value = fields[name];
form.appendChild(input);
});
frame.body.appendChild(form);
return form;
}
/**
* Response handler when server returns accountId on the /authorize request
* @param request
* @param accountId
* @param apiId
* @param config
* @param browserStorage
* @param nativeStorage
* @param eventHandler
* @param logger
* @param performanceClient
* @param nativeMessageHandler
* @returns
*/
async function handleResponsePlatformBroker(request, accountId, apiId, config, browserStorage, nativeStorage, eventHandler, logger, performanceClient, platformAuthProvider) {
logger.verbose("11qcow", request.correlationId);
if (!platformAuthProvider) {
throw createBrowserAuthError(nativeConnectionNotEstablished, request.correlationId);
}
const browserCrypto = new CryptoOps(logger, performanceClient);
const nativeInteractionClient = new PlatformAuthInteractionClient(config, browserStorage, browserCrypto, logger, eventHandler, config.system.navigationClient, apiId, performanceClient, platformAuthProvider, accountId, nativeStorage, request.correlationId);
const { userRequestState } = parseRequestState(browserCrypto.base64Decode, request.state, request.correlationId);
return invokeAsync(nativeInteractionClient.acquireToken.bind(nativeInteractionClient), NativeInteractionClientAcquireToken, logger, performanceClient, request.correlationId)({
...request,
state: userRequestState,
prompt: undefined, // Server should handle the prompt, ideally native broker can do this part silently
});
}
/**
* Response handler when server returns code on the /authorize request
* @param request
* @param response
* @param codeVerifier
* @param authClient
* @param browserStorage
* @param logger
* @param performanceClient
* @returns
*/
async function handleResponseCode(request, response, codeVerifier, apiId, config, authClient, browserStorage, nativeStorage, eventHandler, logger, performanceClient, platformAuthProvider) {
// Remove throttle if it exists
ThrottlingUtils.removeThrottle(browserStorage, config.auth.clientId, request);
// Instrument clientdata telemetry fields from the authorize response
instrumentClientData(response, request.correlationId, performanceClient);
if (response.accountId) {
return invokeAsync(handleResponsePlatformBroker, HandleResponsePlatformBroker, logger, performanceClient, request.correlationId)(request, response.accountId, apiId, config, browserStorage, nativeStorage, eventHandler, logger, performanceClient, platformAuthProvider);
}
const authCodeRequest = {
...request,
code: response.code || "",
codeVerifier: codeVerifier,
};
// Create popup interaction handler.
const interactionHandler = new InteractionHandler(authClient, browserStorage, authCodeRequest, logger, performanceClient);
// Handle response from hash string.
const result = await invokeAsync(interactionHandler.handleCodeResponse.bind(interactionHandler), HandleCodeResponse, logger, performanceClient, request.correlationId)(response, request, apiId);
return result;
}
/**
* Response handler when server returns ear_jwe on the /authorize request
* @param request
* @param response
* @param apiId
* @param config
* @param authority
* @param browserStorage
* @param nativeStorage
* @param eventHandler
* @param logger
* @param performanceClient
* @param nativeMessageHandler
* @returns
*/
async function handleResponseEAR(request, response, apiId, config, authority, browserStorage, nativeStorage, eventHandler, logger, performanceClient, platformAuthProvider) {
// Remove throttle if it exists
ThrottlingUtils.removeThrottle(browserStorage, config.auth.clientId, request);
// Instrument clientdata telemetry fields from the authorize response
instrumentClientData(response, request.correlationId, performanceClient);
// Validate state & check response for errors
validateAuthorizationResponse(response, request.state, request.correlationId);
if (!response.ear_jwe) {
throw createBrowserAuthError(earJweEmpty, request.correlationId);
}
if (!request.earJwk) {
throw createBrowserAuthError(earJwkEmpty, request.correlationId);
}
const decryptedData = JSON.parse(await invokeAsync(decryptEarResponse, DecryptEarResponse, logger, performanceClient, request.correlationId)(request.earJwk, response.ear_jwe));
if (decryptedData.accountId) {
return invokeAsync(handleResponsePlatformBroker, HandleResponsePlatformBroker, logger, performanceClient, request.correlationId)(request, decryptedData.accountId, apiId, config, browserStorage, nativeStorage, eventHandler, logger, performanceClient, platformAuthProvider);
}
const responseHandler = new ResponseHandler(config.auth.clientId, browserStorage, new CryptoOps(logger, performanceClient), logger, performanceClient, null, null, new TokenBindingKeyManager(logger, performanceClient));
// Validate response. This function throws a server error if an error is returned by the server.
responseHandler.validateTokenResponse(decryptedData, request.correlationId);
// Temporary until response handler is refactored to be more flow agnostic.
const additionalData = {
code: "",
state: request.state,
nonce: request.nonce,
client_info: decryptedData.client_info,
cloud_graph_host_name: decryptedData.cloud_graph_host_name,
cloud_instance_host_name: decryptedData.cloud_instance_host_name,
cloud_instance_name: decryptedData.cloud_instance_name,
msgraph_host: decryptedData.msgraph_host,
};
return (await invokeAsync(responseHandler.handleServerTokenResponse.bind(responseHandler), HandleServerTokenResponse, logger, performanceClient, request.correlationId)(decryptedData, authority, nowSeconds(), request, apiId, additionalData, undefined, undefined, undefined, undefined));
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
// Constant byte array length
const RANDOM_BYTE_ARR_LENGTH = 32;
/**
* This file defines APIs to generate PKCE codes and code verifiers.
*/
/**
* Generates PKCE Codes. See the RFC for more information: https://tools.ietf.org/html/rfc7636
*/
async function generatePkceCodes(performanceClient, logger, correlationId) {
const codeVerifier = invoke(generateCodeVerifier, GenerateCodeVerifier, logger, performanceClient, correlationId)(performanceClient, logger, correlationId);
const codeChallenge = await invokeAsync(generateCodeChallengeFromVerifier, GenerateCodeChallengeFromVerifier, logger, performanceClient, correlationId)(codeVerifier, performanceClient, logger, correlationId);
return {
verifier: codeVerifier,
challenge: codeChallenge,
};
}
/**
* Generates a random 32 byte buffer and returns the base64
* encoded string to be used as a PKCE Code Verifier
*/
function generateCodeVerifier(performanceClient, logger, correlationId) {
try {
// Generate random values as utf-8
const buffer = new Uint8Array(RANDOM_BYTE_ARR_LENGTH);
invoke(getRandomValues, GetRandomValues, logger, performanceClient, correlationId)(buffer);
// encode verifier as base64
const pkceCodeVerifierB64 = urlEncodeArr(buffer);
return pkceCodeVerifierB64;
}
catch (e) {
throw createBrowserAuthError(pkceNotCreated, correlationId);
}
}
/**
* Creates a base64 encoded PKCE Code Challenge string from the
* hash created from the PKCE Code Verifier supplied
*/
async function generateCodeChallengeFromVerifier(pkceCodeVerifier, performanceClient, logger, correlationId) {
try {
// hashed verifier
const pkceHashedCodeVerifier = await invokeAsync(sha256Digest, Sha256Digest, logger, performanceClient, correlationId)(pkceCodeVerifier);
// encode hash as base64
return urlEncodeArr(new Uint8Array(pkceHashedCodeVerifier));
}
catch (e) {
throw createBrowserAuthError(pkceNotCreated, correlationId);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class NavigationClient {
/**
* Navigates to other pages within the same web application
* @param url
* @param options
*/
navigateInternal(url, options) {
return NavigationClient.defaultNavigateWindow(url, options);
}
/**
* Navigates to other pages outside the web application i.e. the Identity Provider
* @param url
* @param options
*/
navigateExternal(url, options) {
return NavigationClient.defaultNavigateWindow(url, options);
}
/**
* Default navigation implementation invoked by the internal and external functions
* @param url
* @param options
*/
static defaultNavigateWindow(url, options) {
if (options.noHistory) {
window.location.replace(url); // CodeQL [SM03712] Application owner controls the URL. User can't change it.
}
else {
window.location.assign(url); // CodeQL [SM03712] Application owner controls the URL. User can't change it.
}
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(createBrowserAuthError(timedOut, "", "failed_to_redirect"));
}, options.timeout);
});
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const MAX_FETCH_POST_RETRIES = 1;
const RETRY_DELAY_MS = 100;
/**
* This class implements the Fetch API for GET and POST requests. See more here: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
*/
class FetchClient {
/**
* Fetch Client for REST endpoints - Get request
* @param url
* @param headers
* @param body
*/
async sendGetRequestAsync(url, options) {
let response;
let responseHeaders = {};
let responseStatus = 0;
const reqHeaders = getFetchHeaders(options);
try {
response = await fetch(url, {
method: HTTP_REQUEST_TYPE.GET,
headers: reqHeaders,
});
}
catch (e) {
throw createNetworkError(createBrowserAuthError(window.navigator.onLine
? getRequestFailed
: noNetworkConnectivity, ""), undefined, undefined, e);
}
responseHeaders = getHeaderDict(response.headers);
try {
responseStatus = response.status;
return {
headers: responseHeaders,
body: (await response.json()),
status: responseStatus,
};
}
catch (e) {
throw createNetworkError(createBrowserAuthError(failedToParseResponse, ""), responseStatus, responseHeaders, e);
}
}
/**
* Fetch Client for REST endpoints - Post request
* @param url
* @param headers
* @param body
*/
async sendPostRequestAsync(url, options) {
const reqBody = (options && options.body) || "";
const reqHeaders = getFetchHeaders(options);
const correlationId = options?.correlationId;
const performanceClient = options?.performanceClient;
let response;
let lastError;
for (let attempt = 1; attempt <= MAX_FETCH_POST_RETRIES + 1; attempt++) {
try {
response = await fetch(url, {
method: HTTP_REQUEST_TYPE.POST,
headers: reqHeaders,
body: reqBody,
});
break;
}
catch (e) {
lastError = e;
if (!shouldRetryPostFetchError(lastError, attempt)) {
throw createNetworkError(createBrowserAuthError(window.navigator.onLine !== false
? postRequestFailed
: noNetworkConnectivity, correlationId || ""), undefined, undefined, lastError);
}
// Brief backoff before retry
await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS));
if (correlationId) {
performanceClient?.incrementFields({ fetchRetryCount: 1 }, correlationId);
}
}
}
if (!response) {
throw createNetworkError(createBrowserAuthError(window.navigator.onLine !== false
? postRequestFailed
: noNetworkConnectivity, correlationId || ""), undefined, undefined, lastError);
}
let responseStatus = 0;
let responseHeaders = {};
responseHeaders = getHeaderDict(response.headers);
try {
responseStatus = response.status;
return {
headers: responseHeaders,
body: (await response.json()),
status: responseStatus,
};
}
catch (e) {
throw createNetworkError(createBrowserAuthError(failedToParseResponse, correlationId || ""), responseStatus, responseHeaders, e);
}
}
}
function shouldRetryPostFetchError(error, attempt) {
return (attempt <= MAX_FETCH_POST_RETRIES &&
window.navigator.onLine !== false &&
error.name !== "AbortError");
}
/**
* Get Fetch API Headers object from string map
* @param inputHeaders
*/
function getFetchHeaders(options) {
try {
const headers = new Headers();
if (!(options && options.headers)) {
return headers;
}
const optionsHeaders = options.headers;
Object.entries(optionsHeaders).forEach(([key, value]) => {
headers.append(key, value);
});
return headers;
}
catch (e) {
throw createNetworkError(createBrowserAuthError(failedToBuildHeaders, ""), undefined, undefined, e);
}
}
/**
* Returns object representing response headers
* @param headers
* @returns
*/
function getHeaderDict(headers) {
try {
const headerDict = {};
headers.forEach((value, key) => {
headerDict[key] = value;
});
return headerDict;
}
catch (e) {
throw createBrowserAuthError(failedToParseHeaders, "");
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
// Default timeout for popup windows and iframes in milliseconds
const DEFAULT_POPUP_TIMEOUT_MS = 60000;
const DEFAULT_IFRAME_TIMEOUT_MS = 10000;
const DEFAULT_REDIRECT_TIMEOUT_MS = 30000;
const DEFAULT_NATIVE_BROKER_HANDSHAKE_TIMEOUT_MS = 2000;
/**
* MSAL function that sets the default options when not explicitly configured from app developer
*
* @param auth
* @param cache
* @param system
*
* @returns Configuration object
*/
function buildConfiguration({ auth: userInputAuth, cache: userInputCache, system: userInputSystem, experimental: userInputExperimental, telemetry: userInputTelemetry, }, isBrowserEnvironment) {
// Default auth options for browser
const DEFAULT_AUTH_OPTIONS = {
clientId: "",
authority: `${DEFAULT_AUTHORITY}`,
knownAuthorities: [],
cloudDiscoveryMetadata: "",
authorityMetadata: "",
redirectUri: typeof window !== "undefined" && window.location
? window.location.href.split("?")[0].split("#")[0]
: "",
postLogoutRedirectUri: "",
popupRelayUri: "",
clientCapabilities: [],
OIDCOptions: {
responseMode: ResponseMode.FRAGMENT,
defaultScopes: [
OPENID_SCOPE,
PROFILE_SCOPE,
OFFLINE_ACCESS_SCOPE,
],
},
azureCloudOptions: {
azureCloudInstance: AzureCloudInstance.None,
tenant: "",
},
instanceAware: false,
isMcp: false,
verifySSO: false,
};
// Default cache options for browser
const DEFAULT_CACHE_OPTIONS = {
cacheLocation: BrowserCacheLocation.SessionStorage,
cacheRetentionDays: 5,
};
// Default logger options for browser
const DEFAULT_LOGGER_OPTIONS = {
// eslint-disable-next-line @typescript-eslint/no-empty-function
loggerCallback: () => {
// allow users to not set logger call back
},
logLevel: exports.LogLevel.Info,
piiLoggingEnabled: false,
};
// Default system options for browser
const DEFAULT_BROWSER_SYSTEM_OPTIONS = {
...DEFAULT_SYSTEM_OPTIONS,
loggerOptions: DEFAULT_LOGGER_OPTIONS,
networkClient: isBrowserEnvironment
? new FetchClient()
: StubbedNetworkModule,
navigationClient: new NavigationClient(),
popupBridgeTimeout: userInputSystem?.popupBridgeTimeout || DEFAULT_POPUP_TIMEOUT_MS,
iframeBridgeTimeout: userInputSystem?.iframeBridgeTimeout || DEFAULT_IFRAME_TIMEOUT_MS,
redirectNavigationTimeout: DEFAULT_REDIRECT_TIMEOUT_MS,
allowRedirectInIframe: false,
navigatePopups: true,
allowPlatformBroker: false,
nativeBrokerHandshakeTimeout: userInputSystem?.nativeBrokerHandshakeTimeout ||
DEFAULT_NATIVE_BROKER_HANDSHAKE_TIMEOUT_MS,
protocolMode: ProtocolMode.AAD,
serverTelemetryEnabled: false,
};
const providedSystemOptions = {
...DEFAULT_BROWSER_SYSTEM_OPTIONS,
...userInputSystem,
loggerOptions: userInputSystem?.loggerOptions || DEFAULT_LOGGER_OPTIONS,
};
const DEFAULT_TELEMETRY_OPTIONS = {
application: {
appName: "",
appVersion: "",
},
client: new StubPerformanceClient(),
};
const DEFAULT_EXPERIMENTAL_OPTIONS = {
iframeTimeoutTelemetry: false,
allowPlatformBrokerWithDOM: false,
};
// Throw an error if user has set OIDCOptions without being in OIDC protocol mode
if (userInputSystem?.protocolMode !== ProtocolMode.OIDC &&
userInputAuth?.OIDCOptions) {
const logger = new Logger(providedSystemOptions.loggerOptions, name, version);
logger.warning(JSON.stringify(createClientConfigurationError(cannotSetOIDCOptions, "")), "");
}
// Throw an error if user has set allowPlatformBroker to true with OIDC protocol mode
if (userInputSystem?.protocolMode &&
userInputSystem.protocolMode === ProtocolMode.OIDC &&
providedSystemOptions?.allowPlatformBroker) {
throw createClientConfigurationError(cannotAllowPlatformBroker, "");
}
const overlayedConfig = {
auth: {
...DEFAULT_AUTH_OPTIONS,
...userInputAuth,
OIDCOptions: {
...DEFAULT_AUTH_OPTIONS.OIDCOptions,
...userInputAuth?.OIDCOptions,
},
},
cache: { ...DEFAULT_CACHE_OPTIONS, ...userInputCache },
system: providedSystemOptions,
experimental: {
...DEFAULT_EXPERIMENTAL_OPTIONS,
...userInputExperimental,
},
telemetry: { ...DEFAULT_TELEMETRY_OPTIONS, ...userInputTelemetry },
};
return overlayedConfig;
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class PlatformAuthExtensionHandler {
constructor(logger, handshakeTimeoutMs, performanceClient, extensionId, correlationId) {
this.logger = logger;
this.handshakeTimeoutMs = handshakeTimeoutMs;
this.extensionId = extensionId;
this.resolvers = new Map(); // Used for non-handshake messages
this.handshakeResolvers = new Map(); // Used for handshake messages
this.messageChannel = new MessageChannel();
this.windowListener = this.onWindowMessage.bind(this); // Window event callback doesn't have access to 'this' unless it's bound
this.performanceClient = performanceClient;
this.correlationId = correlationId || createNewGuid();
this.handshakeEvent = this.performanceClient.startMeasurement(NativeMessageHandlerHandshake, this.correlationId);
this.platformAuthType =
PlatformAuthConstants.PLATFORM_EXTENSION_PROVIDER;
}
/**
* Sends a given message to the extension and resolves with the extension response
* @param request
*/
async sendMessage(request) {
const correlationId = this.getCorrelationId(request.correlationId);
const sendMessageMeasurement = this.performanceClient.startMeasurement(PlatformAuthExtensionGetToken, correlationId);
sendMessageMeasurement.add({
platformAuthProviderType: this.platformAuthType,
});
this.logger.trace(`0on4p2 ${this.platformAuthType}`, correlationId);
try {
// fall back to native calls
const extensionRequest = { ...request };
delete extensionRequest.resourceRequestMethod;
delete extensionRequest.resourceRequestUri;
const messageBody = {
method: NativeExtensionMethod.GetToken,
request: extensionRequest,
};
const req = {
channel: PlatformAuthConstants.CHANNEL_ID,
extensionId: this.extensionId,
responseId: createNewGuid(),
body: messageBody,
};
this.logger.trace(`1qadfi ${this.platformAuthType}`, correlationId);
this.logger.tracePii(`1xm533 ${this.platformAuthType} ${JSON.stringify(req)}`, correlationId);
this.messageChannel.port1.postMessage(req);
const response = await new Promise((resolve, reject) => {
this.resolvers.set(req.responseId, {
resolve,
reject,
correlationId,
});
});
const validatedResponse = this.validatePlatformBrokerResponse(response, correlationId);
sendMessageMeasurement.end({
success: true,
platformAuthProviderType: this.platformAuthType,
});
return validatedResponse;
}
catch (e) {
sendMessageMeasurement.end({
success: false,
platformAuthProviderType: this.platformAuthType,
}, e);
throw e;
}
}
/**
* Returns an instance of the MessageHandler that has successfully established a connection with an extension
* @param {Logger} logger
* @param {number} handshakeTimeoutMs
* @param {IPerformanceClient} performanceClient
* @param {ICrypto} crypto
*/
static async createProvider(logger, handshakeTimeoutMs, performanceClient, correlationId) {
logger.trace("15zfnw", correlationId);
const createProviderMeasurement = performanceClient.startMeasurement(PlatformAuthExtensionCreateProvider, correlationId);
try {
const preferredProvider = new PlatformAuthExtensionHandler(logger, handshakeTimeoutMs, performanceClient, PlatformAuthConstants.PREFERRED_EXTENSION_ID, correlationId);
await preferredProvider.sendHandshakeRequest();
createProviderMeasurement.add({
platformAuthProviderAvailable: true,
platformAuthProviderType: PlatformAuthConstants.PLATFORM_EXTENSION_PROVIDER,
});
createProviderMeasurement.end({
platformAuthProviderAvailable: true,
platformAuthProviderType: PlatformAuthConstants.PLATFORM_EXTENSION_PROVIDER,
});
return preferredProvider;
}
catch (e) {
// If preferred extension fails for whatever reason, fallback to using any installed extension
try {
const backupProvider = new PlatformAuthExtensionHandler(logger, handshakeTimeoutMs, performanceClient, undefined, correlationId);
await backupProvider.sendHandshakeRequest();
createProviderMeasurement.add({
platformAuthProviderAvailable: true,
platformAuthProviderType: PlatformAuthConstants.PLATFORM_EXTENSION_PROVIDER,
});
createProviderMeasurement.end({
platformAuthProviderAvailable: true,
platformAuthProviderType: PlatformAuthConstants.PLATFORM_EXTENSION_PROVIDER,
});
return backupProvider;
}
catch (backupError) {
createProviderMeasurement.add({
platformAuthProviderAvailable: false,
});
createProviderMeasurement.end({
platformAuthProviderAvailable: false,
}, backupError);
throw backupError;
}
}
}
/**
* Send handshake request helper.
*/
async sendHandshakeRequest() {
this.logger.trace(`1dpg9o ${this.platformAuthType}`, this.correlationId);
// Register this event listener before sending handshake
window.addEventListener("message", this.windowListener, false); // false is important, because content script message processing should work first
const req = {
channel: PlatformAuthConstants.CHANNEL_ID,
extensionId: this.extensionId,
responseId: createNewGuid(),
body: {
method: NativeExtensionMethod.HandshakeRequest,
},
};
this.handshakeEvent.add({
extensionId: this.extensionId,
extensionHandshakeTimeoutMs: this.handshakeTimeoutMs,
platformAuthRequestCorrelationId: this.correlationId,
});
this.messageChannel.port1.onmessage = (event) => {
this.onChannelMessage(event);
};
window.postMessage(req, window.origin, [this.messageChannel.port2]);
return new Promise((resolve, reject) => {
this.handshakeResolvers.set(req.responseId, {
resolve,
reject,
correlationId: this.correlationId,
});
this.timeoutId = window.setTimeout(() => {
/*
* Throw an error if neither HandshakeResponse nor original Handshake request are received in a reasonable timeframe.
* This typically suggests an event handler stopped propagation of the Handshake request but did not respond to it on the MessageChannel port
*/
window.removeEventListener("message", this.windowListener, false);
this.messageChannel.port1.close();
this.messageChannel.port2.close();
this.handshakeEvent.add({
extensionHandshakeTimedOut: true,
});
this.handshakeEvent.end({
extensionHandshakeTimedOut: true,
success: false,
});
reject(createBrowserAuthError(nativeHandshakeTimeout, this.correlationId));
this.handshakeResolvers.delete(req.responseId);
}, this.handshakeTimeoutMs); // Use a reasonable timeout in milliseconds here
});
}
/**
* Invoked when a message is posted to the window. If a handshake request is received it means the extension is not installed.
* @param event
*/
onWindowMessage(event) {
let correlationId = createGuid();
this.logger.trace(`0jpn5u ${this.platformAuthType}`, correlationId);
// We only accept messages from ourselves
if (event.source !== window) {
return;
}
const request = event.data;
if (!request.channel ||
request.channel !== PlatformAuthConstants.CHANNEL_ID) {
return;
}
if (request.extensionId && request.extensionId !== this.extensionId) {
return;
}
if (request.body.method === NativeExtensionMethod.HandshakeRequest) {
const handshakeResolver = this.handshakeResolvers.get(request.responseId);
/*
* Filter out responses with no matched resolvers sooner to keep channel ports open while waiting for
* the proper response.
*/
if (!handshakeResolver) {
this.logger.trace(`07buhm ${this.platformAuthType} ${request.responseId}`, correlationId);
return;
}
correlationId = handshakeResolver.correlationId;
// If we receive this message back it means no extension intercepted the request, meaning no extension supporting handshake protocol is installed
this.logger.verbose(request.extensionId
? `0xrkug ${request.extensionId}`
: "No extension installed", correlationId);
clearTimeout(this.timeoutId);
this.messageChannel.port1.close();
this.messageChannel.port2.close();
window.removeEventListener("message", this.windowListener, false);
this.handshakeEvent.add({
extensionInstalled: false,
});
this.handshakeEvent.end({
success: false,
extensionInstalled: false,
});
handshakeResolver.reject(createBrowserAuthError(nativeExtensionNotInstalled, correlationId));
this.handshakeResolvers.delete(request.responseId);
}
}
/**
* Invoked when a message is received from the extension on the MessageChannel port
* @param event
*/
onChannelMessage(event) {
const request = event.data;
const responseId = request?.responseId;
const resolver = responseId
? this.resolvers.get(responseId)
: undefined;
const handshakeResolver = responseId
? this.handshakeResolvers.get(responseId)
: undefined;
const correlationId = resolver?.correlationId ||
handshakeResolver?.correlationId ||
createGuid();
this.logger.trace(`1py8yf ${this.platformAuthType}`, correlationId);
try {
const method = request.body.method;
if (method === NativeExtensionMethod.Response) {
if (!resolver) {
return;
}
try {
const response = request.body.response;
this.logger.trace(`19hpgm ${this.platformAuthType}`, correlationId);
this.logger.tracePii(`179a24 ${this.platformAuthType} ${JSON.stringify(response)}`, correlationId);
if (response.status !== "Success") {
resolver.reject(createNativeAuthError(response.code, correlationId, response.description, response.ext));
}
else if (response.result) {
if (response.result["code"] &&
response.result["description"]) {
resolver.reject(createNativeAuthError(response.result["code"], correlationId, response.result["description"], response.result["ext"]));
}
else {
resolver.resolve(response.result);
}
}
else {
throw createAuthError(unexpectedError, correlationId, "Event does not contain result.");
}
}
finally {
this.resolvers.delete(request.responseId);
}
}
else if (method === NativeExtensionMethod.HandshakeResponse) {
if (!handshakeResolver) {
this.logger.trace(`082qnt ${this.platformAuthType} ${request.responseId}`, correlationId);
return;
}
clearTimeout(this.timeoutId); // Clear setTimeout
window.removeEventListener("message", this.windowListener, false); // Remove 'No extension' listener
this.extensionId = request.extensionId;
this.extensionVersion = request.body.version?.toString();
this.logger.verbose(`0yf5ib ${this.platformAuthType} ${this.extensionId}`, correlationId);
this.handshakeEvent.add({
extensionId: this.extensionId,
extensionVersion: this.extensionVersion,
extensionInstalled: true,
});
this.handshakeEvent.end({
extensionId: this.extensionId,
extensionVersion: this.extensionVersion,
extensionInstalled: true,
success: true,
});
handshakeResolver.resolve();
this.handshakeResolvers.delete(request.responseId);
}
else if (resolver) {
this.resolvers.delete(request.responseId);
resolver.reject(createAuthError(unexpectedError, correlationId, "Extension response contains an unexpected method."));
}
}
catch (err) {
this.logger.error("0xf978", correlationId);
this.logger.errorPii(`04i99o ${err}`, correlationId);
this.logger.errorPii(`0xdvsy ${event}`, correlationId);
if (resolver) {
this.resolvers.delete(responseId);
resolver.reject(err instanceof AuthError
? err
: createAuthError(unexpectedError, correlationId, "Unable to parse extension response."));
}
else if (handshakeResolver) {
clearTimeout(this.timeoutId);
window.removeEventListener("message", this.windowListener, false);
this.messageChannel.port1.close();
this.messageChannel.port2.close();
this.handshakeEvent.end({
success: false,
});
this.handshakeResolvers.delete(responseId);
handshakeResolver.reject(err);
}
}
}
/**
* Validates native platform response before processing
* @param response
*/
validatePlatformBrokerResponse(response, correlationId) {
const responseCorrelationId = this.getCorrelationId(correlationId);
const validationMeasurement = this.performanceClient.startMeasurement(PlatformAuthExtensionValidateResponse, responseCorrelationId);
if (response &&
Object.prototype.hasOwnProperty.call(response, "access_token") &&
Object.prototype.hasOwnProperty.call(response, "id_token") &&
Object.prototype.hasOwnProperty.call(response, "client_info") &&
Object.prototype.hasOwnProperty.call(response, "account") &&
Object.prototype.hasOwnProperty.call(response, "scope") &&
Object.prototype.hasOwnProperty.call(response, "expires_in")) {
validationMeasurement.end({
success: true,
platformAuthProviderType: this.platformAuthType,
});
return response;
}
else {
const error = createAuthError(unexpectedError, responseCorrelationId, "Response missing expected properties.");
validationMeasurement.end({
success: false,
platformAuthProviderType: this.platformAuthType,
}, error);
throw error;
}
}
getCorrelationId(correlationId) {
return correlationId || this.correlationId;
}
/**
* Returns the Id for the browser extension this handler is communicating with
* @returns
*/
getExtensionId() {
return this.extensionId;
}
/**
* Returns the version for the browser extension this handler is communicating with
* @returns
*/
getExtensionVersion() {
return this.extensionVersion;
}
getExtensionName() {
return this.getExtensionId() ===
PlatformAuthConstants.PREFERRED_EXTENSION_ID
? "chrome"
: this.getExtensionId()?.length
? "unknown"
: undefined;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class PlatformAuthDOMHandler {
constructor(logger, performanceClient, correlationId) {
this.logger = logger;
this.performanceClient = performanceClient;
this.correlationId = correlationId;
this.platformAuthType = PlatformAuthConstants.PLATFORM_DOM_PROVIDER;
}
static async createProvider(logger, performanceClient, correlationId) {
logger.trace("12mj4a", correlationId);
const createProviderMeasurement = performanceClient.startMeasurement(PlatformAuthDOMCreateProvider, correlationId);
try {
const platformAuthentication = window.navigator.platformAuthentication;
if (!platformAuthentication) {
createProviderMeasurement.add({
platformAuthProviderAvailable: false,
});
createProviderMeasurement.end({
platformAuthProviderAvailable: false,
});
return undefined;
}
const supportedContracts = (await invokeAsync(platformAuthentication.getSupportedContracts.bind(platformAuthentication), PlatformAuthDOMGetSupportedContracts, logger, performanceClient, correlationId)(PlatformAuthConstants.MICROSOFT_ENTRA_BROKERID));
const contractSupported = supportedContracts?.includes(PlatformAuthConstants.PLATFORM_DOM_APIS);
if (contractSupported) {
logger.trace("1h5q1r", correlationId);
createProviderMeasurement.add({
platformAuthProviderAvailable: true,
platformAuthProviderType: PlatformAuthConstants.PLATFORM_DOM_PROVIDER,
});
createProviderMeasurement.end({
platformAuthProviderAvailable: true,
platformAuthProviderType: PlatformAuthConstants.PLATFORM_DOM_PROVIDER,
});
return new PlatformAuthDOMHandler(logger, performanceClient, correlationId);
}
createProviderMeasurement.add({
platformAuthProviderAvailable: false,
});
createProviderMeasurement.end({
platformAuthProviderAvailable: false,
});
return undefined;
}
catch (e) {
createProviderMeasurement.add({
platformAuthProviderAvailable: false,
});
createProviderMeasurement.end({
platformAuthProviderAvailable: false,
}, e);
throw e;
}
}
/**
* Returns the Id for the broker extension this handler is communicating with
* @returns
*/
getExtensionId() {
return PlatformAuthConstants.MICROSOFT_ENTRA_BROKERID;
}
getExtensionVersion() {
return "";
}
getExtensionName() {
return PlatformAuthConstants.DOM_API_NAME;
}
/**
* Send token request to platform broker via browser DOM API
* @param request
* @returns
*/
async sendMessage(request) {
const correlationId = this.getCorrelationId(request.correlationId);
const sendMessageMeasurement = this.performanceClient.startMeasurement(PlatformAuthDOMGetToken, correlationId);
sendMessageMeasurement.add({
platformAuthProviderType: this.platformAuthType,
});
this.logger.trace(`02bcil ${this.platformAuthType}`, correlationId);
try {
const platformDOMRequest = invoke(this.initializePlatformDOMRequest.bind(this), PlatformAuthDOMInitializeRequest, this.logger, this.performanceClient, correlationId)(request);
const response =
// @ts-ignore
await window.navigator.platformAuthentication.executeGetToken(platformDOMRequest);
const validatedResponse = this.validatePlatformBrokerResponse(response, correlationId);
sendMessageMeasurement.end({
success: true,
platformAuthProviderType: this.platformAuthType,
});
return validatedResponse;
}
catch (e) {
this.logger.error(`11im7g ${this.platformAuthType}`, correlationId);
sendMessageMeasurement.end({
success: false,
platformAuthProviderType: this.platformAuthType,
}, e);
throw e;
}
}
initializePlatformDOMRequest(request) {
const { accountId, clientId, authority, scope, redirectUri, correlationId, state, preferBinding, enclave, reqCnf, extraParametersNoCache, extraParameters, ...remainingProperties } = request;
const requestCorrelationId = this.getCorrelationId(correlationId);
this.logger.trace(`15d6yv ${this.platformAuthType}`, requestCorrelationId);
delete remainingProperties.resourceRequestMethod;
delete remainingProperties.resourceRequestUri;
const validExtraParameters = this.getDOMExtraParams(remainingProperties, requestCorrelationId);
const platformDOMRequest = {
accountId: accountId,
brokerId: this.getExtensionId(),
authority: authority,
clientId: clientId,
correlationId: requestCorrelationId,
extraParameters: {
...extraParameters,
...validExtraParameters,
},
isSecurityTokenService: false,
redirectUri: redirectUri,
scope: scope,
state: state,
preferBinding: preferBinding,
enclave: enclave,
requestConfirmation: reqCnf,
extraParametersNoCache,
};
return platformDOMRequest;
}
validatePlatformBrokerResponse(response, correlationId) {
const validationMeasurement = this.performanceClient.startMeasurement(PlatformAuthDOMValidateResponse, correlationId);
const requiredKeys = [
"accessToken",
"idToken",
"clientInfo",
"account",
"scopes",
"expiresIn",
];
const isValid = response &&
requiredKeys.every((key) => Object.prototype.hasOwnProperty.call(response, key));
if (response &&
Object.prototype.hasOwnProperty.call(response, "isSuccess")) {
if (isValid) {
this.logger.trace(`0h4vei ${this.platformAuthType}`, correlationId);
try {
const validatedResponse = this.convertToPlatformBrokerResponse(response, correlationId);
validationMeasurement.end({
success: true,
platformAuthProviderType: this.platformAuthType,
});
return validatedResponse;
}
catch (e) {
validationMeasurement.end({
success: false,
platformAuthProviderType: this.platformAuthType,
}, e);
throw e;
}
}
else if (Object.prototype.hasOwnProperty.call(response, "error")) {
const errorResponse = response;
if (errorResponse.isSuccess === false &&
errorResponse.error &&
errorResponse.error.code) {
this.logger.trace(`0g92vm ${this.platformAuthType}`, correlationId);
const nativeAuthError = createNativeAuthError(errorResponse.error.code, correlationId, errorResponse.error.description, {
error: parseInt(errorResponse.error.errorCode),
protocol_error: errorResponse.error.protocolError,
status: errorResponse.error.status,
properties: errorResponse.error.properties,
});
validationMeasurement.end({
success: false,
platformAuthProviderType: this.platformAuthType,
brokerErrorName: errorResponse.error.code,
brokerErrorCode: errorResponse.error.errorCode,
}, nativeAuthError);
throw nativeAuthError;
}
}
}
const error = createAuthError(unexpectedError, correlationId, "Response missing expected properties.");
validationMeasurement.end({
success: false,
platformAuthProviderType: this.platformAuthType,
}, error);
throw error;
}
getCorrelationId(correlationId) {
return correlationId || this.correlationId;
}
convertToPlatformBrokerResponse(response, correlationId) {
this.logger.trace(`14913t ${this.platformAuthType}`, correlationId);
const responseProperties = response.properties || {};
const bindingAttested = this.parseDOMBoolean(responseProperties.binding_attested, "binding_attested", correlationId);
const nativeResponse = {
access_token: response.accessToken,
id_token: response.idToken,
client_info: response.clientInfo,
account: response.account,
expires_in: response.expiresIn,
scope: response.scopes,
state: response.state || "",
properties: responseProperties,
extendedLifetimeToken: response.extendedLifetimeToken ?? false,
shr: response.proofOfPossessionPayload,
token_type: responseProperties.token_type,
DPoP: responseProperties.dpop_proof,
binding_attested: bindingAttested,
};
return nativeResponse;
}
parseDOMBoolean(value, propertyName, correlationId) {
if (value === undefined) {
return undefined;
}
if (value === "true" || value === "false") {
return value === "true";
}
throw createAuthError(unexpectedError, correlationId, `Platform broker returned invalid ${propertyName} value.`);
}
getDOMExtraParams(extraParameters, correlationId) {
try {
const stringifiedProperties = {};
for (const [key, value] of Object.entries(extraParameters)) {
if (!value) {
continue;
}
if (typeof value === "object") {
stringifiedProperties[key] = JSON.stringify(value);
}
else {
stringifiedProperties[key] = String(value);
}
}
return stringifiedProperties;
}
catch (e) {
this.logger.error(`0eu9o3 ${this.platformAuthType}`, correlationId);
this.logger.errorPii(`17rpl5 ${this.platformAuthType} ${e}`, correlationId);
return {};
}
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
async function getPlatformAuthProvider(logger, performanceClient, correlationId, nativeBrokerHandshakeTimeout, enablePlatformBrokerDOMSupport) {
logger.trace("134j0v", correlationId);
const discoveryMeasurement = performanceClient.startMeasurement(PlatformAuthProviderDiscovery, correlationId);
logger.trace(`04c81g ${enablePlatformBrokerDOMSupport}`, correlationId);
let platformAuthProvider;
try {
if (enablePlatformBrokerDOMSupport) {
// Check if DOM platform API is supported first
try {
platformAuthProvider =
await PlatformAuthDOMHandler.createProvider(logger, performanceClient, correlationId);
}
catch (e) {
logger.trace("1ij09j", correlationId);
}
if (platformAuthProvider) {
discoveryMeasurement.add({
platformAuthProviderType: PlatformAuthConstants.PLATFORM_DOM_PROVIDER,
});
discoveryMeasurement.end({
success: true,
platformAuthProviderType: PlatformAuthConstants.PLATFORM_DOM_PROVIDER,
});
return platformAuthProvider;
}
}
logger.trace("0l3na8", correlationId);
/*
* If DOM APIs are not available, check if browser extension is available.
* Platform authentication via DOM APIs is preferred over extension APIs.
*/
platformAuthProvider =
await PlatformAuthExtensionHandler.createProvider(logger, nativeBrokerHandshakeTimeout ||
DEFAULT_NATIVE_BROKER_HANDSHAKE_TIMEOUT_MS, performanceClient, correlationId);
if (platformAuthProvider) {
discoveryMeasurement.add({
platformAuthProviderType: PlatformAuthConstants.PLATFORM_EXTENSION_PROVIDER,
});
}
discoveryMeasurement.end({
success: !!platformAuthProvider,
platformAuthProviderType: platformAuthProvider
? PlatformAuthConstants.PLATFORM_EXTENSION_PROVIDER
: undefined,
});
}
catch (e) {
logger.trace("0icbd7", e);
discoveryMeasurement.end({
success: false,
}, e);
}
return platformAuthProvider;
}
/**
* Returns boolean indicating whether or not the request should attempt to use platform broker
* @param logger
* @param config
* @param correlationId
* @param platformAuthProvider
* @param authenticationScheme
*/
function isPlatformAuthAllowed(config, logger, correlationId, platformAuthProvider, authenticationScheme, performanceClient) {
logger.trace("0uko3r", correlationId);
const schemeSupported = !authenticationScheme ||
authenticationScheme === AuthenticationScheme.BEARER ||
authenticationScheme === AuthenticationScheme.POP;
const fields = {
allowPlatformBroker: config.system.allowPlatformBroker,
...(config.system.allowPlatformBroker && {
platformAuthProviderType: platformAuthProvider instanceof PlatformAuthDOMHandler
? PlatformAuthConstants.PLATFORM_DOM_PROVIDER
: platformAuthProvider
? PlatformAuthConstants.PLATFORM_EXTENSION_PROVIDER
: undefined,
}),
};
performanceClient?.addFields(fields, correlationId);
// throw an error if allowPlatformBroker is not enabled and allowPlatformBrokerWithDOM is enabled
if (!config.system.allowPlatformBroker &&
config.experimental.allowPlatformBrokerWithDOM) {
throw createClientConfigurationError(invalidPlatformBrokerConfiguration, "");
}
if (!config.system.allowPlatformBroker) {
logger.trace("04hozs", correlationId);
// Developer disabled WAM
return false;
}
if (!platformAuthProvider) {
logger.trace("0kvv1r", correlationId);
// Platform broker auth providers are not available
return false;
}
if (!schemeSupported) {
logger.trace("1dd2nh", correlationId);
return false;
}
logger.trace("18tev1", correlationId);
return true;
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class PopupClient extends StandardInteractionClient {
constructor(config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, performanceClient, nativeStorageImpl, correlationId, platformAuthHandler, waitForPopupResponseHook, tokenBindingKeyManager) {
super(config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, performanceClient, correlationId, platformAuthHandler, tokenBindingKeyManager);
this.nativeStorage = nativeStorageImpl;
this.eventHandler = eventHandler;
this.waitForPopupResponseHook = waitForPopupResponseHook;
}
/**
* Acquires tokens by opening a popup window to the /authorize endpoint of the authority
* @param request
* @param pkceCodes
*/
acquireToken(request, pkceCodes) {
let popupParams = undefined;
try {
const popupName = this.generatePopupName(request.scopes || OIDC_DEFAULT_SCOPES, request.authority || this.config.auth.authority);
popupParams = {
popupName,
popupWindowAttributes: request.popupWindowAttributes || {},
popupWindowParent: request.popupWindowParent ?? window,
};
this.performanceClient.addFields({ isAsyncPopup: !this.config.system.navigatePopups }, this.correlationId);
// navigatePopups flag is false. Acquires token without first opening popup. Popup will be opened later asynchronously.
if (!this.config.system.navigatePopups) {
this.logger.verbose("162h4u", this.correlationId);
// Passes on popup position and dimensions if in request
return this.acquireTokenPopupAsync(request, popupParams, pkceCodes);
}
else {
// navigatePopups flag is set to true. Opens popup before acquiring token.
// Pre-validate request method to avoid opening popup if the request is invalid
const validatedRequest = {
...request,
httpMethod: validateRequestMethod(request, this.config.system.protocolMode),
};
this.logger.verbose("1f9ok3", this.correlationId);
popupParams.popup = this.openSizedPopup("about:blank", popupParams);
return this.acquireTokenPopupAsync(validatedRequest, popupParams, pkceCodes);
}
}
catch (e) {
return Promise.reject(e);
}
}
/**
* Clears local cache for the current user then opens a popup window prompting the user to sign-out of the server
* @param logoutRequest
*/
logout(logoutRequest) {
try {
this.logger.verbose("068rup", this.correlationId);
const validLogoutRequest = this.initializeLogoutRequest(logoutRequest);
const popupParams = {
popupName: this.generateLogoutPopupName(validLogoutRequest),
popupWindowAttributes: logoutRequest?.popupWindowAttributes || {},
popupWindowParent: logoutRequest?.popupWindowParent ?? window,
};
const authority = logoutRequest && logoutRequest.authority;
const mainWindowRedirectUri = logoutRequest && logoutRequest.mainWindowRedirectUri;
// navigatePopups flag set to false. Acquires token without first opening popup. Popup will be opened later asynchronously.
if (!this.config.system.navigatePopups) {
this.logger.verbose("1phd8u", this.correlationId);
// Passes on popup position and dimensions if in request
return this.logoutPopupAsync(validLogoutRequest, popupParams, authority, mainWindowRedirectUri);
}
else {
// navigatePopups flag is set to true. Opens popup before logging out.
this.logger.verbose("1a28da", this.correlationId);
popupParams.popup = this.openSizedPopup("about:blank", popupParams);
return this.logoutPopupAsync(validLogoutRequest, popupParams, authority, mainWindowRedirectUri);
}
}
catch (e) {
// Since this function is synchronous we need to reject
return Promise.reject(e);
}
}
/**
* Helper which obtains an access_token for your API via opening a popup window in the user's browser
* @param request
* @param popupParams
* @param pkceCodes
*
* @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
*/
async acquireTokenPopupAsync(request, popupParams, pkceCodes) {
this.logger.verbose("1g77pg", this.correlationId);
const validRequest = await invokeAsync(initializeAuthorizationRequest, StandardInteractionClientInitializeAuthorizationRequest, this.logger, this.performanceClient, this.correlationId)(request, InteractionType.Popup, this.config, this.browserCrypto, this.browserStorage, this.logger, this.performanceClient, this.correlationId);
/*
* Skip pre-connect for async popups to reduce time between user interaction and popup window creation to avoid
* popup from being blocked by browsers with shorter popup timers
*/
if (popupParams.popup) {
preconnect(validRequest.authority);
}
const isPlatformBroker = isPlatformAuthAllowed(this.config, this.logger, this.correlationId, this.platformAuthProvider, request.authenticationScheme);
validRequest.platformBroker = isPlatformBroker;
if (this.config.system.protocolMode === ProtocolMode.EAR) {
return this.executeEarFlow(validRequest, popupParams, pkceCodes);
}
else {
return this.executeCodeFlow(validRequest, popupParams, pkceCodes);
}
}
/**
* Executes auth code + PKCE flow
* @param request
* @param popupParams
* @param pkceCodes
* @returns
*/
async executeCodeFlow(request, popupParams, pkceCodes) {
const correlationId = request.correlationId;
const serverTelemetryManager = initializeServerTelemetryManager(ApiId.acquireTokenPopup, this.config.auth.clientId, this.correlationId, this.browserStorage, this.logger, undefined, this.config.system.serverTelemetryEnabled);
const pkce = pkceCodes ||
(await invokeAsync(generatePkceCodes, GeneratePkceCodes, this.logger, this.performanceClient, correlationId)(this.performanceClient, this.logger, correlationId));
const tokenBindingParams = await getTokenBindingRequestParams(request, this.tokenBindingKeyManager, this.logger, this.performanceClient);
const popupRequest = {
...request,
codeChallenge: pkce.challenge,
...tokenBindingParams,
};
try {
// Initialize the client
const authClient = await invokeAsync(this.createAuthCodeClient.bind(this), StandardInteractionClientCreateAuthCodeClient, this.logger, this.performanceClient, correlationId)({
serverTelemetryManager,
requestAuthority: popupRequest.authority,
requestAzureCloudOptions: popupRequest.azureCloudOptions,
requestExtraQueryParameters: popupRequest.extraQueryParameters,
account: popupRequest.account,
});
if (popupRequest.httpMethod === HttpMethod$1.POST) {
return await this.executeCodeFlowWithPost(popupRequest, popupParams, authClient, pkce.verifier);
}
else {
// Create acquire token url.
const navigateUrl = await invokeAsync(getAuthCodeRequestUrl, GetAuthCodeUrl, this.logger, this.performanceClient, correlationId)(this.config, authClient.authority, popupRequest, this.logger, this.performanceClient);
/*
* When a popup-relay page is configured, open it top-level
* (same first-party origin) instead of navigating the popup
* straight to the IdP, and carry the /authorize URL in its hash.
* The relay page opens the IdP child popup and relays the
* response back via postMessage (see waitForPopupResponse).
*/
const popupRelayUri = this.config.auth.popupRelayUri;
const popupNavigateUrl = popupRelayUri
? buildPopupRelayUrl(popupRelayUri, this.getRelayStateId(request.state, correlationId), { method: "GET", url: navigateUrl }, correlationId)
: navigateUrl;
// Show the UI once the url has been created. Get the window handle for the popup.
const popupWindow = this.initiateAuthRequest(popupNavigateUrl, popupParams);
this.eventHandler.emitEvent(EventType.POPUP_OPENED, correlationId, InteractionType.Popup, { popupWindow }, null);
// Wait for the redirect bridge response
const responseString = await this.waitForPopupResponse(request, popupWindow, popupParams.popupWindowParent);
const serverParams = invoke(deserializeResponse, DeserializeResponse, this.logger, this.performanceClient, this.correlationId)(responseString, this.config.auth.OIDCOptions.responseMode, this.logger, this.correlationId);
return await invokeAsync(handleResponseCode, HandleResponseCode, this.logger, this.performanceClient, correlationId)(popupRequest, serverParams, pkce.verifier, ApiId.acquireTokenPopup, this.config, authClient, this.browserStorage, this.nativeStorage, this.eventHandler, this.logger, this.performanceClient, this.platformAuthProvider);
}
}
catch (e) {
// Close the synchronous popup if an error is thrown before the window unload event is registered
popupParams.popup?.close();
if (e instanceof AuthError) {
e.correlationId = this.correlationId;
serverTelemetryManager.cacheFailedRequest(e);
}
throw e;
}
}
/**
* Executes EAR flow
* @param request
*/
async executeEarFlow(request, popupParams, pkceCodes) {
const { correlationId, authority, azureCloudOptions, extraQueryParameters, account, } = request;
// Get the frame handle for the silent request
const discoveredAuthority = await invokeAsync(getDiscoveredAuthority, StandardInteractionClientGetDiscoveredAuthority, this.logger, this.performanceClient, correlationId)(this.config, this.correlationId, this.performanceClient, this.browserStorage, this.logger, authority, azureCloudOptions, extraQueryParameters, account);
const earJwk = await invokeAsync(generateEarKey, GenerateEarKey, this.logger, this.performanceClient, correlationId)();
const pkce = pkceCodes ||
(await invokeAsync(generatePkceCodes, GeneratePkceCodes, this.logger, this.performanceClient, correlationId)(this.performanceClient, this.logger, correlationId));
const tokenBindingParams = await getTokenBindingRequestParams(request, this.tokenBindingKeyManager, this.logger, this.performanceClient);
const popupRequest = {
...request,
earJwk: earJwk,
codeChallenge: pkce.challenge,
...tokenBindingParams,
};
const popupWindow = await this.openPostFormPopup(popupRequest, discoveredAuthority, popupParams, correlationId, true);
// Monitor the popup for the hash. Return the string value and close the popup when the hash is received. Default timeout is 60 seconds.
const responseString = await invokeAsync(this.waitForPopupResponse.bind(this), SilentHandlerMonitorIframeForHash, this.logger, this.performanceClient, correlationId)(popupRequest, popupWindow, popupParams.popupWindowParent);
const serverParams = invoke(deserializeResponse, DeserializeResponse, this.logger, this.performanceClient, this.correlationId)(responseString, this.config.auth.OIDCOptions.responseMode, this.logger, this.correlationId);
if (!serverParams.ear_jwe && serverParams.code) {
const authClient = await invokeAsync(this.createAuthCodeClient.bind(this), StandardInteractionClientCreateAuthCodeClient, this.logger, this.performanceClient, correlationId)({
serverTelemetryManager: initializeServerTelemetryManager(ApiId.acquireTokenPopup, this.config.auth.clientId, correlationId, this.browserStorage, this.logger, undefined, this.config.system.serverTelemetryEnabled),
requestAuthority: request.authority,
requestAzureCloudOptions: request.azureCloudOptions,
requestExtraQueryParameters: request.extraQueryParameters,
account: request.account,
authority: discoveredAuthority,
});
return invokeAsync(handleResponseCode, HandleResponseCode, this.logger, this.performanceClient, correlationId)(popupRequest, serverParams, pkce.verifier, ApiId.acquireTokenPopup, this.config, authClient, this.browserStorage, this.nativeStorage, this.eventHandler, this.logger, this.performanceClient, this.platformAuthProvider);
}
else {
return invokeAsync(handleResponseEAR, HandleResponseEar, this.logger, this.performanceClient, correlationId)(popupRequest, serverParams, ApiId.acquireTokenPopup, this.config, discoveredAuthority, this.browserStorage, this.nativeStorage, this.eventHandler, this.logger, this.performanceClient, this.platformAuthProvider);
}
}
async executeCodeFlowWithPost(request, popupParams, authClient, pkceVerifier) {
const correlationId = request.correlationId;
// Get the frame handle for the silent request
const discoveredAuthority = await invokeAsync(getDiscoveredAuthority, StandardInteractionClientGetDiscoveredAuthority, this.logger, this.performanceClient, correlationId)(this.config, this.correlationId, this.performanceClient, this.browserStorage, this.logger);
const popupWindow = await this.openPostFormPopup(request, discoveredAuthority, popupParams, correlationId, false);
// Monitor the popup for the hash. Return the string value and close the popup when the hash is received. Default timeout is 60 seconds.
const responseString = await invokeAsync(this.waitForPopupResponse.bind(this), SilentHandlerMonitorIframeForHash, this.logger, this.performanceClient, correlationId)(request, popupWindow, popupParams.popupWindowParent);
const serverParams = invoke(deserializeResponse, DeserializeResponse, this.logger, this.performanceClient, this.correlationId)(responseString, this.config.auth.OIDCOptions.responseMode, this.logger, this.correlationId);
return invokeAsync(handleResponseCode, HandleResponseCode, this.logger, this.performanceClient, correlationId)(request, serverParams, pkceVerifier, ApiId.acquireTokenPopup, this.config, authClient, this.browserStorage, this.nativeStorage, this.eventHandler, this.logger, this.performanceClient, this.platformAuthProvider);
}
/**
*
* @param validRequest
* @param popupName
* @param requestAuthority
* @param popup
* @param mainWindowRedirectUri
* @param popupWindowAttributes
*/
async logoutPopupAsync(validRequest, popupParams, requestAuthority, mainWindowRedirectUri) {
this.logger.verbose("0b7yrk", this.correlationId);
this.eventHandler.emitEvent(EventType.LOGOUT_START, this.correlationId, InteractionType.Popup, validRequest);
const serverTelemetryManager = initializeServerTelemetryManager(ApiId.logoutPopup, this.config.auth.clientId, this.correlationId, this.browserStorage, this.logger, undefined, this.config.system.serverTelemetryEnabled);
try {
// Clear cache on logout
await clearCacheOnLogout(this.browserStorage, this.browserCrypto, this.logger, this.correlationId, validRequest.account);
// Initialize the client
const authClient = await invokeAsync(this.createAuthCodeClient.bind(this), StandardInteractionClientCreateAuthCodeClient, this.logger, this.performanceClient, this.correlationId)({
serverTelemetryManager,
requestAuthority: requestAuthority,
account: validRequest.account || undefined,
});
try {
authClient.authority.endSessionEndpoint;
}
catch {
if (validRequest.account?.homeAccountId &&
validRequest.postLogoutRedirectUri &&
authClient.authority.protocolMode === ProtocolMode.OIDC) {
this.eventHandler.emitEvent(EventType.LOGOUT_SUCCESS, validRequest.correlationId, InteractionType.Popup, validRequest);
if (mainWindowRedirectUri) {
const navigationOptions = {
apiId: ApiId.logoutPopup,
timeout: this.config.system.redirectNavigationTimeout,
noHistory: false,
};
const absoluteUrl = UrlString.getAbsoluteUrl(mainWindowRedirectUri, getCurrentUri(), this.correlationId);
await this.navigationClient.navigateInternal(absoluteUrl, navigationOptions);
}
popupParams.popup?.close();
return;
}
}
// Redirect bridge requires "state" param to work properly
validRequest.state = setRequestState(this.browserCrypto, validRequest.state || "", {
interactionType: InteractionType.Popup,
}, validRequest.correlationId);
// Create logout string and navigate user window to logout.
const logoutUri = authClient.getLogoutUri(validRequest);
this.eventHandler.emitEvent(EventType.LOGOUT_SUCCESS, validRequest.correlationId, InteractionType.Popup, validRequest);
/*
* When a popup-relay page is configured, open it top-level (same
* first-party origin) and carry the end-session URL in its hash,
* exactly like the login flow. The relay page opens the IdP child
* popup and the post-logout redirect page (running the redirect
* bridge) relays completion back via postMessage — so logout works
* from an embedded, cross-origin iframe where a direct popup to the
* IdP cannot. See runPopupRelay / waitForPopupResponse.
*/
const popupRelayUri = this.config.auth.popupRelayUri;
const popupNavigateUrl = popupRelayUri
? buildPopupRelayUrl(popupRelayUri, this.getRelayStateId(validRequest.state || "", this.correlationId), { method: "GET", url: logoutUri }, this.correlationId)
: logoutUri;
// Open the popup window to requestUrl.
const popupWindow = this.openPopup(popupNavigateUrl, popupParams);
this.eventHandler.emitEvent(EventType.POPUP_OPENED, validRequest.correlationId, InteractionType.Popup, { popupWindow }, null);
await this.waitForPopupResponse(validRequest, popupWindow, popupParams.popupWindowParent).catch(() => {
// Swallow any errors related to monitoring the window. Server logout is best effort
});
if (mainWindowRedirectUri) {
const navigationOptions = {
apiId: ApiId.logoutPopup,
timeout: this.config.system.redirectNavigationTimeout,
noHistory: false,
};
const absoluteUrl = UrlString.getAbsoluteUrl(mainWindowRedirectUri, getCurrentUri(), this.correlationId);
this.logger.verbose("0qcur2", this.correlationId);
this.logger.verbosePii(`0oj7lk ${absoluteUrl}`, this.correlationId);
await this.navigationClient.navigateInternal(absoluteUrl, navigationOptions);
}
else {
this.logger.verbose("03zgcf", this.correlationId);
}
}
catch (e) {
// Close the synchronous popup if an error is thrown before the window unload event is registered
popupParams.popup?.close();
if (e instanceof AuthError) {
e.correlationId = this.correlationId;
serverTelemetryManager.cacheFailedRequest(e);
}
this.eventHandler.emitEvent(EventType.LOGOUT_FAILURE, this.correlationId, InteractionType.Popup, null, e);
this.eventHandler.emitEvent(EventType.LOGOUT_END, this.correlationId, InteractionType.Popup);
throw e;
}
this.eventHandler.emitEvent(EventType.LOGOUT_END, this.correlationId, InteractionType.Popup);
}
/**
* Opens a popup window with given request Url.
* @param requestUrl
*/
initiateAuthRequest(requestUrl, params) {
// Check that request url is not empty.
if (requestUrl) {
this.logger.infoPii(`1kcr9k ${requestUrl}`, this.correlationId);
// Open the popup window to requestUrl.
return this.openPopup(requestUrl, params);
}
else {
// Throw error if request URL is empty.
this.logger.error("1l7hyp", this.correlationId);
throw createBrowserAuthError(emptyNavigateUri, this.correlationId);
}
}
/**
* @hidden
*
* Configures popup window for login.
*
* @param urlNavigate
* @param title
* @param popUpWidth
* @param popUpHeight
* @param popupWindowAttributes
* @ignore
* @hidden
*/
openPopup(urlNavigate, popupParams) {
try {
let popupWindow;
// Popup window passed in, setting url to navigate to
if (popupParams.popup) {
popupWindow = popupParams.popup;
this.logger.verbosePii(`0cgeo7 ${urlNavigate}`, this.correlationId);
popupWindow.location.assign(urlNavigate);
}
else if (typeof popupParams.popup === "undefined") {
// Popup will be undefined if it was not passed in
this.logger.verbosePii(`0c2awd ${urlNavigate}`, this.correlationId);
popupWindow = this.openSizedPopup(urlNavigate, popupParams);
}
// Popup will be null if popups are blocked
if (!popupWindow) {
throw createBrowserAuthError(emptyWindowError, this.correlationId);
}
try {
popupWindow.document.title = "Microsoft Authentication";
}
catch (e) {
if (typeof DOMException !== "undefined" &&
e instanceof DOMException &&
e.name === "SecurityError") {
// Cross-origin - title cannot be set
}
else {
this.logger.verbose("1s1yfs", this.correlationId);
}
}
if (popupWindow.focus) {
popupWindow.focus();
}
this.currentWindow = popupWindow;
return popupWindow;
}
catch (e) {
this.logger.error(`0dxfb9 ${e.message}`, this.correlationId);
throw createBrowserAuthError(popupWindowError, this.correlationId);
}
}
/**
* Helper function to set popup window dimensions and position
* @param urlNavigate
* @param popupName
* @param popupWindowAttributes
* @returns
*/
openSizedPopup(urlNavigate, { popupName, popupWindowAttributes, popupWindowParent }) {
/**
* adding winLeft and winTop to account for dual monitor
* using screenLeft and screenTop for IE8 and earlier
*/
const winLeft = popupWindowParent.screenLeft
? popupWindowParent.screenLeft
: popupWindowParent.screenX;
const winTop = popupWindowParent.screenTop
? popupWindowParent.screenTop
: popupWindowParent.screenY;
/**
* window.innerWidth displays browser window"s height and width excluding toolbars
* using document.documentElement.clientWidth for IE8 and earlier
*/
const winWidth = popupWindowParent.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth;
const winHeight = popupWindowParent.innerHeight ||
document.documentElement.clientHeight ||
document.body.clientHeight;
let width = popupWindowAttributes.popupSize?.width;
let height = popupWindowAttributes.popupSize?.height;
let top = popupWindowAttributes.popupPosition?.top;
let left = popupWindowAttributes.popupPosition?.left;
if (!width || width < 0 || width > winWidth) {
this.logger.verbose("08vfmo", this.correlationId);
width = BrowserConstants.POPUP_WIDTH;
}
if (!height || height < 0 || height > winHeight) {
this.logger.verbose("09cxa0", this.correlationId);
height = BrowserConstants.POPUP_HEIGHT;
}
if (!top || top < 0 || top > winHeight) {
this.logger.verbose("1qh4wo", this.correlationId);
top = Math.max(0, winHeight / 2 - BrowserConstants.POPUP_HEIGHT / 2 + winTop);
}
if (!left || left < 0 || left > winWidth) {
this.logger.verbose("1sz3en", this.correlationId);
left = Math.max(0, winWidth / 2 - BrowserConstants.POPUP_WIDTH / 2 + winLeft);
}
return popupWindowParent.open(urlNavigate, popupName, `width=${width}, height=${height}, top=${top}, left=${left}, scrollbars=yes`);
}
/**
* Generates the name for the popup based on the client id and request
* @param clientId
* @param request
*/
generatePopupName(scopes, authority) {
return `${BrowserConstants.POPUP_NAME_PREFIX}.${this.config.auth.clientId}.${scopes.join("-")}.${authority}.${this.correlationId}`;
}
/**
* Generates the name for the popup based on the client id and request for logouts
* @param clientId
* @param request
*/
generateLogoutPopupName(request) {
const homeAccountId = request.account && request.account.homeAccountId;
return `${BrowserConstants.POPUP_NAME_PREFIX}.${this.config.auth.clientId}.${homeAccountId}.${this.correlationId}`;
}
/**
* Decodes the per-request library-state id from the encoded request state.
*/
getRelayStateId(state, correlationId) {
return parseRequestState(base64Decode, state, correlationId).libraryState.id;
}
/**
* Opens the interactive popup for a POST-form /authorize request. Shared by
* the auth-code POST and EAR flows, which are identical apart from the form
* builder (`isEAR` selects the EAR vs auth-code builders). When a
* popup-relay page is configured the form is carried to the relay page
* (which opens the IdP child popup); otherwise the form is submitted
* directly into the popup.
*/
async openPostFormPopup(request, discoveredAuthority, popupParams, correlationId, isEAR) {
const popupRelayUri = this.config.auth.popupRelayUri;
if (popupRelayUri) {
const getFormData = isEAR
? getEARFormData
: getCodeFormData;
const formData = await getFormData(this.config, discoveredAuthority, request, this.logger, this.performanceClient);
const relayUrl = buildPopupRelayUrl(popupRelayUri, this.getRelayStateId(request.state, correlationId), {
method: "POST",
action: formData.action,
fields: formData.fields,
}, correlationId);
return this.initiateAuthRequest(relayUrl, popupParams);
}
const popupWindow = popupParams.popup || this.openPopup("about:blank", popupParams);
const getForm = isEAR ? getEARForm : getCodeForm;
const form = await getForm(popupWindow.document, this.config, discoveredAuthority, request, this.logger, this.performanceClient);
form.submit();
return popupWindow;
}
async waitForPopupResponse(request, popupWindow, popupWindowParent) {
/*
* When a popup-relay page is configured the response is relayed back to
* this frame by the relay page via postMessage, and the relay popup's
* lifecycle (including the user dismissing it before signing in) must be
* tracked here. This takes precedence over the default bridge response
* hook, whose BroadcastChannel cannot reach a partitioned cross-site
* frame and which does not track the relay popup.
*/
if (this.config.auth.popupRelayUri) {
return waitForPopupRelayResponse(this.config.system.popupBridgeTimeout, this.logger, request, popupWindow, this.performanceClient);
}
if (this.waitForPopupResponseHook) {
return this.waitForPopupResponseHook(request, popupWindow, popupWindowParent);
}
return waitForBridgeResponse(this.config.system.popupBridgeTimeout, this.logger, request, this.performanceClient);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
function getNavigationType() {
if (typeof window === "undefined" ||
typeof window.performance === "undefined" ||
typeof window.performance.getEntriesByType !== "function") {
return undefined;
}
const navigationEntries = window.performance.getEntriesByType("navigation");
const navigation = navigationEntries.length
? navigationEntries[0]
: undefined;
return navigation?.type;
}
class RedirectClient extends StandardInteractionClient {
constructor(config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, performanceClient, nativeStorageImpl, correlationId, platformAuthHandler, tokenBindingKeyManager) {
super(config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, performanceClient, correlationId, platformAuthHandler, tokenBindingKeyManager);
this.nativeStorage = nativeStorageImpl;
}
/**
* Redirects the page to the /authorize endpoint of the IDP
* @param request
*/
async acquireToken(request) {
const validRequest = await invokeAsync(initializeAuthorizationRequest, StandardInteractionClientInitializeAuthorizationRequest, this.logger, this.performanceClient, this.correlationId)(request, InteractionType.Redirect, this.config, this.browserCrypto, this.browserStorage, this.logger, this.performanceClient, this.correlationId);
validRequest.platformBroker = isPlatformAuthAllowed(this.config, this.logger, this.correlationId, this.platformAuthProvider, request.authenticationScheme);
let rejectBackButtonCancellation;
const backButtonCancellation = new Promise((_, reject) => {
rejectBackButtonCancellation = reject;
});
const handleBackButton = (event) => {
// Clear temporary cache if the back button is clicked during the redirect flow.
if (event.persisted) {
this.logger.verbose("0udvtt", this.correlationId);
this.browserStorage.resetRequestCache(this.correlationId);
this.eventHandler.emitEvent(EventType.RESTORE_FROM_BFCACHE, this.correlationId, InteractionType.Redirect);
rejectBackButtonCancellation(createBrowserAuthError(userCancelled, this.correlationId));
}
};
const redirectStartPage = this.getRedirectStartPage(request.redirectStartPage);
this.logger.verbosePii(`0zao0a ${redirectStartPage}`, this.correlationId);
// Cache start page, returns to this page after redirectUri if navigateToLoginRequestUrl is true
this.browserStorage.setTemporaryCache(TemporaryCacheKeys.ORIGIN_URI, redirectStartPage, true);
// Clear temporary cache if the back button is clicked during the redirect flow.
window.addEventListener("pageshow", handleBackButton);
try {
const redirectOperation = this.config.system.protocolMode === ProtocolMode.EAR
? this.executeEarFlow(validRequest)
: this.executeCodeFlow(validRequest);
await Promise.race([redirectOperation, backButtonCancellation]);
}
catch (e) {
if (e instanceof AuthError) {
e.correlationId = this.correlationId;
}
window.removeEventListener("pageshow", handleBackButton);
throw e;
}
}
/**
* Executes auth code + PKCE flow
* @param request
* @returns
*/
async executeCodeFlow(request) {
const correlationId = request.correlationId;
const serverTelemetryManager = initializeServerTelemetryManager(ApiId.acquireTokenRedirect, this.config.auth.clientId, this.correlationId, this.browserStorage, this.logger, undefined, this.config.system.serverTelemetryEnabled);
const pkceCodes = await invokeAsync(generatePkceCodes, GeneratePkceCodes, this.logger, this.performanceClient, correlationId)(this.performanceClient, this.logger, correlationId);
const tokenBindingParams = await getTokenBindingRequestParams(request, this.tokenBindingKeyManager, this.logger, this.performanceClient);
const redirectRequest = {
...request,
codeChallenge: pkceCodes.challenge,
...tokenBindingParams,
};
this.browserStorage.cacheAuthorizeRequest(redirectRequest, this.correlationId, pkceCodes.verifier);
try {
if (redirectRequest.httpMethod === HttpMethod$1.POST) {
return await this.executeCodeFlowWithPost(redirectRequest);
}
else {
// Initialize the client
const authClient = await invokeAsync(this.createAuthCodeClient.bind(this), StandardInteractionClientCreateAuthCodeClient, this.logger, this.performanceClient, this.correlationId)({
serverTelemetryManager,
requestAuthority: redirectRequest.authority,
requestAzureCloudOptions: redirectRequest.azureCloudOptions,
requestExtraQueryParameters: redirectRequest.extraQueryParameters,
account: redirectRequest.account,
});
// Create acquire token url.
const navigateUrl = await invokeAsync(getAuthCodeRequestUrl, GetAuthCodeUrl, this.logger, this.performanceClient, request.correlationId)(this.config, authClient.authority, redirectRequest, this.logger, this.performanceClient);
// Show the UI once the url has been created. Response will come back in the hash, which will be handled in the handleRedirectCallback function.
return await this.initiateAuthRequest(navigateUrl);
}
}
catch (e) {
if (e instanceof AuthError) {
e.correlationId = this.correlationId;
serverTelemetryManager.cacheFailedRequest(e);
}
throw e;
}
}
/**
* Executes EAR flow
* @param request
*/
async executeEarFlow(request) {
const { correlationId, authority, azureCloudOptions, extraQueryParameters, account, } = request;
// Get the frame handle for the silent request
const discoveredAuthority = await invokeAsync(getDiscoveredAuthority, StandardInteractionClientGetDiscoveredAuthority, this.logger, this.performanceClient, correlationId)(this.config, this.correlationId, this.performanceClient, this.browserStorage, this.logger, authority, azureCloudOptions, extraQueryParameters, account);
const earJwk = await invokeAsync(generateEarKey, GenerateEarKey, this.logger, this.performanceClient, correlationId)();
const pkceCodes = await invokeAsync(generatePkceCodes, GeneratePkceCodes, this.logger, this.performanceClient, correlationId)(this.performanceClient, this.logger, correlationId);
const tokenBindingParams = await getTokenBindingRequestParams(request, this.tokenBindingKeyManager, this.logger, this.performanceClient);
const redirectRequest = {
...request,
earJwk: earJwk,
codeChallenge: pkceCodes.challenge,
...tokenBindingParams,
};
this.browserStorage.cacheAuthorizeRequest(redirectRequest, this.correlationId, pkceCodes.verifier);
const form = await getEARForm(document, this.config, discoveredAuthority, redirectRequest, this.logger, this.performanceClient);
form.submit();
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(createBrowserAuthError(timedOut, "", "failed_to_redirect"));
}, this.config.system.redirectNavigationTimeout);
});
}
/**
* Executes classic Authorization Code flow with a POST request.
* @param request
*/
async executeCodeFlowWithPost(request) {
const correlationId = request.correlationId;
// Get the frame handle for the silent request
const discoveredAuthority = await invokeAsync(getDiscoveredAuthority, StandardInteractionClientGetDiscoveredAuthority, this.logger, this.performanceClient, correlationId)(this.config, this.correlationId, this.performanceClient, this.browserStorage, this.logger);
this.browserStorage.cacheAuthorizeRequest(request, this.correlationId);
const form = await getCodeForm(document, this.config, discoveredAuthority, request, this.logger, this.performanceClient);
form.submit();
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(createBrowserAuthError(timedOut, "", "failed_to_redirect"));
}, this.config.system.redirectNavigationTimeout);
});
}
/**
* Checks if navigateToLoginRequestUrl is set, and:
* - if true, performs logic to cache and navigate
* - if false, handles hash string and parses response
* @param hash {string} url hash
* @param parentMeasurement {InProgressPerformanceEvent} parent measurement
* @param request {CommonAuthorizationUrlRequest} request object
* @param pkceVerifier {string} PKCE verifier
* @param options {HandleRedirectPromiseOptions} options for handling redirect promise
*/
async handleRedirectPromise(request, pkceVerifier, parentMeasurement, options) {
const originalTitle = document.title;
document.title = "Microsoft Authentication";
const serverTelemetryManager = initializeServerTelemetryManager(ApiId.handleRedirectPromise, this.config.auth.clientId, this.correlationId, this.browserStorage, this.logger, undefined, this.config.system.serverTelemetryEnabled);
const navigateToLoginRequestUrl = options?.navigateToLoginRequestUrl ?? true;
try {
const [serverParams, responseString] = this.getRedirectResponse(options?.hash || "");
if (!serverParams) {
// Not a recognized server response hash or hash not associated with a redirect request
this.logger.info("1qmv0q", this.correlationId);
this.browserStorage.resetRequestCache(this.correlationId);
// Do not instrument "no_server_response" if user clicked back button
if (getNavigationType() !== "back_forward") {
parentMeasurement.event.errorCode = "no_server_response";
}
else {
this.logger.verbose("1eqegq", this.correlationId);
}
return null;
}
// If navigateToLoginRequestUrl is true, get the url where the redirect request was initiated
const loginRequestUrl = this.browserStorage.getTemporaryCache(TemporaryCacheKeys.ORIGIN_URI, this.correlationId, true) || "";
const loginRequestUrlNormalized = normalizeUrlForComparison(loginRequestUrl, this.logger, this.correlationId);
const currentUrlNormalized = normalizeUrlForComparison(window.location.href, this.logger, this.correlationId);
if (loginRequestUrlNormalized === currentUrlNormalized &&
navigateToLoginRequestUrl) {
// We are on the page we need to navigate to - handle hash
this.logger.verbose("11yred", this.correlationId);
if (loginRequestUrl.indexOf("#") > -1) {
// Replace current hash with non-msal hash, if present
replaceHash(loginRequestUrl);
}
const handleHashResult = await this.handleResponse(serverParams, request, pkceVerifier, serverTelemetryManager);
return handleHashResult;
}
else if (!navigateToLoginRequestUrl) {
this.logger.verbose("0v4sdv", this.correlationId);
return await this.handleResponse(serverParams, request, pkceVerifier, serverTelemetryManager);
}
else if (!isInIframe() ||
this.config.system.allowRedirectInIframe) {
/*
* Returned from authority using redirect - need to perform navigation before processing response
* Cache the hash to be retrieved after the next redirect
*/
this.browserStorage.setTemporaryCache(TemporaryCacheKeys.URL_HASH, responseString, true);
const navigationOptions = {
apiId: ApiId.handleRedirectPromise,
timeout: this.config.system.redirectNavigationTimeout,
noHistory: true,
};
/**
* Default behavior is to redirect to the start page and not process the hash now.
* The start page is expected to also call handleRedirectPromise which will process the hash in one of the checks above.
*/
let processHashOnRedirect = true;
if (!loginRequestUrl) {
// Redirect to home page if login request url is empty
const homepage = getHomepage(this.correlationId);
// Cache the homepage under ORIGIN_URI to ensure cached hash is processed on homepage
this.browserStorage.setTemporaryCache(TemporaryCacheKeys.ORIGIN_URI, homepage, true);
this.logger.warning("1dutq1", this.correlationId);
processHashOnRedirect =
await this.navigationClient.navigateInternal(homepage, navigationOptions);
}
else {
// Navigate to page that initiated the redirect request
this.logger.verbose(`08jpy1 ${loginRequestUrl}`, this.correlationId);
processHashOnRedirect =
await this.navigationClient.navigateInternal(loginRequestUrl, navigationOptions);
}
// If navigateInternal implementation returns false, handle the hash now
if (!processHashOnRedirect) {
return await this.handleResponse(serverParams, request, pkceVerifier, serverTelemetryManager);
}
}
return null;
}
catch (e) {
if (e instanceof AuthError) {
e.correlationId = this.correlationId;
serverTelemetryManager.cacheFailedRequest(e);
}
throw e;
}
finally {
document.title = originalTitle;
}
}
/**
* Gets the response hash for a redirect request
* Returns null if interactionType in the state value is not "redirect" or the hash does not contain known properties
* @param hash
*/
getRedirectResponse(userProvidedResponse) {
this.logger.verbose("1c5i8m", this.correlationId);
// Get current location hash from window or cache.
let responseString = userProvidedResponse;
if (!responseString) {
if (this.config.auth.OIDCOptions.responseMode ===
ResponseMode.QUERY) {
responseString = window.location.search;
}
else {
responseString = window.location.hash;
}
}
let response = getDeserializedResponse(responseString);
if (response) {
try {
validateInteractionType(response, this.browserCrypto, InteractionType.Redirect, this.correlationId);
}
catch (e) {
if (e instanceof AuthError) {
this.logger.error(`0bkq6p ${e.errorCode} ${e.errorMessage}`, this.correlationId);
}
return [null, ""];
}
clearHash(window);
this.logger.verbose("00uvho", this.correlationId);
return [response, responseString];
}
const cachedHash = this.browserStorage.getTemporaryCache(TemporaryCacheKeys.URL_HASH, this.correlationId, true);
this.browserStorage.removeItem(this.browserStorage.generateCacheKey(TemporaryCacheKeys.URL_HASH));
if (cachedHash) {
response = getDeserializedResponse(cachedHash);
if (response) {
this.logger.verbose("001671", this.correlationId);
return [response, cachedHash];
}
}
return [null, ""];
}
/**
* Checks if hash exists and handles in window.
* @param hash
* @param state
*/
async handleResponse(serverParams, request, codeVerifier, serverTelemetryManager) {
const state = serverParams.state;
if (!state) {
throw createBrowserAuthError(noStateInHash, request.correlationId);
}
const { authority, azureCloudOptions, extraQueryParameters, account } = request;
if (serverParams.ear_jwe) {
const discoveredAuthority = await invokeAsync(getDiscoveredAuthority, StandardInteractionClientGetDiscoveredAuthority, this.logger, this.performanceClient, request.correlationId)(this.config, this.correlationId, this.performanceClient, this.browserStorage, this.logger, authority, azureCloudOptions, extraQueryParameters, account);
return invokeAsync(handleResponseEAR, HandleResponseEar, this.logger, this.performanceClient, request.correlationId)(request, serverParams, ApiId.acquireTokenRedirect, this.config, discoveredAuthority, this.browserStorage, this.nativeStorage, this.eventHandler, this.logger, this.performanceClient, this.platformAuthProvider);
}
const authClient = await invokeAsync(this.createAuthCodeClient.bind(this), StandardInteractionClientCreateAuthCodeClient, this.logger, this.performanceClient, this.correlationId)({ serverTelemetryManager, requestAuthority: request.authority });
return invokeAsync(handleResponseCode, HandleResponseCode, this.logger, this.performanceClient, request.correlationId)(request, serverParams, codeVerifier, ApiId.acquireTokenRedirect, this.config, authClient, this.browserStorage, this.nativeStorage, this.eventHandler, this.logger, this.performanceClient, this.platformAuthProvider);
}
/**
* Redirects window to given URL.
* @param urlNavigate
* @param onRedirectNavigateRequest - onRedirectNavigate callback provided on the request
*/
async initiateAuthRequest(requestUrl) {
this.logger.verbose("0yaw2e", this.correlationId);
// Navigate if valid URL
if (requestUrl) {
this.logger.infoPii(`1luf83 ${requestUrl}`, this.correlationId);
const navigationOptions = {
apiId: ApiId.acquireTokenRedirect,
timeout: this.config.system.redirectNavigationTimeout,
noHistory: false,
};
const onRedirectNavigate = this.config.auth.onRedirectNavigate;
// If onRedirectNavigate is implemented, invoke it and provide requestUrl
if (typeof onRedirectNavigate === "function") {
this.logger.verbose("1nehvl", this.correlationId);
const navigate = onRedirectNavigate(requestUrl);
// Returning false from onRedirectNavigate will stop navigation
if (navigate !== false) {
this.logger.verbose("1a0jxh", this.correlationId);
await this.navigationClient.navigateExternal(requestUrl, navigationOptions);
return;
}
else {
this.logger.verbose("09k5h5", this.correlationId);
return;
}
}
else {
// Navigate window to request URL
this.logger.verbose("0klwf7", this.correlationId);
await this.navigationClient.navigateExternal(requestUrl, navigationOptions);
return;
}
}
else {
// Throw error if request URL is empty.
this.logger.info("0rlh4e", this.correlationId);
throw createBrowserAuthError(emptyNavigateUri, this.correlationId);
}
}
/**
* Use to log out the current user, and redirect the user to the postLogoutRedirectUri.
* Default behaviour is to redirect the user to `window.location.href`.
* @param logoutRequest
*/
async logout(logoutRequest) {
this.logger.verbose("1rkurh", this.correlationId);
const validLogoutRequest = this.initializeLogoutRequest(logoutRequest);
const serverTelemetryManager = initializeServerTelemetryManager(ApiId.logout, this.config.auth.clientId, this.correlationId, this.browserStorage, this.logger, undefined, this.config.system.serverTelemetryEnabled);
try {
this.eventHandler.emitEvent(EventType.LOGOUT_START, this.correlationId, InteractionType.Redirect, logoutRequest);
// Clear cache on logout
await clearCacheOnLogout(this.browserStorage, this.browserCrypto, this.logger, this.correlationId, validLogoutRequest.account);
const navigationOptions = {
apiId: ApiId.logout,
timeout: this.config.system.redirectNavigationTimeout,
noHistory: false,
};
const authClient = await invokeAsync(this.createAuthCodeClient.bind(this), StandardInteractionClientCreateAuthCodeClient, this.logger, this.performanceClient, this.correlationId)({
serverTelemetryManager,
requestAuthority: logoutRequest && logoutRequest.authority,
requestExtraQueryParameters: logoutRequest?.extraQueryParameters,
account: (logoutRequest && logoutRequest.account) || undefined,
});
if (authClient.authority.protocolMode === ProtocolMode.OIDC) {
try {
authClient.authority.endSessionEndpoint;
}
catch {
if (validLogoutRequest.account?.homeAccountId) {
this.eventHandler.emitEvent(EventType.LOGOUT_SUCCESS, this.correlationId, InteractionType.Redirect, validLogoutRequest);
return;
}
}
}
// Redirect bridge requires "state" param to work properly
validLogoutRequest.state = setRequestState(this.browserCrypto, validLogoutRequest.state || "", {
interactionType: InteractionType.Redirect,
}, validLogoutRequest.correlationId);
// Create logout string and navigate user window to logout.
const logoutUri = authClient.getLogoutUri(validLogoutRequest);
if (validLogoutRequest.account?.homeAccountId) {
this.eventHandler.emitEvent(EventType.LOGOUT_SUCCESS, this.correlationId, InteractionType.Redirect, validLogoutRequest);
}
// Check if onRedirectNavigate is implemented, and invoke it if so
const onRedirectNavigate = this.config.auth.onRedirectNavigate;
if (typeof onRedirectNavigate === "function") {
const navigate = onRedirectNavigate(logoutUri);
if (navigate !== false) {
this.logger.verbose("06v57e", this.correlationId);
// Ensure interaction is in progress
if (!this.browserStorage.getInteractionInProgress()) {
this.browserStorage.setInteractionInProgress(true, INTERACTION_TYPE.SIGNOUT);
}
await this.navigationClient.navigateExternal(logoutUri, navigationOptions);
return;
}
else {
// Ensure interaction is not in progress
this.browserStorage.setInteractionInProgress(false);
this.logger.verbose("0xqes1", this.correlationId);
}
}
else {
// Ensure interaction is in progress
if (!this.browserStorage.getInteractionInProgress()) {
this.browserStorage.setInteractionInProgress(true, INTERACTION_TYPE.SIGNOUT);
}
await this.navigationClient.navigateExternal(logoutUri, navigationOptions);
return;
}
}
catch (e) {
if (e instanceof AuthError) {
e.correlationId = this.correlationId;
serverTelemetryManager.cacheFailedRequest(e);
}
this.eventHandler.emitEvent(EventType.LOGOUT_FAILURE, this.correlationId, InteractionType.Redirect, null, e);
this.eventHandler.emitEvent(EventType.LOGOUT_END, this.correlationId, InteractionType.Redirect);
throw e;
}
this.eventHandler.emitEvent(EventType.LOGOUT_END, this.correlationId, InteractionType.Redirect);
}
/**
* Use to get the redirectStartPage either from request or use current window
* @param requestStartPage
*/
getRedirectStartPage(requestStartPage) {
const redirectStartPage = requestStartPage || window.location.href;
const absoluteRedirectStartPage = UrlString.getAbsoluteUrl(redirectStartPage, getCurrentUri(), this.correlationId);
// Sanity check the URL before it is cached so we never persist a malformed value (e.g. the literal string "null")
validateUrl(absoluteRedirectStartPage, this.logger, this.correlationId);
return absoluteRedirectStartPage;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Navigates the given hidden iframe to the provided URL.
* @param frame
* @param requestUrl
*/
async function initiateCodeRequest(frame, requestUrl, logger, correlationId) {
if (!requestUrl) {
// Throw error if request URL is empty.
logger.info("1l7hyp", correlationId);
throw createBrowserAuthError(emptyNavigateUri, correlationId);
}
frame.src = requestUrl;
return frame;
}
async function initiateCodeFlowWithPost(frame, config, authority, request, logger, performanceClient) {
if (!frame.contentDocument) {
throw "No document associated with iframe!";
}
const form = await getCodeForm(frame.contentDocument, config, authority, request, logger, performanceClient);
form.submit();
return frame;
}
async function initiateEarRequest(frame, config, authority, request, logger, performanceClient) {
if (!frame.contentDocument) {
throw "No document associated with iframe!";
}
const form = await getEARForm(frame.contentDocument, config, authority, request, logger, performanceClient);
form.submit();
return frame;
}
/**
* @hidden
* Creates a new hidden iframe for silent token renewal. Callers navigate it
* (set `src` or submit a form) after registering the response listener.
* @ignore
*/
function createHiddenIframe() {
const authFrame = document.createElement("iframe");
authFrame.className = "msalSilentIframe";
authFrame.title = "Microsoft Authentication";
authFrame.style.visibility = "hidden";
authFrame.style.position = "absolute";
authFrame.style.width = authFrame.style.height = "0";
authFrame.style.border = "0";
authFrame.setAttribute("sandbox", "allow-scripts allow-same-origin allow-forms");
authFrame.setAttribute("allow", "local-network-access *");
document.body.appendChild(authFrame);
return authFrame;
}
/**
* @hidden
* Removes a hidden iframe from `document.body` if it is a direct child.
* @param iframe - The iframe element to remove.
*/
function removeHiddenIframe(iframe) {
if (document.body === iframe.parentNode) {
document.body.removeChild(iframe);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class SilentIframeClient extends StandardInteractionClient {
constructor(config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, apiId, performanceClient, nativeStorageImpl, correlationId, platformAuthProvider, waitForIframeResponseHook, tokenBindingKeyManager) {
super(config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, performanceClient, correlationId, platformAuthProvider, tokenBindingKeyManager);
this.apiId = apiId;
this.nativeStorage = nativeStorageImpl;
this.waitForIframeResponseHook = waitForIframeResponseHook;
}
/**
* Acquires a token silently by opening a hidden iframe to the /authorize endpoint with prompt=none or prompt=no_session
* @param request
*/
async acquireToken(request) {
// Check that we have some SSO data
if (!request.loginHint &&
!request.sid &&
(!request.account || !request.account.username)) {
this.logger.warning("1kl318", this.correlationId);
}
// Check the prompt value
const inputRequest = { ...request };
if (inputRequest.prompt) {
if (inputRequest.prompt !== PromptValue.NONE &&
inputRequest.prompt !== PromptValue.NO_SESSION) {
this.logger.warning(`0bmctg ${inputRequest.prompt} ${PromptValue.NONE}`, this.correlationId);
inputRequest.prompt = PromptValue.NONE;
}
}
else {
inputRequest.prompt = PromptValue.NONE;
}
// Create silent request
const silentRequest = await invokeAsync(initializeAuthorizationRequest, StandardInteractionClientInitializeAuthorizationRequest, this.logger, this.performanceClient, this.correlationId)(inputRequest, InteractionType.Silent, this.config, this.browserCrypto, this.browserStorage, this.logger, this.performanceClient, this.correlationId);
silentRequest.platformBroker = isPlatformAuthAllowed(this.config, this.logger, this.correlationId, this.platformAuthProvider, silentRequest.authenticationScheme);
preconnect(silentRequest.authority);
if (this.config.system.protocolMode === ProtocolMode.EAR) {
return this.executeEarFlow(silentRequest);
}
else {
return this.executeCodeFlow(silentRequest);
}
}
/**
* Executes auth code + PKCE flow
* @param request
* @returns
*/
async executeCodeFlow(request) {
let authClient;
const serverTelemetryManager = initializeServerTelemetryManager(this.apiId, this.config.auth.clientId, this.correlationId, this.browserStorage, this.logger, undefined, this.config.system.serverTelemetryEnabled);
try {
// Initialize the client
authClient = await invokeAsync(this.createAuthCodeClient.bind(this), StandardInteractionClientCreateAuthCodeClient, this.logger, this.performanceClient, request.correlationId)({
serverTelemetryManager,
requestAuthority: request.authority,
requestAzureCloudOptions: request.azureCloudOptions,
requestExtraQueryParameters: request.extraQueryParameters,
account: request.account,
});
return await invokeAsync(this.silentTokenHelper.bind(this), SilentIframeClientTokenHelper, this.logger, this.performanceClient, request.correlationId)(authClient, request);
}
catch (e) {
if (e instanceof AuthError) {
e.correlationId = this.correlationId;
serverTelemetryManager.cacheFailedRequest(e);
}
if (!authClient ||
!(e instanceof AuthError) ||
e.errorCode !== BrowserConstants.INVALID_GRANT_ERROR) {
throw e;
}
this.performanceClient.addFields({
retryError: e.errorCode,
}, this.correlationId);
return await invokeAsync(this.silentTokenHelper.bind(this), SilentIframeClientTokenHelper, this.logger, this.performanceClient, this.correlationId)(authClient, request);
}
}
/**
* Executes EAR flow
* @param request
*/
async executeEarFlow(request) {
const { correlationId, authority, azureCloudOptions, extraQueryParameters, account, } = request;
const discoveredAuthority = await invokeAsync(getDiscoveredAuthority, StandardInteractionClientGetDiscoveredAuthority, this.logger, this.performanceClient, correlationId)(this.config, this.correlationId, this.performanceClient, this.browserStorage, this.logger, authority, azureCloudOptions, extraQueryParameters, account);
const earJwk = await invokeAsync(generateEarKey, GenerateEarKey, this.logger, this.performanceClient, correlationId)();
const pkceCodes = await invokeAsync(generatePkceCodes, GeneratePkceCodes, this.logger, this.performanceClient, correlationId)(this.performanceClient, this.logger, correlationId);
const silentRequest = {
...request,
earJwk: earJwk,
codeChallenge: pkceCodes.challenge,
};
// Create the iframe, register the response listener, then navigate, so the listener is active before the iframe can respond.
const iframe = createHiddenIframe();
const responseType = this.config.auth.OIDCOptions.responseMode;
let responseString;
try {
const responsePromise = invokeAsync(this.waitForIframeResponse.bind(this), SilentHandlerMonitorIframeForHash, this.logger, this.performanceClient, correlationId)(iframe, request);
responsePromise.catch(() => {
/*
* If navigation below throws before responsePromise is awaited,
* the listener still rejects on timeout. Swallow it here so it
* does not surface as an unhandled rejection; the navigation
* error is propagated instead.
*/
});
await invokeAsync(initiateEarRequest, SilentHandlerInitiateAuthRequest, this.logger, this.performanceClient, correlationId)(iframe, this.config, discoveredAuthority, silentRequest, this.logger, this.performanceClient);
responseString = await responsePromise;
}
finally {
invoke(removeHiddenIframe, RemoveHiddenIframe, this.logger, this.performanceClient, correlationId)(iframe);
}
const serverParams = invoke(deserializeResponse, DeserializeResponse, this.logger, this.performanceClient, correlationId)(responseString, responseType, this.logger, this.correlationId);
if (!serverParams.ear_jwe && serverParams.code) {
// If server doesn't support EAR, they may fallback to auth code flow instead
const authClient = await invokeAsync(this.createAuthCodeClient.bind(this), StandardInteractionClientCreateAuthCodeClient, this.logger, this.performanceClient, correlationId)({
serverTelemetryManager: initializeServerTelemetryManager(this.apiId, this.config.auth.clientId, correlationId, this.browserStorage, this.logger, undefined, this.config.system.serverTelemetryEnabled),
requestAuthority: request.authority,
requestAzureCloudOptions: request.azureCloudOptions,
requestExtraQueryParameters: request.extraQueryParameters,
account: request.account,
authority: discoveredAuthority,
});
return invokeAsync(handleResponseCode, HandleResponseCode, this.logger, this.performanceClient, correlationId)(silentRequest, serverParams, pkceCodes.verifier, this.apiId, this.config, authClient, this.browserStorage, this.nativeStorage, this.eventHandler, this.logger, this.performanceClient, this.platformAuthProvider);
}
else {
return invokeAsync(handleResponseEAR, HandleResponseEar, this.logger, this.performanceClient, correlationId)(silentRequest, serverParams, this.apiId, this.config, discoveredAuthority, this.browserStorage, this.nativeStorage, this.eventHandler, this.logger, this.performanceClient, this.platformAuthProvider);
}
}
/**
* Verifies SSO capability by making an iframe request to /authorize without exchanging the code for tokens.
* This is useful for verifying SSO capability in the background without the overhead of a full token exchange.
* @param request - The SSO silent request
* @returns true if SSO verification was successful with a valid authorization code, false otherwise
*/
async verifySso(request) {
const inputRequest = { ...request };
if (!inputRequest.prompt) {
inputRequest.prompt = PromptValue.NONE;
}
// Create silent request
const silentRequest = await invokeAsync(initializeAuthorizationRequest, StandardInteractionClientInitializeAuthorizationRequest, this.logger, this.performanceClient, this.correlationId)(inputRequest, InteractionType.Silent, this.config, this.browserCrypto, this.browserStorage, this.logger, this.performanceClient, this.correlationId);
const authClient = await invokeAsync(this.createAuthCodeClient.bind(this), StandardInteractionClientCreateAuthCodeClient, this.logger, this.performanceClient, this.correlationId)({
serverTelemetryManager: initializeServerTelemetryManager(this.apiId, this.config.auth.clientId, this.correlationId, this.browserStorage, this.logger, undefined, this.config.system.serverTelemetryEnabled),
requestAuthority: silentRequest.authority,
requestAzureCloudOptions: silentRequest.azureCloudOptions,
requestExtraQueryParameters: silentRequest.extraQueryParameters,
account: silentRequest.account,
});
const { serverParams } = await this.silentAuthorizeHelper(authClient, silentRequest);
const correlationId = silentRequest.correlationId;
// Validate the response - this checks for errors and validates state
validateAuthorizationResponse(serverParams, silentRequest.state, correlationId);
// Verify a valid authorization code is present
if (!serverParams.code) {
this.logger.warning("0y34ti", correlationId);
return false;
}
this.logger.verbose("0kkkcj", correlationId);
return true;
}
/**
* Currently Unsupported
*/
logout() {
// Synchronous so we must reject
return Promise.reject(createBrowserAuthError(silentLogoutUnsupported, ""));
}
/**
* Helper which acquires an authorization code silently using a hidden iframe from given url
* using the scopes requested as part of the id, and exchanges the code for a set of OAuth tokens.
* @param navigateUrl
* @param userRequestScopes
*/
async silentTokenHelper(authClient, request) {
const { serverParams, pkceCodes, silentRequest } = await this.silentAuthorizeHelper(authClient, request);
return invokeAsync(handleResponseCode, HandleResponseCode, this.logger, this.performanceClient, request.correlationId)(silentRequest, serverParams, pkceCodes.verifier, this.apiId, this.config, authClient, this.browserStorage, this.nativeStorage, this.eventHandler, this.logger, this.performanceClient, this.platformAuthProvider);
}
/**
* Shared helper that generates PKCE codes, builds the /authorize URL,
* loads it in a hidden iframe, waits for the redirect-bridge response,
* and returns the deserialized server parameters along with the PKCE codes
* and the request that was sent.
*/
async silentAuthorizeHelper(authClient, request) {
const correlationId = request.correlationId;
const pkceCodes = await invokeAsync(generatePkceCodes, GeneratePkceCodes, this.logger, this.performanceClient, correlationId)(this.performanceClient, this.logger, correlationId);
const tokenBindingParams = await getTokenBindingRequestParams(request, this.tokenBindingKeyManager, this.logger, this.performanceClient);
const silentRequest = {
...request,
codeChallenge: pkceCodes.challenge,
...tokenBindingParams,
};
// Create the iframe, register the response listener, then navigate, so the listener is active before the iframe can respond.
const iframe = createHiddenIframe();
const responseType = this.config.auth.OIDCOptions.responseMode;
// Wait for response from the redirect bridge.
let responseString;
try {
const responsePromise = invokeAsync(this.waitForIframeResponse.bind(this), SilentHandlerMonitorIframeForHash, this.logger, this.performanceClient, correlationId)(iframe, request);
responsePromise.catch(() => {
/*
* If URL creation or navigation below throws before
* responsePromise is awaited, the listener still rejects on
* timeout. Swallow it here so it does not surface as an
* unhandled rejection; the navigation error is propagated
* instead.
*/
});
if (request.httpMethod === HttpMethod$1.POST) {
await invokeAsync(initiateCodeFlowWithPost, SilentHandlerInitiateAuthRequest, this.logger, this.performanceClient, correlationId)(iframe, this.config, authClient.authority, silentRequest, this.logger, this.performanceClient);
}
else {
// Create authorize request url
const navigateUrl = await invokeAsync(getAuthCodeRequestUrl, GetAuthCodeUrl, this.logger, this.performanceClient, correlationId)(this.config, authClient.authority, silentRequest, this.logger, this.performanceClient);
// Navigate the iframe to the authorize request url
await invokeAsync(initiateCodeRequest, SilentHandlerInitiateAuthRequest, this.logger, this.performanceClient, correlationId)(iframe, navigateUrl, this.logger, correlationId);
}
responseString = await responsePromise;
}
finally {
invoke(removeHiddenIframe, RemoveHiddenIframe, this.logger, this.performanceClient, correlationId)(iframe);
}
const serverParams = invoke(deserializeResponse, DeserializeResponse, this.logger, this.performanceClient, correlationId)(responseString, responseType, this.logger, this.correlationId);
return { serverParams, pkceCodes, silentRequest };
}
async waitForIframeResponse(iframe, request) {
if (this.waitForIframeResponseHook) {
return this.waitForIframeResponseHook(iframe, request);
}
return waitForBridgeResponse(this.config.system.iframeBridgeTimeout, this.logger, request, this.performanceClient, this.config.experimental);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class SilentRefreshClient extends StandardInteractionClient {
/**
* Exchanges the refresh token for new tokens
* @param request
*/
async acquireToken(request) {
const baseRequest = await invokeAsync(initializeBaseRequest, InitializeBaseRequest, this.logger, this.performanceClient, request.correlationId)(request, this.config, this.performanceClient, this.logger, this.correlationId);
const tokenBindingParams = await getTokenBindingRequestParams(baseRequest, this.tokenBindingKeyManager, this.logger, this.performanceClient);
const silentRequest = {
...request,
...baseRequest,
...tokenBindingParams,
};
if (request.redirectUri) {
// Make sure any passed redirectUri is converted to an absolute URL - redirectUri is not a required parameter for refresh token redemption so only include if explicitly provided
silentRequest.redirectUri = getRedirectUri(request.redirectUri, this.config.auth.redirectUri, this.logger, this.correlationId);
}
const serverTelemetryManager = initializeServerTelemetryManager(ApiId.acquireTokenSilent_silentFlow, this.config.auth.clientId, this.correlationId, this.browserStorage, this.logger, undefined, this.config.system.serverTelemetryEnabled);
const refreshTokenClient = await this.createRefreshTokenClient({
serverTelemetryManager,
authorityUrl: silentRequest.authority,
azureCloudOptions: silentRequest.azureCloudOptions,
account: silentRequest.account,
});
// Send request to renew token. Auth module will throw errors if token cannot be renewed.
return invokeAsync(refreshTokenClient.acquireTokenByRefreshToken.bind(refreshTokenClient), RefreshTokenClientAcquireTokenByRefreshToken, this.logger, this.performanceClient, request.correlationId)(silentRequest, ApiId.acquireTokenSilent_silentFlow).catch((e) => {
e.correlationId = this.correlationId;
serverTelemetryManager.cacheFailedRequest(e);
throw e;
});
}
/**
* Currently Unsupported
*/
logout() {
// Synchronous so we must reject
return Promise.reject(createBrowserAuthError(silentLogoutUnsupported, ""));
}
/**
* Creates a Refresh Client with the given authority, or the default authority.
* @param params {
* serverTelemetryManager: ServerTelemetryManager;
* authorityUrl?: string;
* azureCloudOptions?: AzureCloudOptions;
* extraQueryParams?: StringDict;
* account?: AccountInfo;
* }
*/
async createRefreshTokenClient(params) {
// Create auth module.
const clientConfig = await invokeAsync(this.getClientConfiguration.bind(this), StandardInteractionClientGetClientConfiguration, this.logger, this.performanceClient, this.correlationId)({
serverTelemetryManager: params.serverTelemetryManager,
requestAuthority: params.authorityUrl,
requestAzureCloudOptions: params.azureCloudOptions,
requestExtraQueryParameters: params.extraQueryParameters,
account: params.account,
});
return new RefreshTokenClient(clientConfig, this.performanceClient);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class HybridSpaAuthorizationCodeClient extends AuthorizationCodeClient {
constructor(config, performanceClient) {
super(config, performanceClient);
this.includeRedirectUri = false;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class SilentAuthCodeClient extends StandardInteractionClient {
constructor(config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, apiId, performanceClient, correlationId, platformAuthProvider, tokenBindingKeyManager) {
super(config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, performanceClient, correlationId, platformAuthProvider, tokenBindingKeyManager);
this.apiId = apiId;
}
/**
* Acquires a token silently by redeeming an authorization code against the /token endpoint
* @param request
*/
async acquireToken(request) {
// Auth code payload is required
if (!request.code) {
throw createBrowserAuthError(authCodeRequired, this.correlationId);
}
// Create silent request
const silentRequest = await invokeAsync(initializeAuthorizationRequest, StandardInteractionClientInitializeAuthorizationRequest, this.logger, this.performanceClient, this.correlationId)(request, InteractionType.Silent, this.config, this.browserCrypto, this.browserStorage, this.logger, this.performanceClient,
/*
* correlationId is optional in request payload, while this.correlationId is always instantiated as request.correlationId || createGuid().
* Each auth request creates a new instance of *Client so we can safely use this.correlationId.
*/
this.correlationId);
const serverTelemetryManager = initializeServerTelemetryManager(this.apiId, this.config.auth.clientId, this.correlationId, this.browserStorage, this.logger, undefined, this.config.system.serverTelemetryEnabled);
try {
const tokenBindingParams = await getTokenBindingRequestParams(silentRequest, this.tokenBindingKeyManager, this.logger, this.performanceClient);
// Create auth code request (PKCE not needed)
const authCodeRequest = {
...silentRequest,
code: request.code,
...tokenBindingParams,
};
// Initialize the client
const clientConfig = await invokeAsync(this.getClientConfiguration.bind(this), StandardInteractionClientGetClientConfiguration, this.logger, this.performanceClient, this.correlationId)({
serverTelemetryManager,
requestAuthority: silentRequest.authority,
requestAzureCloudOptions: silentRequest.azureCloudOptions,
requestExtraQueryParameters: silentRequest.extraQueryParameters,
account: silentRequest.account,
});
const authClient = new HybridSpaAuthorizationCodeClient(clientConfig, this.performanceClient);
this.logger.verbose("1uic5e", this.correlationId);
// Create silent handler
const interactionHandler = new InteractionHandler(authClient, this.browserStorage, authCodeRequest, this.logger, this.performanceClient);
// Handle auth code parameters from request
return await invokeAsync(interactionHandler.handleCodeResponseFromServer.bind(interactionHandler), HandleCodeResponseFromServer, this.logger, this.performanceClient, this.correlationId)({
code: request.code,
msgraph_host: request.msGraphHost,
cloud_graph_host_name: request.cloudGraphHostName,
cloud_instance_host_name: request.cloudInstanceHostName,
}, silentRequest, this.apiId, false);
}
catch (e) {
if (e instanceof AuthError) {
e.correlationId = this.correlationId;
serverTelemetryManager.cacheFailedRequest(e);
}
throw e;
}
}
/**
* Currently Unsupported
*/
logout() {
// Synchronous so we must reject
return Promise.reject(createBrowserAuthError(silentLogoutUnsupported, ""));
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Get network information for telemetry purposes. This is only supported in Chromium-based browsers.
* @returns Network connection information, or an empty object if not available.
*/
function collectInstanceStats(currentClientId, performanceEvent, logger, correlationId) {
const frameInstances =
// @ts-ignore
window.msal?.clientIds || [];
const msalInstanceCount = frameInstances.length;
const sameClientIdInstanceCount = frameInstances.filter((i) => i === currentClientId).length;
if (sameClientIdInstanceCount > 1) {
logger.warning("1e88vg", correlationId);
}
performanceEvent.add({
msalInstanceCount: msalInstanceCount,
sameClientIdInstanceCount: sameClientIdInstanceCount,
});
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Selects request preparation using the current account and broker availability.
*/
function resolveSilentRequestPreparation(input, platformAuthProvider, logger, performanceClient) {
const { request, account, correlationId, config } = input;
const prepareRequest = account.nativeAccountId &&
isPlatformAuthAllowed(config, logger, correlationId, platformAuthProvider, request.authenticationScheme, performanceClient)
? preparePlatformSilentRequest
: prepareWebSilentRequest;
return prepareRequest(input);
}
/**
* Preserves the standard web thumbprint and caller-owned request references.
*/
function prepareWebSilentRequest({ request, account, correlationId, config, }) {
const thumbprint = getRequestThumbprint(config.auth.clientId, {
...request,
authority: request.authority || config.auth.authority}, account.homeAccountId);
return {
key: JSON.stringify(thumbprint),
request,
account,
};
}
/**
* Snapshots broker inputs and creates the extended key before acquisition begins.
*/
function preparePlatformSilentRequest({ request, account, config, }) {
const platformRequest = snapshotPlatformSilentRequest({
...request,
account,
});
return {
key: `platform:${getPlatformSilentRequestKey(platformRequest, config)}`,
request: platformRequest,
account: platformRequest.account,
};
}
/**
* Extends the common thumbprint with broker and client-side silent-flow inputs.
* Scopes are normalized like the broker request, without folding their casing.
*/
function getPlatformSilentRequestKey(request, config) {
const thumbprint = getRequestThumbprint(config.auth.clientId, {
...request,
authority: request.authority || config.auth.authority,
correlationId: request.correlationId || "",
scopes: new ScopeSet([...(request.scopes || []), ...OIDC_DEFAULT_SCOPES], request.correlationId || "")
.asArray()
.sort(),
}, request.account.homeAccountId);
return JSON.stringify({
...thumbprint,
accountId: request.account.nativeAccountId,
accountTenantId: request.account.tenantId,
accountEnvironment: request.account.environment,
azureCloudInstance: request.azureCloudOptions?.azureCloudInstance,
cloudTenantId: request.azureCloudOptions?.tenant,
redirectUri: request.redirectUri || config.auth.redirectUri,
nonce: request.nonce,
prompt: request.prompt,
state: request.state,
loginHint: request.loginHint,
popKid: request.popKid,
shrNonce: request.shrNonce,
dpopNonce: request.dpopNonce,
skipBrokerClaims: request.embeddedClientId
? !!request.skipBrokerClaims
: undefined,
extraParameters: canonicalizeStringDict(request.extraParameters),
extraQueryParameters: canonicalizeStringDict(request.extraQueryParameters),
extraParametersNoCache: canonicalizeStringDict(request.extraParametersNoCache),
forceRefresh: !!request.forceRefresh,
cacheLookupPolicy: request.cacheLookupPolicy ?? CacheLookupPolicy.Default,
});
}
/**
* Copies caller-owned mutable inputs before asynchronous broker initialization.
*/
function snapshotPlatformSilentRequest(request) {
return {
...request,
scopes: [...(request.scopes || [])],
account: { ...request.account },
azureCloudOptions: request.azureCloudOptions
? { ...request.azureCloudOptions }
: undefined,
extraParameters: request.extraParameters
? { ...request.extraParameters }
: undefined,
extraQueryParameters: request.extraQueryParameters
? { ...request.extraQueryParameters }
: undefined,
extraParametersNoCache: request.extraParametersNoCache
? { ...request.extraParametersNoCache }
: undefined,
attributeTokens: request.attributeTokens
? [...request.attributeTokens]
: undefined,
storeInCache: request.storeInCache
? { ...request.storeInCache }
: undefined,
};
}
/**
* Canonicalizes dictionary ordering while preserving exact parameter values.
*/
function canonicalizeStringDict(values = {}) {
return Object.keys(values)
.sort()
.map((key) => [key, values[key]]);
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
function preflightCheck(initialized, performanceEvent, config, request) {
try {
preflightCheck$1(initialized);
enforceResourceParameter(config.auth.isMcp, request);
}
catch (e) {
performanceEvent.end({ success: false }, e, request.account);
throw e;
}
}
class StandardController {
/**
* @constructor
* Constructor for the PublicClientApplication used to instantiate the PublicClientApplication object
*
* Important attributes in the Configuration object for auth are:
* - clientID: the application ID of your application. You can obtain one by registering your application with our Application registration portal : https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredAppsPreview
* - authority: the authority URL for your application.
* - redirect_uri: the uri of your application registered in the portal.
*
* In Azure AD, authority is a URL indicating the Azure active directory that MSAL uses to obtain tokens.
* It is of the form https://login.microsoftonline.com/{Enter_the_Tenant_Info_Here}
* If your application supports Accounts in one organizational directory, replace "Enter_the_Tenant_Info_Here" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com).
* If your application supports Accounts in any organizational directory, replace "Enter_the_Tenant_Info_Here" value with organizations.
* If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace "Enter_the_Tenant_Info_Here" value with common.
* To restrict support to Personal Microsoft accounts only, replace "Enter_the_Tenant_Info_Here" value with consumers.
*
* In Azure B2C, authority is of the form https://{instance}/tfp/{tenant}/{policyName}/
* Full B2C functionality will be available in this library in future versions.
*
* @param configuration Object for the MSAL PublicClientApplication instance
*/
constructor(operatingContext) {
this.operatingContext = operatingContext;
this.isBrowserEnvironment =
this.operatingContext.isBrowserEnvironment();
// Set the configuration.
this.config = operatingContext.getConfig();
this.initialized = false;
// Initialize logger
this.logger = this.operatingContext.getLogger();
// Initialize the network module class.
this.networkClient = this.config.system.networkClient;
// Initialize the navigation client class.
this.navigationClient = this.config.system.navigationClient;
// Initialize redirectResponse Map
this.redirectResponse = new Map();
// Initial hybrid spa map
this.hybridAuthCodeResponses = new Map();
// Initialize performance client
this.performanceClient = this.config.telemetry.client;
this.performanceClient.addGlobalFields({
allowPlatformBroker: this.config.system.allowPlatformBroker,
});
// Initialize environment-specific crypto and token-binding services.
if (this.isBrowserEnvironment) {
this.browserCrypto = new CryptoOps(this.logger, this.performanceClient);
this.tokenBindingKeyManager = new TokenBindingKeyManager(this.logger, this.performanceClient);
}
else {
this.browserCrypto = DEFAULT_CRYPTO_IMPLEMENTATION;
this.tokenBindingKeyManager = DEFAULT_TOKEN_BINDING_KEY_MANAGER;
}
this.eventHandler = new EventHandler(this.logger);
// Initialize the browser storage class.
this.browserStorage = this.isBrowserEnvironment
? new BrowserCacheManager(this.config.auth.clientId, this.config.cache, this.browserCrypto, this.logger, this.performanceClient, this.eventHandler, buildStaticAuthorityOptions(this.config.auth), this.tokenBindingKeyManager)
: DEFAULT_BROWSER_CACHE_MANAGER(this.config.auth.clientId, this.logger, this.performanceClient, this.eventHandler, undefined, this.tokenBindingKeyManager);
// initialize in memory storage for native flows
const nativeCacheOptions = {
cacheLocation: BrowserCacheLocation.MemoryStorage,
cacheRetentionDays: 5,
};
this.nativeInternalStorage = new BrowserCacheManager(this.config.auth.clientId, nativeCacheOptions, this.browserCrypto, this.logger, this.performanceClient, this.eventHandler, undefined, this.tokenBindingKeyManager);
this.activeSilentTokenRequests = new Map();
// Register listener functions
this.trackStateChange = this.trackStateChange.bind(this);
// Register listener functions
this.trackStateChangeWithMeasurement =
this.trackStateChangeWithMeasurement.bind(this);
}
static async createController(operatingContext, request) {
const controller = new StandardController(operatingContext);
await controller.initialize(request);
return controller;
}
trackStateChange(correlationId, event) {
if (!correlationId) {
return;
}
if (event.type === "visibilitychange") {
this.logger.info("16v6hv", correlationId);
this.performanceClient.incrementFields({ visibilityChangeCount: 1 }, correlationId);
}
else if (event.type === "online") {
this.logger.info("0zirfd", correlationId);
this.performanceClient.incrementFields({ onlineStatusChangeCount: 1 }, correlationId);
}
else if (event.type === "offline") {
this.logger.info("1xk9ef", correlationId);
this.performanceClient.incrementFields({ onlineStatusChangeCount: 1 }, correlationId);
}
}
/**
* Initializer function to perform async startup tasks such as connecting to WAM extension
* @param request {?InitializeApplicationRequest} correlation id
*/
async initialize(request) {
const correlationId = this.getRequestCorrelationId(request);
this.logger.trace("1f7joy", correlationId);
if (this.initialized) {
this.logger.info("061m5x", correlationId);
return;
}
if (!this.isBrowserEnvironment) {
this.logger.info("19fvpi", correlationId);
this.initialized = true;
this.eventHandler.emitEvent(EventType.INITIALIZE_END, correlationId);
return;
}
const allowPlatformBroker = this.config.system.allowPlatformBroker;
const initMeasurement = this.performanceClient.startMeasurement(InitializeClientApplication, correlationId);
this.eventHandler.emitEvent(EventType.INITIALIZE_START, correlationId);
// Broker applications are initialized twice, so we avoid double-counting it
this.logMultipleInstances(initMeasurement, correlationId);
initMeasurement.add({ isMcp: this.config.auth.isMcp });
await invokeAsync(this.browserStorage.initialize.bind(this.browserStorage), InitializeCache, this.logger, this.performanceClient, correlationId)(correlationId);
if (allowPlatformBroker) {
try {
// check if platform authentication is available via DOM or browser extension and create relevant handlers
this.platformAuthProvider = await getPlatformAuthProvider(this.logger, this.performanceClient, correlationId, this.config.system.nativeBrokerHandshakeTimeout, this.config.experimental.allowPlatformBrokerWithDOM);
}
catch (e) {
this.logger.verbose(e, correlationId);
}
}
if (this.config.cache.cacheLocation ===
BrowserCacheLocation.LocalStorage) {
this.eventHandler.subscribeCrossTab();
}
!this.config.system.navigatePopups &&
(await this.preGeneratePkceCodes(correlationId));
this.initialized = true;
this.eventHandler.emitEvent(EventType.INITIALIZE_END, correlationId);
initMeasurement.end({
allowPlatformBroker: allowPlatformBroker,
success: true,
});
}
// #region Redirect Flow
/**
* Event handler function which allows users to fire events after the PublicClientApplication object
* has loaded during redirect flows. This should be invoked on all page loads involved in redirect
* auth flows.
* @param hash Hash to process. Defaults to the current value of window.location.hash. Only needs to be provided explicitly if the response to be handled is not contained in the current value.
* @param options Object containing optional configuration for redirect promise handling.
* @returns Token response or null. If the return value is null, then no auth redirect was detected.
*/
async handleRedirectPromise(options) {
this.logger.verbose("02l8bm", "");
// Block token acquisition before initialize has been called
blockAPICallsBeforeInitialize(this.initialized);
if (this.isBrowserEnvironment) {
/**
* Store the promise on the PublicClientApplication instance if this is the first invocation of handleRedirectPromise,
* otherwise return the promise from the first invocation. Prevents race conditions when handleRedirectPromise is called
* several times concurrently.
*/
const redirectResponseKey = options?.hash || "";
let response = this.redirectResponse.get(redirectResponseKey);
if (typeof response === "undefined") {
response = this.handleRedirectPromiseInternal(options);
this.redirectResponse.set(redirectResponseKey, response);
this.logger.verbose("1wn9kp", "");
}
else {
this.logger.verbose("0w0gm3", "");
}
return response;
}
this.logger.verbose("12xi63", "");
return null;
}
/**
* The internal details of handleRedirectPromise. This is separated out to a helper to allow handleRedirectPromise to memoize requests
* @param hash
* @returns
*/
async handleRedirectPromiseInternal(options) {
if (!this.browserStorage.isInteractionInProgress(true)) {
this.logger.info("0le6uv", "");
return null;
}
const interactionType = this.browserStorage.getInteractionInProgress()?.type;
if (interactionType === INTERACTION_TYPE.SIGNOUT) {
this.logger.verbose("1ywcv2", "");
this.browserStorage.setInteractionInProgress(false);
return Promise.resolve(null);
}
const loggedInAccounts = this.getAllAccounts();
const platformBrokerRequest = this.browserStorage.getCachedNativeRequest();
const useNative = platformBrokerRequest && !options?.hash;
let rootMeasurement;
let redirectResponse;
let cachedRedirectRequest;
try {
if (useNative && this.platformAuthProvider) {
const correlationId = platformBrokerRequest?.correlationId || "";
this.eventHandler.emitEvent(EventType.HANDLE_REDIRECT_START, correlationId, InteractionType.Redirect);
rootMeasurement = this.performanceClient.startMeasurement(AcquireTokenRedirect, correlationId);
this.logger.trace("12v7is", correlationId);
// Cached nativeAccountId routes directly to the broker (no /authorize call)
rootMeasurement.add({
isPlatformBrokerRequest: true,
});
const nativeClient = new PlatformAuthInteractionClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, ApiId.handleRedirectPromise, this.performanceClient, this.platformAuthProvider, platformBrokerRequest.accountId, this.nativeInternalStorage, platformBrokerRequest.correlationId, this.tokenBindingKeyManager);
redirectResponse = invokeAsync(nativeClient.handleRedirectPromise.bind(nativeClient), HandleNativeRedirectPromiseMeasurement, this.logger, this.performanceClient, rootMeasurement.event.correlationId)();
}
else {
const [standardRequest, codeVerifier] = this.browserStorage.getCachedRequest("");
cachedRedirectRequest = standardRequest;
const correlationId = standardRequest.correlationId;
this.eventHandler.emitEvent(EventType.HANDLE_REDIRECT_START, correlationId, InteractionType.Redirect);
// Reset rootMeasurement now that we have correlationId
rootMeasurement = this.performanceClient.startMeasurement(AcquireTokenRedirect, correlationId);
this.logger.trace("0znzs5", correlationId);
const redirectClient = this.createRedirectClient(correlationId);
redirectResponse = invokeAsync(redirectClient.handleRedirectPromise.bind(redirectClient), HandleRedirectPromiseMeasurement, this.logger, this.performanceClient, rootMeasurement.event.correlationId)(standardRequest, codeVerifier, rootMeasurement, options);
}
}
catch (e) {
this.browserStorage.resetRequestCache("");
throw e;
}
return redirectResponse
.then((result) => {
if (result) {
this.browserStorage.resetRequestCache(result.correlationId);
this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_SUCCESS, result.correlationId, InteractionType.Redirect, result);
this.logger.verbose("0ui8f5", result.correlationId);
// Emit login event if number of accounts change
const isLoggingIn = loggedInAccounts.length < this.getAllAccounts().length;
if (isLoggingIn) {
this.eventHandler.emitEvent(EventType.LOGIN_SUCCESS, result.correlationId, InteractionType.Redirect, result.account);
this.logger.verbose("16im3l", result.correlationId);
}
rootMeasurement.end({
success: true,
isNativeBroker: result.fromPlatformBroker ?? false,
}, undefined, result.account);
// Fire-and-forget SSO capability verification in background
this.verifySsoCapability(cachedRedirectRequest, InteractionType.Redirect);
}
else {
/*
* Instrument an event only if an error code is set. Otherwise, discard it when the redirect response
* is empty and the error code is missing.
*/
if (!!rootMeasurement.event.errorCode) {
rootMeasurement.end({ success: false });
}
else {
rootMeasurement.discard();
}
}
this.eventHandler.emitEvent(EventType.HANDLE_REDIRECT_END, rootMeasurement.event.correlationId, InteractionType.Redirect);
return result;
})
.catch((e) => {
this.browserStorage.resetRequestCache(rootMeasurement.event.correlationId);
const eventError = e;
this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, rootMeasurement.event.correlationId, InteractionType.Redirect, null, eventError);
this.eventHandler.emitEvent(EventType.HANDLE_REDIRECT_END, rootMeasurement.event.correlationId, InteractionType.Redirect);
rootMeasurement.end({
success: false,
}, eventError);
throw e;
});
}
/**
* Use when you want to obtain an access_token for your API by redirecting the user's browser window to the authorization endpoint. This function redirects
* the page, so any code that follows this function will not execute.
*
* IMPORTANT: It is NOT recommended to have code that is dependent on the resolution of the Promise. This function will navigate away from the current
* browser window. It currently returns a Promise in order to reflect the asynchronous nature of the code running in this function.
*
* @param request
*/
async acquireTokenRedirect(request) {
// Preflight request
const correlationId = this.getRequestCorrelationId(request);
this.logger.verbose("0os66p", correlationId);
redirectPreflightCheck(this.initialized, this.config);
this.browserStorage.setInteractionInProgress(true, INTERACTION_TYPE.SIGNIN);
const atrMeasurement = this.performanceClient.startMeasurement(AcquireTokenPreRedirect, correlationId);
atrMeasurement.add({
scenarioId: request.scenarioId,
});
const configOnRedirectNavigateCb = this.config.auth.onRedirectNavigate;
this.config.auth.onRedirectNavigate = (url) => {
const navigate = typeof configOnRedirectNavigateCb === "function"
? configOnRedirectNavigateCb(url)
: undefined;
atrMeasurement.add({
navigateCallbackResult: navigate !== false,
});
atrMeasurement.event =
atrMeasurement.end({ success: true }, undefined, request.account) || atrMeasurement.event;
return navigate;
};
try {
enforceResourceParameter(this.config.auth.isMcp, request);
this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_START, correlationId, InteractionType.Redirect, request);
let result;
const platformAuthProvider = this.platformAuthProvider;
if (this.canUsePlatformBroker(request) && platformAuthProvider) {
const nativeClient = new PlatformAuthInteractionClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, ApiId.acquireTokenRedirect, this.performanceClient, platformAuthProvider, this.getNativeAccountId(request), this.nativeInternalStorage, correlationId, this.tokenBindingKeyManager);
result = invokeAsync(nativeClient.acquireTokenRedirect.bind(nativeClient), NativeInteractionClientAcquireTokenRedirect, this.logger, this.performanceClient, correlationId)(request, atrMeasurement).catch((e) => {
if (e instanceof NativeAuthError &&
isFatalNativeAuthError(e)) {
this.platformAuthProvider = undefined; // If extension gets uninstalled during session prevent future requests from continuing to attempt platform broker calls
const redirectClient = this.createRedirectClient(correlationId);
return redirectClient.acquireToken(request);
}
else if (e instanceof InteractionRequiredAuthError) {
this.logger.verbose("1ipyz4", correlationId);
const redirectClient = this.createRedirectClient(correlationId);
return redirectClient.acquireToken(request);
}
throw e;
});
}
else {
const redirectClient = this.createRedirectClient(correlationId);
result = redirectClient.acquireToken(request);
}
return await result;
}
catch (e) {
this.browserStorage.resetRequestCache(correlationId);
/*
* Pre-redirect event completes before navigation occurs.
* Timed out navigation needs to be instrumented separately as a post-redirect event.
*/
if (atrMeasurement.event.status === 2) {
this.performanceClient
.startMeasurement(AcquireTokenRedirect, correlationId)
.end({ success: false }, e, request.account);
}
else {
atrMeasurement.end({ success: false }, e, request.account);
}
this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, correlationId, InteractionType.Redirect, null, e);
throw e;
}
}
// #endregion
// #region Popup Flow
/**
* Use when you want to obtain an access_token for your API via opening a popup window in the user's browser
*
* @param request
*
* @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
*/
acquireTokenPopup(request) {
const correlationId = this.getRequestCorrelationId(request);
const atPopupMeasurement = this.performanceClient.startMeasurement(AcquireTokenPopup, correlationId);
atPopupMeasurement.add({
scenarioId: request.scenarioId,
});
try {
this.logger.verbose("0ch87b", correlationId);
preflightCheck(this.initialized, atPopupMeasurement, this.config, request);
this.browserStorage.setInteractionInProgress(true, INTERACTION_TYPE.SIGNIN, request.overrideInteractionInProgress, correlationId);
}
catch (e) {
// Since this function is syncronous we need to reject
return Promise.reject(e);
}
// If logged in, emit acquire token events
const loggedInAccounts = this.getAllAccounts();
this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_START, correlationId, InteractionType.Popup, request);
let result;
const pkce = this.getPreGeneratedPkceCodes(correlationId);
if (this.canUsePlatformBroker(request)) {
// Cached nativeAccountId routes directly to the broker (no /authorize call)
atPopupMeasurement.add({
isPlatformBrokerRequest: true,
});
result = this.acquireTokenNative({
...request,
correlationId,
}, ApiId.acquireTokenPopup)
.then((response) => {
atPopupMeasurement.end({
success: true,
isNativeBroker: response.fromPlatformBroker ?? false,
}, undefined, response.account);
return response;
})
.catch((e) => {
if (e instanceof NativeAuthError &&
isFatalNativeAuthError(e)) {
this.platformAuthProvider = undefined; // If extension gets uninstalled during session prevent future requests from continuing to attempt platform broker calls
const popupClient = this.createPopupClient(correlationId);
return popupClient.acquireToken(request, pkce);
}
else if (e instanceof InteractionRequiredAuthError) {
this.logger.verbose("0yy5fw", correlationId);
const popupClient = this.createPopupClient(correlationId);
return popupClient.acquireToken(request, pkce);
}
throw e;
});
}
else {
const popupClient = this.createPopupClient(correlationId);
result = popupClient.acquireToken(request, pkce);
}
return result
.then((result) => {
/*
* If logged in, emit acquire token events
*/
const isLoggingIn = loggedInAccounts.length < this.getAllAccounts().length;
this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_SUCCESS, correlationId, InteractionType.Popup, result);
if (isLoggingIn) {
this.eventHandler.emitEvent(EventType.LOGIN_SUCCESS, correlationId, InteractionType.Popup, result.account);
}
atPopupMeasurement.end({
success: true,
isNativeBroker: result.fromPlatformBroker ?? false,
accessTokenSize: result.accessToken.length,
idTokenSize: result.idToken.length,
}, undefined, result.account);
// SSO capability verification in background
this.verifySsoCapability(request, InteractionType.Popup);
return result;
})
.catch((e) => {
this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, correlationId, InteractionType.Popup, null, e);
atPopupMeasurement.end({
success: false,
}, e, request.account);
// Since this function is syncronous we need to reject
return Promise.reject(e);
})
.finally(async () => {
this.browserStorage.setInteractionInProgress(false);
if (!this.config.system.navigatePopups) {
await this.preGeneratePkceCodes(correlationId);
}
});
}
trackStateChangeWithMeasurement(event) {
const measurement = this.ssoSilentMeasurement ||
this.acquireTokenByCodeAsyncMeasurement;
if (!measurement) {
return;
}
if (event.type === "visibilitychange") {
this.logger.info(`0yzimq ${measurement.event.name}`, measurement.event.correlationId);
measurement.increment({
visibilityChangeCount: 1,
});
}
else if (event.type === "online") {
this.logger.info(`1caf53 ${measurement.event.name}`, measurement.event.correlationId);
measurement.increment({
onlineStatusChangeCount: 1,
});
}
else if (event.type === "offline") {
this.logger.info(`0fdyk7 ${measurement.event.name}`, measurement.event.correlationId);
measurement.increment({
onlineStatusChangeCount: 1,
});
}
}
addStateChangeListeners(listener) {
document.addEventListener("visibilitychange", listener);
window.addEventListener("online", listener);
window.addEventListener("offline", listener);
}
removeStateChangeListeners(listener) {
document.removeEventListener("visibilitychange", listener);
window.removeEventListener("online", listener);
window.removeEventListener("offline", listener);
}
/**
* Reads the cached ssoCapable value from localStorage.
* @returns The cached ssoCapable boolean value, or undefined if not cached or expired.
*/
getCachedSsoCapable() {
try {
const cachedValue = window.localStorage.getItem(SSO_CAPABLE);
if (cachedValue) {
const parsed = JSON.parse(cachedValue);
if (parsed &&
typeof parsed.ssoCapable === "boolean" &&
parsed.expiresOn &&
Date.now() < parsed.expiresOn) {
return parsed.ssoCapable;
}
}
}
catch {
// If parsing fails, return undefined
}
return undefined;
}
/**
* SSO capability verification in the background.
* This method makes an iframe request to /authorize to verify SSO capability without calling /token.
* This method does not block the caller and tracks telemetry for success/failure.
* This method only executes if verifySSO is set to true in the auth configuration.
* The result is cached in localStorage with a 24-hour TTL; the SSO verification call
* is only attempted when the cached value is absent or expired.
* @param request - The original request used for the authentication flow
* @param interactionType - The interactionType of the AT operation for logging purposes
*/
verifySsoCapability(request, interactionType) {
// Check if SSO capability verification is enabled
if (!this.config.auth.verifySSO) {
return;
}
// Check TTL: derive ssoCapable state from localStorage and skip if not expired
const ssoCacheKey = SSO_CAPABLE;
const SSO_CAPABLE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
const cachedSsoCapable = this.getCachedSsoCapable();
if (cachedSsoCapable !== undefined) {
this.logger.verbose(`13poou ${interactionType}`, "");
return;
}
const correlationId = createNewGuid();
const ssoCapableMeasurement = this.performanceClient.startMeasurement(SsoCapable, correlationId);
ssoCapableMeasurement.add({
"ext.interactionType": interactionType,
});
this.logger.verbose(`0pbr0i ${interactionType}`, correlationId);
/*
* Use setTimeout to ensure this runs in a separate macrotask after the current call stack completes
* This ensures the result is returned to the caller before the SSO verification starts and doesn't affect performance
*/
setTimeout(() => {
const ssoVerificationRequest = {
...request,
correlationId: correlationId,
};
const silentIframeClient = this.createSilentIframeClient(correlationId);
silentIframeClient
.verifySso(ssoVerificationRequest)
.then((result) => {
this.logger.verbose(`1gd1iv ${interactionType} ${result}`, correlationId);
// TBD to add profileTelemetry later in localStorage with 24h TTL
try {
const cacheEntry = JSON.stringify({
ssoCapable: result,
expiresOn: Date.now() + SSO_CAPABLE_TTL_MS,
});
window.localStorage.setItem(ssoCacheKey, cacheEntry);
}
catch {
this.logger.warning(`18lmoj ${interactionType}`, correlationId);
}
ssoCapableMeasurement.end({
fromCache: false,
success: result,
}, undefined);
})
.catch((error) => {
this.logger.warning(`05g83w ${interactionType} ${error.message}`, correlationId);
// reset the cache
try {
window.localStorage.removeItem(ssoCacheKey);
}
catch {
this.logger.warning(`0nlf9q ${interactionType}`, correlationId);
}
ssoCapableMeasurement.end({
fromCache: false,
success: false,
}, error);
});
}, 0);
}
// #endregion
// #region Silent Flow
/**
* This function uses a hidden iframe to fetch an authorization code from the eSTS. There are cases where this may not work:
* - Any browser using a form of Intelligent Tracking Prevention
* - If there is not an established session with the service
*
* In these cases, the request must be done inside a popup or full frame redirect.
*
* For the cases where interaction is required, you cannot send a request with prompt=none.
*
* If your refresh token has expired, you can use this function to fetch a new set of tokens silently as long as
* you session on the server still exists.
* @param request {@link SsoSilentRequest}
*
* @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
*/
async ssoSilent(request) {
const correlationId = this.getRequestCorrelationId(request);
const validRequest = {
...request,
correlationId: correlationId,
};
this.ssoSilentMeasurement = this.performanceClient.startMeasurement(SsoSilent, correlationId);
this.ssoSilentMeasurement?.add({
scenarioId: request.scenarioId,
ssoCapable: this.getCachedSsoCapable(),
});
preflightCheck(this.initialized, this.ssoSilentMeasurement, this.config, validRequest);
this.ssoSilentMeasurement?.increment({
visibilityChangeCount: 0,
onlineStatusChangeCount: 0,
});
this.addStateChangeListeners(this.trackStateChangeWithMeasurement);
const loggedInAccounts = this.getAllAccounts();
this.logger.verbose("0w1b45", correlationId);
this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_START, correlationId, InteractionType.Silent, validRequest);
let result;
if (this.canUsePlatformBroker(validRequest)) {
// Cached nativeAccountId routes directly to the broker (no /authorize call)
this.ssoSilentMeasurement?.add({
isPlatformBrokerRequest: true,
});
result = this.acquireTokenNative(validRequest, ApiId.ssoSilent).catch((e) => {
// If native token acquisition fails for availability reasons fallback to standard flow
if (e instanceof NativeAuthError && isFatalNativeAuthError(e)) {
this.platformAuthProvider = undefined; // If extension gets uninstalled during session prevent future requests from continuing to attempt platform broker calls
const silentIframeClient = this.createSilentIframeClient(validRequest.correlationId);
return silentIframeClient.acquireToken(validRequest);
}
throw e;
});
}
else {
const silentIframeClient = this.createSilentIframeClient(validRequest.correlationId);
result = silentIframeClient.acquireToken(validRequest);
}
return result
.then((response) => {
const isLoggingIn = loggedInAccounts.length < this.getAllAccounts().length;
this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_SUCCESS, correlationId, InteractionType.Silent, response);
if (isLoggingIn) {
this.eventHandler.emitEvent(EventType.LOGIN_SUCCESS, correlationId, InteractionType.Silent, response.account);
}
this.ssoSilentMeasurement?.end({
success: true,
isNativeBroker: response.fromPlatformBroker ?? false,
accessTokenSize: response.accessToken.length,
idTokenSize: response.idToken.length,
}, undefined, response.account);
return response;
})
.catch((e) => {
this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, correlationId, InteractionType.Silent, null, e);
this.ssoSilentMeasurement?.end({
success: false,
}, e, request.account);
throw e;
})
.finally(() => {
this.removeStateChangeListeners(this.trackStateChangeWithMeasurement);
});
}
/**
* This function redeems an authorization code (passed as code) from the eSTS token endpoint.
* This authorization code should be acquired server-side using a confidential client to acquire a spa_code.
* This API is not indended for normal authorization code acquisition and redemption.
*
* Redemption of this authorization code will not require PKCE, as it was acquired by a confidential client.
*
* @param request {@link AuthorizationCodeRequest}
* @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
*/
async acquireTokenByCode(request) {
const correlationId = this.getRequestCorrelationId(request);
this.logger.trace("0ch6ga", correlationId);
const atbcMeasurement = this.performanceClient.startMeasurement(AcquireTokenByCode, correlationId);
preflightCheck(this.initialized, atbcMeasurement, this.config, request);
this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_START, correlationId, InteractionType.Silent, request);
atbcMeasurement.add({ scenarioId: request.scenarioId });
try {
if (request.code && request.nativeAccountId) {
// Throw error in case server returns both spa_code and spa_accountid in exchange for auth code.
throw createBrowserAuthError(spaCodeAndNativeAccountIdPresent, correlationId);
}
else if (request.code) {
const hybridAuthCode = request.code;
let response = this.hybridAuthCodeResponses.get(hybridAuthCode);
if (!response) {
this.logger.verbose("06eh73", correlationId);
response = this.acquireTokenByCodeAsync({
...request,
correlationId,
})
.then((result) => {
this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_SUCCESS, correlationId, InteractionType.Silent, result);
this.hybridAuthCodeResponses.delete(hybridAuthCode);
atbcMeasurement.end({
success: true,
isNativeBroker: false,
accessTokenSize: result.accessToken.length,
idTokenSize: result.idToken.length,
}, undefined, result.account);
return result;
})
.catch((error) => {
this.hybridAuthCodeResponses.delete(hybridAuthCode);
this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, correlationId, InteractionType.Silent, null, error);
atbcMeasurement.end({
success: false,
}, error);
throw error;
});
this.hybridAuthCodeResponses.set(hybridAuthCode, response);
}
else {
this.logger.verbose("0qgp28", correlationId);
atbcMeasurement.discard();
}
return await response;
}
else if (request.nativeAccountId) {
if (this.canUsePlatformBroker(request, request.nativeAccountId)) {
atbcMeasurement.add({
isPlatformBrokerRequest: true,
});
const result = await this.acquireTokenNative({
...request,
correlationId,
}, ApiId.acquireTokenByCode, request.nativeAccountId).catch((e) => {
// If native token acquisition fails for availability reasons fallback to standard flow
if (e instanceof NativeAuthError &&
isFatalNativeAuthError(e)) {
this.platformAuthProvider = undefined; // If extension gets uninstalled during session prevent future requests from continuing to attempt
}
throw e;
});
atbcMeasurement.end({
success: true,
isNativeBroker: result.fromPlatformBroker ?? false,
}, undefined, result.account);
return result;
}
else {
throw createBrowserAuthError(unableToAcquireTokenFromNativePlatform, correlationId);
}
}
else {
throw createBrowserAuthError(authCodeOrNativeAccountIdRequired, correlationId);
}
}
catch (e) {
this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, correlationId, InteractionType.Silent, null, e);
atbcMeasurement.end({
success: false,
}, e);
throw e;
}
}
/**
* Creates a SilentAuthCodeClient to redeem an authorization code.
* @param request
* @returns Result of the operation to redeem the authorization code
*/
async acquireTokenByCodeAsync(request) {
const correlationId = this.getRequestCorrelationId(request);
this.logger.trace("10d9hy", correlationId);
this.acquireTokenByCodeAsyncMeasurement =
this.performanceClient.startMeasurement(AcquireTokenByCodeAsync, correlationId);
this.acquireTokenByCodeAsyncMeasurement?.increment({
visibilityChangeCount: 0,
onlineStatusChangeCount: 0,
});
this.addStateChangeListeners(this.trackStateChangeWithMeasurement);
const silentAuthCodeClient = this.createSilentAuthCodeClient(correlationId);
const silentTokenResult = await silentAuthCodeClient
.acquireToken(request)
.then((response) => {
this.acquireTokenByCodeAsyncMeasurement?.end({
success: true,
isNativeBroker: false,
fromCache: response.fromCache,
});
return response;
})
.catch((tokenRenewalError) => {
this.acquireTokenByCodeAsyncMeasurement?.end({
success: false,
}, tokenRenewalError);
throw tokenRenewalError;
})
.finally(() => {
this.removeStateChangeListeners(this.trackStateChangeWithMeasurement);
});
return silentTokenResult;
}
/**
* Attempt to acquire an access token from the cache
* @param silentCacheClient SilentCacheClient
* @param commonRequest CommonSilentFlowRequest
* @param silentRequest SilentRequest
* @returns A promise that, when resolved, returns the access token
*/
async acquireTokenFromCache(commonRequest, cacheLookupPolicy) {
switch (cacheLookupPolicy) {
case CacheLookupPolicy.Default:
case CacheLookupPolicy.AccessToken:
case CacheLookupPolicy.AccessTokenAndRefreshToken:
const silentCacheClient = this.createSilentCacheClient(commonRequest.correlationId);
return invokeAsync(silentCacheClient.acquireToken.bind(silentCacheClient), SilentCacheClientAcquireToken, this.logger, this.performanceClient, commonRequest.correlationId)(commonRequest);
default:
throw createClientAuthError(tokenRefreshRequired, commonRequest.correlationId);
}
}
/**
* Attempt to acquire an access token via a refresh token
* @param commonRequest CommonSilentFlowRequest
* @param cacheLookupPolicy CacheLookupPolicy
* @returns A promise that, when resolved, returns the access token
*/
async acquireTokenByRefreshToken(commonRequest, cacheLookupPolicy) {
switch (cacheLookupPolicy) {
case CacheLookupPolicy.Default:
case CacheLookupPolicy.AccessTokenAndRefreshToken:
case CacheLookupPolicy.RefreshToken:
case CacheLookupPolicy.RefreshTokenAndNetwork:
const silentRefreshClient = this.createSilentRefreshClient(commonRequest.correlationId);
return invokeAsync(silentRefreshClient.acquireToken.bind(silentRefreshClient), SilentRefreshClientAcquireToken, this.logger, this.performanceClient, commonRequest.correlationId)(commonRequest);
default:
throw createClientAuthError(tokenRefreshRequired, commonRequest.correlationId);
}
}
/**
* Attempt to acquire an access token via an iframe
* @param request CommonSilentFlowRequest
* @returns A promise that, when resolved, returns the access token
*/
async acquireTokenBySilentIframe(request) {
const silentIframeClient = this.createSilentIframeClient(request.correlationId);
return invokeAsync(silentIframeClient.acquireToken.bind(silentIframeClient), SilentIframeClientAcquireToken, this.logger, this.performanceClient, request.correlationId)(request);
}
// #endregion
// #region Logout
/**
* Use to log out the current user, and redirect the user to the postLogoutRedirectUri.
* Default behaviour is to redirect the user to `window.location.href`.
* @param logoutRequest
*/
async logoutRedirect(logoutRequest) {
const correlationId = this.getRequestCorrelationId(logoutRequest);
redirectPreflightCheck(this.initialized, this.config);
this.browserStorage.setInteractionInProgress(true, INTERACTION_TYPE.SIGNOUT);
const redirectClient = this.createRedirectClient(correlationId);
return redirectClient.logout(logoutRequest);
}
/**
* Clears local cache for the current user then opens a popup window prompting the user to sign-out of the server
* @param logoutRequest
*/
logoutPopup(logoutRequest) {
try {
const correlationId = this.getRequestCorrelationId(logoutRequest);
preflightCheck$1(this.initialized);
this.browserStorage.setInteractionInProgress(true, INTERACTION_TYPE.SIGNOUT);
const popupClient = this.createPopupClient(correlationId);
return popupClient.logout(logoutRequest).finally(() => {
this.browserStorage.setInteractionInProgress(false);
});
}
catch (e) {
// Since this function is syncronous we need to reject
return Promise.reject(e);
}
}
/**
* Creates a cache interaction client to clear broswer cache.
* @param logoutRequest
*/
async clearCache(logoutRequest) {
if (!this.isBrowserEnvironment) {
return;
}
const correlationId = this.getRequestCorrelationId(logoutRequest);
const cacheClient = this.createSilentCacheClient(correlationId);
return cacheClient.logout(logoutRequest);
}
// #endregion
// #region Account APIs
/**
* Returns all the accounts in the cache that match the optional filter. If no filter is provided, all accounts are returned.
* @param accountFilter - (Optional) filter to narrow down the accounts returned
* @returns Array of AccountInfo objects in cache
*/
getAllAccounts(accountFilter) {
return getAllAccounts(this.logger, this.browserStorage, this.isBrowserEnvironment, this.getRequestCorrelationId(), accountFilter);
}
/**
* Returns the first account found in the cache that matches the account filter passed in.
* @param accountFilter
* @returns The first account found in the cache matching the provided filter or null if no account could be found.
*/
getAccount(accountFilter) {
return getAccount(accountFilter, this.logger, this.browserStorage, this.getRequestCorrelationId());
}
/**
* Sets the account to use as the active account. If no account is passed to the acquireToken APIs, then MSAL will use this active account.
* @param account
*/
setActiveAccount(account) {
setActiveAccount(account, this.browserStorage, this.getRequestCorrelationId());
}
/**
* Gets the currently active account
*/
getActiveAccount() {
return getActiveAccount(this.browserStorage, this.getRequestCorrelationId());
}
// #endregion
/**
* Hydrates the cache with the tokens from an AuthenticationResult
* @param result
* @param request
* @returns
*/
async hydrateCache(result, request) {
this.logger.verbose("16jycr", result.correlationId);
// Account gets saved to browser storage regardless of native or not
const accountEntity = createAccountEntityFromAccountInfo(result.account, result.cloudGraphHostName, result.msGraphHost);
await this.browserStorage.setAccount(accountEntity, result.correlationId, isKmsi(result.idTokenClaims), ApiId.hydrateCache);
if (result.fromPlatformBroker) {
this.logger.verbose("1i5atf", result.correlationId);
// Create idToken entity and store in browser storage
const idTokenEntity = createIdTokenEntity(result.account.homeAccountId, result.account.environment, result.idToken, this.config.auth.clientId, result.tenantId);
// Create accessToken entity and store in native internal storage
const attributeTokenPartition = serializeAttributeTokens(request.attributeTokens);
const additionalCacheKeyComponents = attributeTokenPartition
? {
attribute_tokens: attributeTokenPartition,
}
: undefined;
const accessTokenEntity = createAccessTokenEntity(result.account.homeAccountId, result.account.environment, result.accessToken, this.config.auth.clientId, result.tenantId, result.scopes.join(" "), result.expiresOn
? toSecondsFromDate(result.expiresOn)
: 0, result.extExpiresOn
? toSecondsFromDate(result.extExpiresOn)
: 0, base64Decode, request.correlationId || "", undefined, // refreshOn
result.tokenType, undefined, // userAssertionHash
request.sshKid, additionalCacheKeyComponents);
if (request.resource) {
accessTokenEntity.resource = request.resource;
}
// Get attribute token partition hash for cache key isolation
const components = additionalCacheKeyComponents;
const additionalCacheKeyHash = components
? await this.browserCrypto.hashString(JSON.stringify(components))
: undefined;
const kmsi = isKmsi(result.idTokenClaims);
// Store idToken in browser storage
await this.browserStorage.setIdTokenCredential(idTokenEntity, result.correlationId, kmsi);
// Store accessToken in native internal storage
await this.nativeInternalStorage.setAccessTokenCredential(accessTokenEntity, result.correlationId, kmsi, additionalCacheKeyHash);
}
else {
return this.browserStorage.hydrateCache(result, request);
}
}
// #region Helpers
/**
* Acquire a token from native device (e.g. WAM)
* @param request
* @param apiId
* @param accountId
* @param cacheLookupPolicy
*/
async acquireTokenNative(request, apiId, accountId, cacheLookupPolicy) {
/*
* Callers always normalize correlationId onto the request before delegating
* here, so it is guaranteed defined and is the single id used to key this
* flow's telemetry.
*/
const correlationId = this.getRequestCorrelationId(request);
this.logger.trace("0b9y3p", correlationId);
if (!this.platformAuthProvider) {
throw createBrowserAuthError(nativeConnectionNotEstablished, correlationId);
}
const nativeClient = new PlatformAuthInteractionClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, apiId, this.performanceClient, this.platformAuthProvider, accountId || this.getNativeAccountId(request), this.nativeInternalStorage, correlationId, this.tokenBindingKeyManager);
return invokeAsync(nativeClient.acquireToken.bind(nativeClient), NativeInteractionClientAcquireToken, this.logger, this.performanceClient, correlationId)(request, cacheLookupPolicy);
}
/**
* Returns boolean indicating if this request can use the platform broker
* @param request
*/
canUsePlatformBroker(request, accountId) {
const correlationId = this.getRequestCorrelationId(request);
this.logger.trace("1n9lbl", correlationId);
const platformAuthAllowed = isPlatformAuthAllowed(this.config, this.logger, correlationId, this.platformAuthProvider, request.authenticationScheme, this.performanceClient);
if (!platformAuthAllowed) {
this.logger.trace("0yoy1g", correlationId);
return false;
}
if (request.prompt) {
switch (request.prompt) {
case PromptValue.NONE:
case PromptValue.CONSENT:
case PromptValue.LOGIN:
this.logger.trace("0vdv8e", correlationId);
break;
default:
this.logger.trace(`0pdzw6 ${request.prompt}`, correlationId);
return false;
}
}
if (!accountId && !this.getNativeAccountId(request)) {
this.logger.trace("16lbtk", correlationId);
return false;
}
return true;
}
/**
* Get the native accountId from the account
* @param request
* @returns
*/
getNativeAccountId(request) {
const account = request.account ||
this.getAccount({
loginHint: request.loginHint,
sid: request.sid,
}) ||
(!request.loginHint && !request.sid
? this.getActiveAccount()
: null);
return (account && account.nativeAccountId) || "";
}
/**
* Returns new instance of the Popup Interaction Client
* @param correlationId
*/
createPopupClient(correlationId) {
return new PopupClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, this.performanceClient, this.nativeInternalStorage, correlationId, this.platformAuthProvider, this.operatingContext.getResponseHandlers()?.waitForPopupResponse, this.tokenBindingKeyManager);
}
/**
* Returns new instance of the Redirect Interaction Client
* @param correlationId
*/
createRedirectClient(correlationId) {
return new RedirectClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, this.performanceClient, this.nativeInternalStorage, correlationId, this.platformAuthProvider, this.tokenBindingKeyManager);
}
/**
* Returns new instance of the Silent Iframe Interaction Client
* @param correlationId
*/
createSilentIframeClient(correlationId) {
return new SilentIframeClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, ApiId.ssoSilent, this.performanceClient, this.nativeInternalStorage, correlationId, this.platformAuthProvider, this.operatingContext.getResponseHandlers()?.waitForIframeResponse, this.tokenBindingKeyManager);
}
/**
* Returns new instance of the Silent Cache Interaction Client
*/
createSilentCacheClient(correlationId) {
return new SilentCacheClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, this.performanceClient, correlationId, this.platformAuthProvider, this.tokenBindingKeyManager);
}
/**
* Returns new instance of the Silent Refresh Interaction Client
*/
createSilentRefreshClient(correlationId) {
return new SilentRefreshClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, this.performanceClient, correlationId, this.platformAuthProvider, this.tokenBindingKeyManager);
}
/**
* Returns new instance of the Silent AuthCode Interaction Client
*/
createSilentAuthCodeClient(correlationId) {
return new SilentAuthCodeClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, ApiId.acquireTokenByCode, this.performanceClient, correlationId, this.platformAuthProvider, this.tokenBindingKeyManager);
}
/**
* Adds event callbacks to array
* @param callback
*/
addEventCallback(callback, eventTypes) {
return this.eventHandler.addEventCallback(callback, eventTypes);
}
/**
* Removes callback with provided id from callback array
* @param callbackId
*/
removeEventCallback(callbackId) {
this.eventHandler.removeEventCallback(callbackId);
}
/**
* Registers a callback to receive performance events.
*
* @param {PerformanceCallbackFunction} callback
* @returns {string}
*/
addPerformanceCallback(callback) {
blockNonBrowserEnvironment();
return this.performanceClient.addPerformanceCallback(callback);
}
/**
* Removes a callback registered with addPerformanceCallback.
*
* @param {string} callbackId
* @returns {boolean}
*/
removePerformanceCallback(callbackId) {
return this.performanceClient.removePerformanceCallback(callbackId);
}
/**
* Returns the logger instance
*/
getLogger() {
return this.logger;
}
/**
* Replaces the default logger set in configurations with new Logger with new configurations
* @param logger Logger instance
*/
setLogger(logger) {
this.logger = logger;
}
/**
* Called by wrapper libraries (Angular & React) to set SKU and Version passed down to telemetry, logger, etc.
* @param sku
* @param version
*/
initializeWrapperLibrary(sku, version) {
// Validate the SKU passed in is one we expect
this.browserStorage.setWrapperMetadata(sku, version);
}
/**
* Sets navigation client
* @param navigationClient
*/
setNavigationClient(navigationClient) {
this.navigationClient = navigationClient;
}
/**
* Returns the configuration object
*/
getConfiguration() {
return this.config;
}
/**
* Returns the performance client
*/
getPerformanceClient() {
return this.performanceClient;
}
/**
* Returns the browser env indicator
*/
isBrowserEnv() {
return this.isBrowserEnvironment;
}
/**
* Generates a correlation id for a request if none is provided.
*
* @protected
* @param {?Partial<BaseAuthRequest>} [request]
* @returns {string}
*/
getRequestCorrelationId(request) {
if (request?.correlationId) {
return request.correlationId;
}
if (this.isBrowserEnvironment) {
return createNewGuid();
}
/*
* Included for fallback for non-browser environments,
* and to ensure this method always returns a string.
*/
return "";
}
// #endregion
/**
* Use when initiating the login process by redirecting the user's browser to the authorization endpoint. This function redirects the page, so
* any code that follows this function will not execute.
*
* IMPORTANT: It is NOT recommended to have code that is dependent on the resolution of the Promise. This function will navigate away from the current
* browser window. It currently returns a Promise in order to reflect the asynchronous nature of the code running in this function.
*
* @param request
*/
async loginRedirect(request) {
const correlationId = this.getRequestCorrelationId(request);
this.logger.verbose("0lz9hf", correlationId);
return this.acquireTokenRedirect({
correlationId,
...(request || DEFAULT_REQUEST),
});
}
/**
* Use when initiating the login process via opening a popup window in the user's browser
*
* @param request
*
* @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
*/
loginPopup(request) {
const correlationId = this.getRequestCorrelationId(request);
this.logger.verbose("0qw7v5", correlationId);
return this.acquireTokenPopup({
correlationId,
...(request || DEFAULT_REQUEST),
});
}
/**
* Silently acquire an access token for a given set of scopes. Returns currently processing promise if parallel requests are made.
*
* @param {@link (SilentRequest:type)}
* @returns {Promise.<AuthenticationResult>} - a promise that is fulfilled when this function has completed, or rejected if an error was raised. Returns the {@link AuthResponse} object
*/
async acquireTokenSilent(request) {
const correlationId = this.getRequestCorrelationId(request);
const atsMeasurement = this.performanceClient.startMeasurement(AcquireTokenSilent, correlationId);
atsMeasurement.add({
cacheLookupPolicy: request.cacheLookupPolicy,
scenarioId: request.scenarioId,
ssoCapable: this.getCachedSsoCapable(),
});
preflightCheck(this.initialized, atsMeasurement, this.config, request);
this.logger.verbose("0x1c4s", correlationId);
const account = request.account || this.getActiveAccount();
if (!account) {
throw createBrowserAuthError(noAccountError, correlationId);
}
return this.acquireTokenSilentDeduped(request, account, correlationId)
.then((result) => {
atsMeasurement.end({
success: true,
isNativeBroker: result.fromPlatformBroker ?? false,
fromCache: result.fromCache,
accessTokenSize: result.accessToken.length,
idTokenSize: result.idToken.length,
}, undefined, result.account);
return {
...result,
state: request.state,
correlationId: correlationId, // Ensures PWB scenarios can correctly match request to response
};
})
.catch((error) => {
if (error instanceof AuthError) {
// Ensures PWB scenarios can correctly match request to response
error.correlationId = correlationId;
}
atsMeasurement.end({
success: false,
}, error, account);
throw error;
});
}
/**
* Checks if identical request is already in flight and returns reference to the existing promise or fires off a new one if this is the first
* @param request
* @param account
* @param correlationId
* @returns
*/
async acquireTokenSilentDeduped(request, account, correlationId) {
const preparedRequest = resolveSilentRequestPreparation({
request,
account,
correlationId,
config: this.config,
}, this.platformAuthProvider, this.logger, this.performanceClient);
const inProgressRequest = this.activeSilentTokenRequests.get(preparedRequest.key);
if (typeof inProgressRequest === "undefined") {
this.logger.verbose("0fcjbk", correlationId);
this.performanceClient.addFields({ deduped: false }, correlationId);
const activeRequest = invokeAsync(this.acquireTokenSilentAsync.bind(this), AcquireTokenSilentAsync, this.logger, this.performanceClient, correlationId)({
...preparedRequest.request,
correlationId,
}, preparedRequest.account);
this.activeSilentTokenRequests.set(preparedRequest.key, activeRequest);
return activeRequest.finally(() => {
this.activeSilentTokenRequests.delete(preparedRequest.key);
});
}
else {
this.logger.verbose("1yq7nb", correlationId);
this.performanceClient.addFields({ deduped: true }, correlationId);
return inProgressRequest;
}
}
/**
* Silently acquire an access token for a given set of scopes. Will use cached token if available, otherwise will attempt to acquire a new token from the network via refresh token.
* @param {@link (SilentRequest:type)}
* @param {@link (AccountInfo:type)}
* @returns {Promise.<AuthenticationResult>} - a promise that is fulfilled when this function has completed, or rejected if an error was raised. Returns the {@link AuthResponse}
*/
async acquireTokenSilentAsync(request, account) {
const trackStateChange = (event) => this.trackStateChange(request.correlationId, event);
this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_START, request.correlationId, InteractionType.Silent, request);
if (request.correlationId) {
this.performanceClient.incrementFields({ visibilityChangeCount: 0, onlineStatusChangeCount: 0 }, request.correlationId);
}
this.addStateChangeListeners(trackStateChange);
const silentRequest = await invokeAsync(initializeSilentRequest, InitializeSilentRequest, this.logger, this.performanceClient, request.correlationId)(request, account, this.config, this.performanceClient, this.logger);
const cacheLookupPolicy = request.cacheLookupPolicy || CacheLookupPolicy.Default;
const result = this.acquireTokenSilentNoIframe(silentRequest, cacheLookupPolicy).catch(async (refreshTokenError) => {
const shouldTryToResolveSilently = checkIfRefreshTokenErrorCanBeResolvedSilently(refreshTokenError, cacheLookupPolicy);
if (shouldTryToResolveSilently) {
const silentRefreshReason = `${refreshTokenError.errorCode}${refreshTokenError.subError
? `|${refreshTokenError.subError}`
: ""}`;
this.performanceClient.addFields({ silentRefreshReason }, request.correlationId);
if (!this.activeIframeRequest) {
let _resolve;
// Always set the active request tracker immediately after checking it to prevent races
this.activeIframeRequest = [
new Promise((resolve) => {
_resolve = resolve;
}),
silentRequest.correlationId,
];
this.logger.verbose("0rh08z", silentRequest.correlationId);
return invokeAsync(this.acquireTokenBySilentIframe.bind(this), AcquireTokenBySilentIframe, this.logger, this.performanceClient, silentRequest.correlationId)(silentRequest)
.then((iframeResult) => {
_resolve(true);
return iframeResult;
})
.catch((e) => {
_resolve(false);
throw e;
})
.finally(() => {
this.activeIframeRequest = undefined;
});
}
else if (cacheLookupPolicy !== CacheLookupPolicy.Skip) {
const [activePromise, activeCorrelationId] = this.activeIframeRequest;
this.logger.verbose(`1w8fso ${activeCorrelationId}`, silentRequest.correlationId);
const awaitConcurrentIframeMeasure = this.performanceClient.startMeasurement(AwaitConcurrentIframe, silentRequest.correlationId);
awaitConcurrentIframeMeasure.add({
awaitIframeCorrelationId: activeCorrelationId,
});
const activePromiseResult = await activePromise;
awaitConcurrentIframeMeasure.end({
success: activePromiseResult,
});
if (activePromiseResult) {
this.logger.verbose(`0ywzzi ${activeCorrelationId}`, silentRequest.correlationId);
// Retry cache lookup and/or RT exchange after iframe completes
return this.acquireTokenSilentNoIframe(silentRequest, cacheLookupPolicy);
}
else {
this.logger.info(`17y14q ${activeCorrelationId}`, silentRequest.correlationId);
// If previous iframe request failed, it's unlikely to succeed this time. Throw original error.
throw refreshTokenError;
}
}
else {
// Cache policy set to skip and another iframe request is already in progress
this.logger.warning("1bd4p8", silentRequest.correlationId);
return invokeAsync(this.acquireTokenBySilentIframe.bind(this), AcquireTokenBySilentIframe, this.logger, this.performanceClient, silentRequest.correlationId)(silentRequest);
}
}
else {
// Error cannot be silently resolved or iframe renewal is not allowed, interaction required
throw refreshTokenError;
}
});
return result
.then((response) => {
this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_SUCCESS, request.correlationId, InteractionType.Silent, response);
if (request.correlationId) {
this.performanceClient.addFields({
fromCache: response.fromCache,
isNativeBroker: response.fromPlatformBroker ?? false,
}, request.correlationId);
}
return response;
})
.catch((tokenRenewalError) => {
this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, request.correlationId, InteractionType.Silent, null, tokenRenewalError);
throw tokenRenewalError;
})
.finally(() => {
this.removeStateChangeListeners(trackStateChange);
});
}
/**
* AcquireTokenSilent without the iframe fallback. This is used to enable the correct fallbacks in cases where there's a potential for multiple silent requests to be made in parallel and prevent those requests from making concurrent iframe requests.
* @param silentRequest
* @param cacheLookupPolicy
* @returns
*/
async acquireTokenSilentNoIframe(silentRequest, cacheLookupPolicy) {
// if the cache policy is set to access_token only, we should not be hitting the native layer yet
if (isPlatformAuthAllowed(this.config, this.logger, silentRequest.correlationId, this.platformAuthProvider, silentRequest.authenticationScheme, this.performanceClient) &&
silentRequest.account.nativeAccountId) {
this.logger.verbose("0sczo4", silentRequest.correlationId);
this.performanceClient.addFields({ isPlatformBrokerRequest: true }, silentRequest.correlationId);
return this.acquireTokenNative(silentRequest, ApiId.acquireTokenSilent_silentFlow, silentRequest.account.nativeAccountId, cacheLookupPolicy).catch(async (e) => {
// If native token acquisition fails for availability reasons fallback to web flow
if (e instanceof NativeAuthError && isFatalNativeAuthError(e)) {
this.logger.verbose("07rkmb", silentRequest.correlationId);
this.platformAuthProvider = undefined; // Prevent future requests from continuing to attempt
// Cache will not contain tokens, given that previous WAM requests succeeded. Skip cache and RT renewal and go straight to iframe renewal
throw createClientAuthError(tokenRefreshRequired, silentRequest.correlationId);
}
throw e;
});
}
else {
this.logger.verbose("0ox81t", silentRequest.correlationId);
// add logs to identify embedded cache retrieval
if (cacheLookupPolicy === CacheLookupPolicy.AccessToken) {
this.logger.verbose("0fvwxe", silentRequest.correlationId);
}
return invokeAsync(this.acquireTokenFromCache.bind(this), AcquireTokenFromCache, this.logger, this.performanceClient, silentRequest.correlationId)(silentRequest, cacheLookupPolicy).catch((cacheError) => {
if (cacheLookupPolicy === CacheLookupPolicy.AccessToken) {
throw cacheError;
}
this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_NETWORK_START, silentRequest.correlationId, InteractionType.Silent, silentRequest);
return invokeAsync(this.acquireTokenByRefreshToken.bind(this), AcquireTokenByRefreshToken, this.logger, this.performanceClient, silentRequest.correlationId)(silentRequest, cacheLookupPolicy);
});
}
}
/**
* Pre-generates PKCE codes and stores it in local variable
* @param correlationId
*/
async preGeneratePkceCodes(correlationId) {
this.logger.verbose("1x6uj6", correlationId);
this.pkceCode = await invokeAsync(generatePkceCodes, GeneratePkceCodes, this.logger, this.performanceClient, correlationId)(this.performanceClient, this.logger, correlationId);
return Promise.resolve();
}
/**
* Provides pre-generated PKCE codes, if any
* @param correlationId
*/
getPreGeneratedPkceCodes(correlationId) {
const res = this.pkceCode ? { ...this.pkceCode } : undefined;
this.pkceCode = undefined;
if (res) {
this.logger.verbose("12js1o", correlationId);
}
else {
this.logger.verbose("1oe9ci", correlationId);
}
this.performanceClient.addFields({ usePreGeneratedPkce: !!res }, correlationId);
return res;
}
logMultipleInstances(performanceEvent, correlationId) {
const clientId = this.config.auth.clientId;
if (!window)
return;
// @ts-ignore
window.msal = window.msal || {};
// @ts-ignore
window.msal.clientIds = window.msal.clientIds || [];
// @ts-ignore
const clientIds = window.msal.clientIds;
if (clientIds.length > 0) {
this.logger.verbose("1qtz3l", correlationId);
}
// @ts-ignore
window.msal.clientIds.push(clientId);
collectInstanceStats(clientId, performanceEvent, this.logger, correlationId);
}
}
/**
* Determines whether an error thrown by the refresh token endpoint can be resolved without interaction
* @param refreshTokenError
* @param silentRequest
* @param cacheLookupPolicy
* @returns
*/
function checkIfRefreshTokenErrorCanBeResolvedSilently(refreshTokenError, cacheLookupPolicy) {
const noInteractionRequired = !(refreshTokenError instanceof InteractionRequiredAuthError &&
// For refresh token errors, bad_token does not always require interaction (silently resolvable)
refreshTokenError.subError !==
badToken);
// Errors that result when the refresh token needs to be replaced
const refreshTokenRefreshRequired = refreshTokenError.errorCode === BrowserConstants.INVALID_GRANT_ERROR ||
refreshTokenError.errorCode ===
tokenRefreshRequired;
// Errors that may be resolved before falling back to interaction (through iframe renewal)
const isSilentlyResolvable = (noInteractionRequired && refreshTokenRefreshRequired) ||
refreshTokenError.errorCode ===
noTokensFound ||
refreshTokenError.errorCode ===
refreshTokenExpired;
// Only these policies allow for an iframe renewal attempt
const tryIframeRenewal = iFrameRenewalPolicies.includes(cacheLookupPolicy);
return isSilentlyResolvable && tryIframeRenewal;
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Controller for standard native auth operations.
*/
class CustomAuthStandardController extends StandardController {
/*
* Constructor for CustomAuthStandardController.
* @param operatingContext - The operating context for the controller.
* @param customAuthApiClient - The client to use for custom auth API operations.
* @param customAuthApiClientV2 - The client to use for V2 custom auth API operations.
*/
constructor(operatingContext, customAuthApiClient, customAuthApiClientV2) {
super(operatingContext);
this.signUpStateTransitionHandlerV2 = new SignUpStateTransitionHandlerV2();
if (!this.isBrowserEnvironment) {
this.logger.verbose("1f7i3q", "");
throw new UnsupportedEnvironmentError();
}
this.logger = this.logger.clone(name, DefaultPackageInfo.VERSION);
this.customAuthConfig = operatingContext.getCustomAuthConfig();
this.authority = new CustomAuthAuthority(this.customAuthConfig.auth.authority, this.customAuthConfig, this.networkClient, this.browserStorage, this.logger, this.performanceClient, this.customAuthConfig.customAuth?.authApiProxyUrl);
const interactionClientFactory = new CustomAuthInterationClientFactory(this.customAuthConfig, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, this.performanceClient, customAuthApiClient ??
new CustomAuthApiClient(this.authority.getCustomAuthApiDomain(), this.customAuthConfig.auth.clientId, new FetchHttpClient(this.logger), this.customAuthConfig.customAuth?.capabilities?.join(" "), this.customAuthConfig.customAuth?.customAuthApiQueryParams, this.customAuthConfig.customAuth?.requestInterceptor, this.logger), this.authority, this.tokenBindingKeyManager);
this.signInClient = interactionClientFactory.create(SignInClient);
this.signUpClient = interactionClientFactory.create(SignUpClient);
this.resetPasswordClient =
interactionClientFactory.create(ResetPasswordClient);
this.jitClient = interactionClientFactory.create(JitClient);
this.mfaClient = interactionClientFactory.create(MfaClient);
this.cacheClient = interactionClientFactory.create(CustomAuthSilentCacheClient);
this.flowClientV2 = new FlowInteractionClientV2(this.customAuthConfig, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, this.performanceClient, this.authority, customAuthApiClientV2 ??
new CustomAuthApiClientV2(this.authority.getCustomAuthApiDomain(), this.customAuthConfig.auth.clientId, new FetchHttpClient(this.logger), this.customAuthConfig.customAuth?.customAuthApiQueryParams, this.customAuthConfig.customAuth?.requestInterceptor, this.logger));
}
/*
* Gets the current account from the cache.
* @param accountRetrievalInputs - Inputs for getting the current cached account
* @returns {GetAccountResult} The account result
*/
getCurrentAccount(accountRetrievalInputs) {
const correlationId = this.getCorrelationId(accountRetrievalInputs);
try {
this.logger.verbose("0mb49j", correlationId);
const account = this.cacheClient.getCurrentAccount(correlationId);
if (account) {
this.logger.verbose("1utnrc", correlationId);
return new GetAccountResult(new CustomAuthAccountData(account, this.customAuthConfig, this.cacheClient, this.logger, correlationId));
}
throw new NoCachedAccountFoundError(correlationId);
}
catch (error) {
this.logger.errorPii(`0ar5hw ${error}`, correlationId);
return GetAccountResult.createWithError(error);
}
}
/*
* Signs the user in.
* @param signInInputs - Inputs for signing in the user.
* @returns {Promise<SignInResult>} The result of the operation.
*/
async signIn(signInInputs) {
const correlationId = this.getCorrelationId(signInInputs);
try {
ensureArgumentIsNotNullOrUndefined("signInInputs", signInInputs, correlationId);
ensureArgumentIsNotEmptyString("signInInputs.username", signInInputs.username, correlationId);
this.ensureUserNotSignedIn(correlationId);
if (signInInputs.claims) {
ensureArgumentIsJSONString("signInInputs.claims", signInInputs.claims, correlationId);
}
// start the signin flow
const signInStartParams = {
clientId: this.customAuthConfig.auth.clientId,
correlationId: correlationId,
challengeType: this.customAuthConfig.customAuth.challengeTypes ?? [],
username: signInInputs.username,
password: signInInputs.password,
};
this.logger.verbose(`0mncjk ${!!signInInputs.password ? "with" : "without"}`, correlationId);
const startResult = await this.signInClient.start(signInStartParams);
this.logger.verbose("0b1x6k", correlationId);
if (startResult.type === SIGN_IN_CODE_SEND_RESULT_TYPE) {
// require code
this.logger.verbose("19jerh", correlationId);
return new SignInResult(new SignInCodeRequiredState({
correlationId: startResult.correlationId,
continuationToken: startResult.continuationToken,
logger: this.logger,
config: this.customAuthConfig,
signInClient: this.signInClient,
cacheClient: this.cacheClient,
jitClient: this.jitClient,
mfaClient: this.mfaClient,
username: signInInputs.username,
codeLength: startResult.codeLength,
scopes: signInInputs.scopes ?? [],
claims: signInInputs.claims,
}));
}
else if (startResult.type === SIGN_IN_PASSWORD_REQUIRED_RESULT_TYPE) {
// require password
this.logger.verbose("0457px", correlationId);
if (!signInInputs.password) {
this.logger.verbose("09dgsg", correlationId);
return new SignInResult(new SignInPasswordRequiredState({
correlationId: startResult.correlationId,
continuationToken: startResult.continuationToken,
logger: this.logger,
config: this.customAuthConfig,
signInClient: this.signInClient,
cacheClient: this.cacheClient,
jitClient: this.jitClient,
mfaClient: this.mfaClient,
username: signInInputs.username,
scopes: signInInputs.scopes ?? [],
claims: signInInputs.claims,
}));
}
this.logger.verbose("1dm2kj", correlationId);
// if the password is provided, then try to get token silently.
const submitPasswordParams = {
clientId: this.customAuthConfig.auth.clientId,
correlationId: correlationId,
challengeType: this.customAuthConfig.customAuth.challengeTypes ?? [],
scopes: signInInputs.scopes ?? [],
continuationToken: startResult.continuationToken,
password: signInInputs.password,
username: signInInputs.username,
claims: signInInputs.claims,
};
const submitPasswordResult = await this.signInClient.submitPassword(submitPasswordParams);
this.logger.verbose("09ajki", correlationId);
if (submitPasswordResult.type === SIGN_IN_COMPLETED_RESULT_TYPE) {
const accountInfo = new CustomAuthAccountData(submitPasswordResult.authenticationResult.account, this.customAuthConfig, this.cacheClient, this.logger, correlationId);
return new SignInResult(new SignInCompletedState(), accountInfo);
}
else if (submitPasswordResult.type ===
SIGN_IN_JIT_REQUIRED_RESULT_TYPE) {
// Authentication method registration is required - create AuthMethodRegistrationRequiredState
this.logger.verbose("187c19", correlationId);
return new SignInResult(new AuthMethodRegistrationRequiredState({
correlationId: correlationId,
continuationToken: submitPasswordResult.continuationToken,
logger: this.logger,
config: this.customAuthConfig,
jitClient: this.jitClient,
cacheClient: this.cacheClient,
authMethods: submitPasswordResult.authMethods,
username: signInInputs.username,
scopes: signInInputs.scopes ?? [],
claims: signInInputs.claims,
}));
}
else if (submitPasswordResult.type ===
SIGN_IN_MFA_REQUIRED_RESULT_TYPE) {
// MFA is required - create MfaAwaitingState
this.logger.verbose("1t79dc", correlationId);
return new SignInResult(new MfaAwaitingState({
correlationId: correlationId,
continuationToken: submitPasswordResult.continuationToken,
logger: this.logger,
config: this.customAuthConfig,
mfaClient: this.mfaClient,
cacheClient: this.cacheClient,
scopes: signInInputs.scopes ?? [],
authMethods: submitPasswordResult.authMethods ?? [],
}));
}
else {
// Unexpected result type
const result = submitPasswordResult;
const error = new Error(`Unexpected result type: ${result.type}`);
return SignInResult.createWithError(error);
}
}
this.logger.error("14awz5", correlationId);
throw new UnexpectedError("Unknow sign-in result type", correlationId);
}
catch (error) {
this.logger.errorPii(`1te6co ${error}`, correlationId);
return SignInResult.createWithError(error);
}
}
/*
* Signs the user up.
* @param signUpInputs - Inputs for signing up the user.
* @returns {Promise<SignUpResult>} The result of the operation
*/
async signUp(signUpInputs) {
const correlationId = this.getCorrelationId(signUpInputs);
try {
ensureArgumentIsNotNullOrUndefined("signUpInputs", signUpInputs, correlationId);
ensureArgumentIsNotEmptyString("signUpInputs.username", signUpInputs.username, correlationId);
this.ensureUserNotSignedIn(correlationId);
this.logger.verbose(`1f4ezz ${!!signUpInputs.password
? ` with ${!!signUpInputs.attributes
? "password and attributes"
: "password"}`
: ""}`, correlationId);
const startResult = await this.signUpClient.start({
clientId: this.customAuthConfig.auth.clientId,
correlationId: correlationId,
challengeType: this.customAuthConfig.customAuth.challengeTypes ?? [],
username: signUpInputs.username,
password: signUpInputs.password,
attributes: signUpInputs.attributes,
});
this.logger.verbose("1pwgi0", correlationId);
if (startResult.type === SIGN_UP_CODE_REQUIRED_RESULT_TYPE) {
// Code required
this.logger.verbose("1hm6bi", correlationId);
return new SignUpResult(new SignUpCodeRequiredState({
correlationId: startResult.correlationId,
continuationToken: startResult.continuationToken,
logger: this.logger,
config: this.customAuthConfig,
signInClient: this.signInClient,
signUpClient: this.signUpClient,
cacheClient: this.cacheClient,
jitClient: this.jitClient,
mfaClient: this.mfaClient,
username: signUpInputs.username,
codeLength: startResult.codeLength,
codeResendInterval: startResult.interval,
}));
}
else if (startResult.type === SIGN_UP_PASSWORD_REQUIRED_RESULT_TYPE) {
// Password required
this.logger.verbose("098u8y", correlationId);
return new SignUpResult(new SignUpPasswordRequiredState({
correlationId: startResult.correlationId,
continuationToken: startResult.continuationToken,
logger: this.logger,
config: this.customAuthConfig,
signInClient: this.signInClient,
signUpClient: this.signUpClient,
cacheClient: this.cacheClient,
jitClient: this.jitClient,
mfaClient: this.mfaClient,
username: signUpInputs.username,
}));
}
this.logger.error("12ceo3", correlationId);
throw new UnexpectedError("Unknown sign-up result type", correlationId);
}
catch (error) {
this.logger.errorPii(`1ym5p8 ${error}`, correlationId);
return SignUpResult.createWithError(error);
}
}
/*
* Resets the user's password.
* @param resetPasswordInputs - Inputs for resetting the user's password.
* @returns {Promise<ResetPasswordStartResult>} The result of the operation.
*/
async resetPassword(resetPasswordInputs) {
const correlationId = this.getCorrelationId(resetPasswordInputs);
try {
ensureArgumentIsNotNullOrUndefined("resetPasswordInputs", resetPasswordInputs, correlationId);
ensureArgumentIsNotEmptyString("resetPasswordInputs.username", resetPasswordInputs.username, correlationId);
this.ensureUserNotSignedIn(correlationId);
this.logger.verbose("1u9e3k", correlationId);
const startResult = await this.resetPasswordClient.start({
clientId: this.customAuthConfig.auth.clientId,
correlationId: correlationId,
challengeType: this.customAuthConfig.customAuth.challengeTypes ?? [],
username: resetPasswordInputs.username,
});
this.logger.verbose("1axxe2", correlationId);
return new ResetPasswordStartResult(new ResetPasswordCodeRequiredState({
correlationId: startResult.correlationId,
continuationToken: startResult.continuationToken,
logger: this.logger,
config: this.customAuthConfig,
signInClient: this.signInClient,
resetPasswordClient: this.resetPasswordClient,
cacheClient: this.cacheClient,
jitClient: this.jitClient,
mfaClient: this.mfaClient,
username: resetPasswordInputs.username,
codeLength: startResult.codeLength,
}));
}
catch (error) {
this.logger.errorPii(`1s0wwh ${error}`, correlationId);
return ResetPasswordStartResult.createWithError(error);
}
}
async resetPasswordV2(inputs) {
const correlationId = this.getCorrelationId(inputs);
try {
ensureArgumentIsNotNullOrUndefined("inputs", inputs, correlationId);
ensureArgumentIsNotEmptyString("inputs.username", inputs.username, correlationId);
this.ensureUserNotSignedIn(correlationId);
this.logger.verbose("0301h1", correlationId);
const result = await this.flowClientV2.resetPassword({
correlationId,
username: inputs.username,
});
this.logger.verbose("1yrzgs", correlationId);
if (result.type === FLOW_CODE_REQUIRED_V2) {
return new CustomAuthResultV2(new CodeRequiredStateV2({
correlationId: result.correlationId,
logger: this.logger,
config: this.customAuthConfig,
flowClient: this.flowClientV2,
continuationState: result.continuationState,
cacheClient: this.cacheClient,
method: result.method,
sentTo: result.sentTo,
channel: result.channel,
codeLength: result.codeLength,
}), undefined, result.continuationState.scenario);
}
return new CustomAuthResultV2(new AuthMethodSelectionRequiredStateV2({
correlationId: result.correlationId,
logger: this.logger,
config: this.customAuthConfig,
flowClient: this.flowClientV2,
continuationState: result.continuationState,
cacheClient: this.cacheClient,
methods: result.methods,
}), undefined, result.continuationState.scenario);
}
catch (error) {
this.logger.errorPii(`1f279y ${error}`, correlationId);
return CustomAuthResultV2.createWithError(error, {
errorType: ResetPasswordStartErrorV2,
scenario: CustomAuthFlowScenarioV2.PasswordReset,
correlationId,
});
}
}
async signInV2(inputs) {
const correlationId = this.getCorrelationId(inputs);
try {
ensureArgumentIsNotNullOrUndefined("inputs", inputs, correlationId);
ensureArgumentIsNotEmptyString("inputs.username", inputs.username, correlationId);
if (inputs.claims) {
ensureArgumentIsJSONString("inputs.claims", inputs.claims, correlationId);
}
this.ensureUserNotSignedIn(correlationId);
this.logger.verbose("145cnd", correlationId);
const result = await this.flowClientV2.signIn({
correlationId,
username: inputs.username,
password: inputs.password,
scopes: inputs.scopes,
});
if (result.type === FLOW_COMPLETED_V2) {
return new CustomAuthResultV2(new CompletedStateV2(), new CustomAuthAccountData(result.authenticationResult.account, this.customAuthConfig, this.cacheClient, this.logger, correlationId), CustomAuthFlowScenarioV2.SignIn);
}
if (result.type === FLOW_MFA_REQUIRED_V2) {
return new CustomAuthResultV2(new MFARequiredStateV2({
correlationId: result.correlationId,
logger: this.logger,
config: this.customAuthConfig,
flowClient: this.flowClientV2,
continuationState: result.continuationState,
cacheClient: this.cacheClient,
methods: result.methods,
}), undefined, result.continuationState.scenario);
}
if (result.type === FLOW_CODE_REQUIRED_V2) {
return new CustomAuthResultV2(new CodeRequiredStateV2({
correlationId: result.correlationId,
logger: this.logger,
config: this.customAuthConfig,
flowClient: this.flowClientV2,
continuationState: result.continuationState,
cacheClient: this.cacheClient,
method: result.method,
sentTo: result.sentTo,
channel: result.channel,
codeLength: result.codeLength,
}), undefined, result.continuationState.scenario);
}
if (result.type === FLOW_PASSWORD_REQUIRED_V2) {
return new CustomAuthResultV2(new PasswordRequiredStateV2({
correlationId: result.correlationId,
logger: this.logger,
config: this.customAuthConfig,
flowClient: this.flowClientV2,
continuationState: result.continuationState,
cacheClient: this.cacheClient,
}), undefined, result.continuationState.scenario);
}
throw new UnexpectedError("Unsupported native auth V2 sign-in result type.", correlationId);
}
catch (error) {
this.logger.errorPii(`11afy0 ${error}`, correlationId);
return CustomAuthResultV2.createWithError(error, {
errorType: SignInStartErrorV2,
scenario: CustomAuthFlowScenarioV2.SignIn,
correlationId,
});
}
}
async signUpV2(inputs) {
const correlationId = this.getCorrelationId(inputs);
try {
ensureArgumentIsNotNullOrUndefined("inputs", inputs, correlationId);
ensureArgumentIsNotEmptyString("inputs.username", inputs.username, correlationId);
if (Object.prototype.hasOwnProperty.call(inputs, "password")) {
ensureArgumentIsNotNullOrUndefined("inputs.password", inputs.password, correlationId);
ensureArgumentIsNotEmptyString("inputs.password", inputs.password, correlationId);
}
this.ensureUserNotSignedIn(correlationId);
this.logger.verbose("0010xn", correlationId);
const result = await this.flowClientV2.signUp({
correlationId,
username: inputs.username,
password: inputs.password,
attributes: inputs.attributes,
scopes: inputs.scopes,
claims: inputs.claims,
});
const commonStateParameters = {
correlationId: result.correlationId,
logger: this.logger,
config: this.customAuthConfig,
flowClient: this.flowClientV2,
continuationState: result.continuationState,
cacheClient: this.cacheClient,
signUpStateTransitionHandler: this.signUpStateTransitionHandlerV2,
};
if (result.type === FLOW_CODE_REQUIRED_V2) {
return new CustomAuthResultV2(new CodeRequiredStateV2({
...commonStateParameters,
sentTo: result.sentTo,
channel: result.channel,
codeLength: result.codeLength,
}), undefined, result.continuationState.scenario);
}
if (result.type === FLOW_SIGN_UP_PASSWORD_REQUIRED_V2) {
return new CustomAuthResultV2(new SignUpPasswordRequiredStateV2({
...commonStateParameters,
attributes: result.attributes,
requiredPasswordAttribute: result.requiredPasswordAttribute,
}), undefined, result.continuationState.scenario);
}
if (result.type === FLOW_ATTRIBUTES_REQUIRED_V2) {
return new CustomAuthResultV2(new AttributesRequiredStateV2({
...commonStateParameters,
attributes: result.attributes,
}), undefined, result.continuationState.scenario);
}
throw new UnexpectedError("Unsupported native auth V2 sign-up result type.", correlationId);
}
catch (error) {
this.logger.errorPii(`196wno ${error}`, correlationId);
return CustomAuthResultV2.createWithError(error, {
errorType: SignUpStartErrorV2,
scenario: CustomAuthFlowScenarioV2.SignUp,
correlationId,
});
}
}
getCorrelationId(actionInputs) {
return (actionInputs?.correlationId || this.browserCrypto.createNewGuid());
}
ensureUserNotSignedIn(correlationId) {
const account = this.getCurrentAccount({
correlationId: correlationId,
});
if (account && !!account.data) {
this.logger.error("1a17tw", correlationId);
throw new UserAlreadySignedInError(correlationId);
}
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Base class for operating context
* Operating contexts are contexts in which MSAL.js is being run
* More than one operating context may be available at a time
* It's important from a logging and telemetry point of view for us to be able to identify the operating context.
* For example: Some operating contexts will pre-cache tokens impacting performance telemetry
*/
class BaseOperatingContext {
static loggerCallback(level, message) {
switch (level) {
case exports.LogLevel.Error:
// eslint-disable-next-line no-console
console.error(message);
return;
case exports.LogLevel.Info:
// eslint-disable-next-line no-console
console.info(message);
return;
case exports.LogLevel.Verbose:
// eslint-disable-next-line no-console
console.debug(message);
return;
case exports.LogLevel.Warning:
// eslint-disable-next-line no-console
console.warn(message);
return;
default:
// eslint-disable-next-line no-console
console.log(message);
return;
}
}
constructor(config, responseHandlers) {
/*
* If loaded in an environment where window is not available,
* set internal flag to false so that further requests fail.
* This is to support server-side rendering environments.
*/
this.browserEnvironment = typeof window !== "undefined";
this.config = buildConfiguration(config, this.browserEnvironment);
this.responseHandlers = responseHandlers;
let sessionStorage;
try {
sessionStorage = window[BrowserCacheLocation.SessionStorage];
// Mute errors if it's a non-browser environment or cookies are blocked.
}
catch (e) { }
const logLevelKey = sessionStorage?.getItem(LOG_LEVEL_CACHE_KEY);
const piiLoggingKey = sessionStorage
?.getItem(LOG_PII_CACHE_KEY)
?.toLowerCase();
const piiLoggingEnabled = piiLoggingKey === "true"
? true
: piiLoggingKey === "false"
? false
: undefined;
const loggerOptions = { ...this.config.system.loggerOptions };
const logLevel = logLevelKey && Object.keys(exports.LogLevel).includes(logLevelKey)
? exports.LogLevel[logLevelKey]
: undefined;
if (logLevel) {
loggerOptions.loggerCallback = BaseOperatingContext.loggerCallback;
loggerOptions.logLevel = logLevel;
}
if (piiLoggingEnabled !== undefined) {
loggerOptions.piiLoggingEnabled = piiLoggingEnabled;
}
this.logger = new Logger(loggerOptions, name, version);
this.available = false;
}
/**
* Return the MSAL config
* @returns BrowserConfiguration
*/
getConfig() {
return this.config;
}
/**
* Returns the internal response handlers supplied by PublicClientApplication, if any.
* @returns AuthResponseHandlers | undefined
*/
getResponseHandlers() {
return this.responseHandlers;
}
/**
* Returns the MSAL Logger
* @returns Logger
*/
getLogger() {
return this.logger;
}
isAvailable() {
return this.available;
}
isBrowserEnvironment() {
return this.browserEnvironment;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class CustomAuthOperatingContext extends BaseOperatingContext {
constructor(configuration) {
super(configuration);
this.customAuthOptions = configuration.customAuth;
}
getModuleName() {
return CustomAuthOperatingContext.MODULE_NAME;
}
getId() {
return CustomAuthOperatingContext.ID;
}
getCustomAuthConfig() {
return {
...this.getConfig(),
customAuth: this.customAuthOptions,
};
}
async initialize() {
this.available = typeof window !== "undefined";
return this.available;
}
}
CustomAuthOperatingContext.MODULE_NAME = "";
CustomAuthOperatingContext.ID = "CustomAuthOperatingContext";
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class InvalidConfigurationError extends CustomAuthError {
constructor(error, message, correlationId) {
super(error, message, correlationId);
Object.setPrototypeOf(this, InvalidConfigurationError.prototype);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class StandardOperatingContext extends BaseOperatingContext {
/**
* Return the module name. Intended for use with import() to enable dynamic import
* of the implementation associated with this operating context
* @returns
*/
getModuleName() {
return StandardOperatingContext.MODULE_NAME;
}
/**
* Returns the unique identifier for this operating context
* @returns string
*/
getId() {
return StandardOperatingContext.ID;
}
/**
* Checks whether the operating context is available.
* Confirms that the code is running a browser rather. This is required.
* @returns Promise<boolean> indicating whether this operating context is currently available.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async initialize(correlationId) {
this.available = typeof window !== "undefined";
return this.available;
/*
* NOTE: The standard context is available as long as there is a window. If/when we split out WAM from Browser
* We can move the current contents of the initialize method to here and verify that the WAM extension is available
*/
}
}
/*
* TODO: Once we have determine the bundling code return here to specify the name of the bundle
* containing the implementation for this operating context
*/
StandardOperatingContext.MODULE_NAME = "";
/**
* Unique identifier for the operating context
*/
StandardOperatingContext.ID = "StandardOperatingContext";
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const BridgeStatusCode = {
NestedAppAuthUnavailable: "NESTED_APP_AUTH_UNAVAILABLE", // NAA is unavailable in the current context, can retry with standard browser based auth
};
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Correlates outbound requests with inbound responses by `requestId`.
*/
class PendingRequestRegistry {
constructor() {
this.pending = new Map();
}
/**
* Register a pending request. Returns a promise that resolves when a
* response with the matching `requestId` arrives, or rejects if the
* caller invokes `reject` for that id.
*/
register(requestId) {
return new Promise((resolve, reject) => {
this.pending.set(requestId, { resolve, reject });
});
}
/** Resolve a pending request. No-op if `requestId` isn't registered. */
resolve(requestId, response) {
const entry = this.pending.get(requestId);
if (entry === undefined) {
return;
}
this.pending.delete(requestId);
entry.resolve(response);
}
/** Reject a pending request. No-op if `requestId` isn't registered. */
reject(requestId, reason) {
const entry = this.pending.get(requestId);
if (entry === undefined) {
return;
}
this.pending.delete(requestId);
entry.reject(reason);
}
/** True if `requestId` has an in-flight registration. */
has(requestId) {
return this.pending.has(requestId);
}
/**
* Register, then invoke `send` synchronously. If `send` throws, the
* pending entry is cleared and the promise rejects with the thrown
* error.
*/
async sendAndAwait(message, send) {
const promise = this.register(message.requestId);
try {
send(message);
}
catch (err) {
this.reject(message.requestId, err);
}
return promise;
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* BridgeProxy
* Provides a proxy for accessing a bridge to a host app and/or
* platform broker
*/
class BridgeProxy {
/**
* initializeNestedAppAuthBridge - Initializes the bridge to the host app
* @returns a promise that resolves to an InitializeBridgeResponse or rejects with an Error
* @remarks This method will be called by the create factory method
* @remarks If the bridge is not available, this method will throw an error
*/
static async initializeNestedAppAuthBridge() {
if (window === undefined) {
throw new Error("window is undefined");
}
if (window.nestedAppAuthBridge === undefined) {
throw new Error("window.nestedAppAuthBridge is undefined");
}
try {
window.nestedAppAuthBridge.addEventListener("message", (response) => {
const responsePayload = typeof response === "string" ? response : response.data;
const responseEnvelope = JSON.parse(responsePayload);
if (responseEnvelope.success) {
BridgeProxy.pendingRegistry.resolve(responseEnvelope.requestId, responseEnvelope);
}
else {
BridgeProxy.pendingRegistry.reject(responseEnvelope.requestId, responseEnvelope.error);
}
});
const bridgeResponse = await BridgeProxy.sendRequestViaRegistry(BridgeProxy.buildRequest("GetInitContext"));
return BridgeProxy.validateBridgeResultOrThrow(bridgeResponse.initContext);
}
catch (error) {
window.console.log(error);
throw error;
}
}
/**
* getTokenInteractive - Attempts to get a token interactively from the bridge
* @param request A token request
* @returns a promise that resolves to an auth result or rejects with a BridgeError
*/
getTokenInteractive(request) {
return this.getToken("GetTokenPopup", request);
}
/**
* getTokenSilent Attempts to get a token silently from the bridge
* @param request A token request
* @returns a promise that resolves to an auth result or rejects with a BridgeError
*/
getTokenSilent(request) {
return this.getToken("GetToken", request);
}
async getToken(requestType, request) {
const result = await this.sendRequest(requestType, {
tokenParams: request,
});
return {
token: BridgeProxy.validateBridgeResultOrThrow(result.token),
account: BridgeProxy.validateBridgeResultOrThrow(result.account),
};
}
getHostCapabilities() {
return this.capabilities ?? null;
}
getAccountContext() {
return this.accountContext ? this.accountContext : null;
}
static buildRequest(method, requestParams) {
return {
messageType: "NestedAppAuthRequest",
method: method,
requestId: createNewGuid(),
sendTime: Date.now(),
clientLibrary: BrowserConstants.MSAL_SKU,
clientLibraryVersion: version,
...requestParams,
};
}
/**
* A method used to send a request to the bridge
* @param request A token request
* @returns a promise that resolves to a response of provided type or rejects with a BridgeError
*/
sendRequest(method, requestParams) {
return BridgeProxy.sendRequestViaRegistry(BridgeProxy.buildRequest(method, requestParams));
}
/**
* Registers `message.requestId` with the shared pending-request
* registry, then posts the envelope over the host bridge. Resolves
* with the matching response envelope; rejects with the raw
* `BridgeError` payload.
*/
static sendRequestViaRegistry(message) {
const correlationKey = {
requestId: message.requestId,
type: message.method,
};
return BridgeProxy.pendingRegistry.sendAndAwait(correlationKey, () => {
window.nestedAppAuthBridge.postMessage(JSON.stringify(message));
});
}
static validateBridgeResultOrThrow(input) {
if (input === undefined) {
const bridgeError = {
status: BridgeStatusCode.NestedAppAuthUnavailable,
};
throw bridgeError;
}
return input;
}
/**
* Private constructor for BridgeProxy
* @param sdkName The name of the SDK being used to make requests on behalf of the app
* @param sdkVersion The version of the SDK being used to make requests on behalf of the app
* @param capabilities The capabilities of the bridge / SDK / platform broker
*/
constructor(sdkName, sdkVersion, accountContext, capabilities) {
this.sdkName = sdkName;
this.sdkVersion = sdkVersion;
this.accountContext = accountContext;
this.capabilities = capabilities;
}
/**
* Factory method for creating an implementation of IBridgeProxy
* @returns A promise that resolves to a BridgeProxy implementation
*/
static async create() {
const response = await BridgeProxy.initializeNestedAppAuthBridge();
return new BridgeProxy(response.sdkName, response.sdkVersion, response.accountContext, response.capabilities);
}
}
/**
* Correlates outbound bridge requests with inbound responses by
* `requestId`
*/
BridgeProxy.pendingRegistry = new PendingRequestRegistry();
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class NestedAppOperatingContext extends BaseOperatingContext {
constructor() {
super(...arguments);
this.bridgeProxy = undefined;
this.accountContext = null;
}
/**
* Return the module name. Intended for use with import() to enable dynamic import
* of the implementation associated with this operating context
* @returns
*/
getModuleName() {
return NestedAppOperatingContext.MODULE_NAME;
}
/**
* Returns the unique identifier for this operating context
* @returns string
*/
getId() {
return NestedAppOperatingContext.ID;
}
/**
* Returns the current BridgeProxy
* @returns IBridgeProxy | undefined
*/
getBridgeProxy() {
return this.bridgeProxy;
}
/**
* Checks whether the operating context is available.
* Confirms that the code is running a browser rather. This is required.
* @param correlationId
* @returns Promise<boolean> indicating whether this operating context is currently available.
*/
async initialize(correlationId) {
const cid = correlationId || "";
try {
if (typeof window !== "undefined") {
if (typeof window.__initializeNestedAppAuth === "function") {
await window.__initializeNestedAppAuth();
}
const bridgeProxy = await BridgeProxy.create();
/*
* Because we want single sign on we expect the host app to provide the account context
* with a min set of params that can be used to identify the account
* this.account = nestedApp.getAccountByFilter(bridgeProxy.getAccountContext());
*/
this.accountContext = bridgeProxy.getAccountContext();
this.bridgeProxy = bridgeProxy;
this.available = bridgeProxy !== undefined;
}
}
catch (ex) {
this.logger.infoPii(`1mdxyj ${ex}`, cid);
}
this.logger.info(`12jy9a ${this.available}`, cid);
return this.available;
}
}
/*
* TODO: Once we have determine the bundling code return here to specify the name of the bundle
* containing the implementation for this operating context
*/
NestedAppOperatingContext.MODULE_NAME = "";
/**
* Unique identifier for the operating context
*/
NestedAppOperatingContext.ID = "NestedAppOperatingContext";
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* The PublicClientApplication class is the object exposed by the library to perform authentication and authorization functions in Single Page Applications
* to obtain JWT tokens as described in the OAuth 2.0 Authorization Code Flow with PKCE specification.
*/
class PublicClientApplication {
/**
* @constructor
* Constructor for the PublicClientApplication used to instantiate the PublicClientApplication object
*
* Important attributes in the Configuration object for auth are:
* - clientID: the application ID of your application. You can obtain one by registering your application with our Application registration portal : https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredAppsPreview
* - authority: the authority URL for your application.
* - redirect_uri: the uri of your application registered in the portal.
*
* In Azure AD, authority is a URL indicating the Azure active directory that MSAL uses to obtain tokens.
* It is of the form https://login.microsoftonline.com/{Enter_the_Tenant_Info_Here}
* If your application supports Accounts in one organizational directory, replace "Enter_the_Tenant_Info_Here" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com).
* If your application supports Accounts in any organizational directory, replace "Enter_the_Tenant_Info_Here" value with organizations.
* If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace "Enter_the_Tenant_Info_Here" value with common.
* To restrict support to Personal Microsoft accounts only, replace "Enter_the_Tenant_Info_Here" value with consumers.
*
* In Azure B2C, authority is of the form https://{instance}/tfp/{tenant}/{policyName}/
* Full B2C functionality will be available in this library in future versions.
*
* @param configuration Object for the MSAL PublicClientApplication instance
* @param IController Optional parameter to explictly set the controller. (Will be removed when we remove public constructor)
*/
constructor(configuration, controller) {
this.controller =
controller ||
new StandardController(new StandardOperatingContext(configuration, {
waitForPopupResponse: this.waitForPopupResponse.bind(this),
waitForIframeResponse: this.waitForIframeResponse.bind(this),
}));
}
/**
* Waits for the auth response from a popup window opened by MSAL.
*
* The default implementation delegates to MSAL's `BroadcastChannel`-based bridge.
* Subclasses must return the raw response string (hash/query/fragment), or reject
* with an `AuthError` on failure.
*
* @internal
* @param request The in-flight authorization or end-session request.
* @param popupWindow The popup window opened by MSAL.
* @param popupWindowParent The parent window that opened the popup.
*/
async waitForPopupResponse(request,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
popupWindow,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
popupWindowParent) {
const controller = this.controller;
return waitForBridgeResponse(controller.getConfiguration().system.popupBridgeTimeout, controller.getLogger(), request, controller.getPerformanceClient());
}
/**
* Waits for the auth response from a hidden iframe used by MSAL silent flows.
*
* The default implementation delegates to MSAL's `BroadcastChannel`-based bridge.
* Subclasses must return the raw response string (hash/query/fragment), or reject
* with an `AuthError` on failure.
*
* @internal
* @param iframe The hidden iframe MSAL attached to the document.
* @param request The in-flight authorization request.
*/
async waitForIframeResponse(
// eslint-disable-next-line @typescript-eslint/no-unused-vars
iframe, request) {
const controller = this.controller;
const config = controller.getConfiguration();
return waitForBridgeResponse(config.system.iframeBridgeTimeout, controller.getLogger(), request, controller.getPerformanceClient(), config.experimental);
}
/**
* Initializer function to perform async startup tasks such as connecting to WAM extension
* @param request {?InitializeApplicationRequest}
*/
async initialize(request) {
return this.controller.initialize(request);
}
/**
* Use when you want to obtain an access_token for your API via opening a popup window in the user's browser
*
* @param request
*
* @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
*/
async acquireTokenPopup(request) {
return this.controller.acquireTokenPopup(request);
}
/**
* Use when you want to obtain an access_token for your API by redirecting the user's browser window to the authorization endpoint. This function redirects
* the page, so any code that follows this function will not execute.
*
* IMPORTANT: It is NOT recommended to have code that is dependent on the resolution of the Promise. This function will navigate away from the current
* browser window. It currently returns a Promise in order to reflect the asynchronous nature of the code running in this function.
*
* @param request
*/
acquireTokenRedirect(request) {
return this.controller.acquireTokenRedirect(request);
}
/**
* Silently acquire an access token for a given set of scopes. Returns currently processing promise if parallel requests are made.
*
* @param {@link (SilentRequest:type)}
* @returns {Promise.<AuthenticationResult>} - a promise that is fulfilled when this function has completed, or rejected if an error was raised. Returns the {@link AuthenticationResult} object
*/
acquireTokenSilent(silentRequest) {
return this.controller.acquireTokenSilent(silentRequest);
}
/**
* This function redeems an authorization code (passed as code) from the eSTS token endpoint.
* This authorization code should be acquired server-side using a confidential client to acquire a spa_code.
* This API is not indended for normal authorization code acquisition and redemption.
*
* Redemption of this authorization code will not require PKCE, as it was acquired by a confidential client.
*
* @param request {@link AuthorizationCodeRequest}
* @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
*/
acquireTokenByCode(request) {
return this.controller.acquireTokenByCode(request);
}
/**
* Adds event callbacks to array
* @param callback
* @param eventTypes
*/
addEventCallback(callback, eventTypes) {
return this.controller.addEventCallback(callback, eventTypes);
}
/**
* Removes callback with provided id from callback array
* @param callbackId
*/
removeEventCallback(callbackId) {
return this.controller.removeEventCallback(callbackId);
}
/**
* Registers a callback to receive performance events.
*
* @param {PerformanceCallbackFunction} callback
* @returns {string}
*/
addPerformanceCallback(callback) {
return this.controller.addPerformanceCallback(callback);
}
/**
* Removes a callback registered with addPerformanceCallback.
*
* @param {string} callbackId
* @returns {boolean}
*/
removePerformanceCallback(callbackId) {
return this.controller.removePerformanceCallback(callbackId);
}
/**
* Returns the first account found in the cache that matches the account filter passed in.
* @param accountFilter
* @returns The first account found in the cache matching the provided filter or null if no account could be found.
*/
getAccount(accountFilter) {
return this.controller.getAccount(accountFilter);
}
/**
* Returns all the accounts in the cache that match the optional filter. If no filter is provided, all accounts are returned.
* @param accountFilter - (Optional) filter to narrow down the accounts returned
* @returns Array of AccountInfo objects in cache
*/
getAllAccounts(accountFilter) {
return this.controller.getAllAccounts(accountFilter);
}
/**
* Event handler function which allows users to fire events after the PublicClientApplication object
* has loaded during redirect flows. This should be invoked on all page loads involved in redirect
* auth flows.
* @param hash Hash to process. Defaults to the current value of window.location.hash. Only needs to be provided explicitly if the response to be handled is not contained in the current value.
* @param options Object containing optional configuration for redirect promise handling.
* @returns Token response or null. If the return value is null, then no auth redirect was detected.
*/
handleRedirectPromise(options) {
return this.controller.handleRedirectPromise(options);
}
/**
* Use when initiating the login process via opening a popup window in the user's browser
*
* @param request
*
* @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
*/
loginPopup(request) {
return this.controller.loginPopup(request);
}
/**
* Use when initiating the login process by redirecting the user's browser to the authorization endpoint. This function redirects the page, so
* any code that follows this function will not execute.
*
* IMPORTANT: It is NOT recommended to have code that is dependent on the resolution of the Promise. This function will navigate away from the current
* browser window. It currently returns a Promise in order to reflect the asynchronous nature of the code running in this function.
*
* @param request
*/
loginRedirect(request) {
return this.controller.loginRedirect(request);
}
/**
* Use to log out the current user, and redirect the user to the postLogoutRedirectUri.
* Default behaviour is to redirect the user to `window.location.href`.
* @param logoutRequest
*/
logoutRedirect(logoutRequest) {
return this.controller.logoutRedirect(logoutRequest);
}
/**
* Clears local cache for the current user then opens a popup window prompting the user to sign-out of the server
* @param logoutRequest
*/
logoutPopup(logoutRequest) {
return this.controller.logoutPopup(logoutRequest);
}
/**
* This function uses a hidden iframe to fetch an authorization code from the eSTS. There are cases where this may not work:
* - Any browser using a form of Intelligent Tracking Prevention
* - If there is not an established session with the service
*
* In these cases, the request must be done inside a popup or full frame redirect.
*
* For the cases where interaction is required, you cannot send a request with prompt=none.
*
* If your refresh token has expired, you can use this function to fetch a new set of tokens silently as long as
* you session on the server still exists.
* @param request {@link SsoSilentRequest}
*
* @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
*/
ssoSilent(request) {
return this.controller.ssoSilent(request);
}
/**
* Returns the logger instance
*/
getLogger() {
return this.controller.getLogger();
}
/**
* Replaces the default logger set in configurations with new Logger with new configurations
* @param logger Logger instance
*/
setLogger(logger) {
this.controller.setLogger(logger);
}
/**
* Sets the account to use as the active account. If no account is passed to the acquireToken APIs, then MSAL will use this active account.
* @param account
*/
setActiveAccount(account) {
this.controller.setActiveAccount(account);
}
/**
* Gets the currently active account
*/
getActiveAccount() {
return this.controller.getActiveAccount();
}
/**
* Called by wrapper libraries (Angular & React) to set SKU and Version passed down to telemetry, logger, etc.
* @param sku
* @param version
*/
initializeWrapperLibrary(sku, version) {
return this.controller.initializeWrapperLibrary(sku, version);
}
/**
* Sets navigation client
* @param navigationClient
*/
setNavigationClient(navigationClient) {
this.controller.setNavigationClient(navigationClient);
}
/**
* Returns the configuration object
* @internal
*/
getConfiguration() {
return this.controller.getConfiguration();
}
/**
* Hydrates cache with the tokens and account in the AuthenticationResult object
* @param result
* @param request - The request object that was used to obtain the AuthenticationResult
* @returns
*/
async hydrateCache(result, request) {
return this.controller.hydrateCache(result, request);
}
/**
* Clears tokens and account from the browser cache.
* @param logoutRequest
*/
clearCache(logoutRequest) {
return this.controller.clearCache(logoutRequest);
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const MissingConfiguration = "missing_configuration";
const InvalidAuthority = "invalid_authority";
const InvalidChallengeType = "invalid_challenge_type";
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class CustomAuthPublicClientApplication extends PublicClientApplication {
/**
* Creates a new instance of a PublicClientApplication with the given configuration and controller to start Native authentication flows
* @param {CustomAuthConfiguration} config - A configuration object for the PublicClientApplication instance
* @returns {Promise<ICustomAuthPublicClientApplicationV2>} - A promise that resolves to a CustomAuthPublicClientApplication instance
*/
static async create(config) {
CustomAuthPublicClientApplication.validateConfig(config);
const customAuthController = new CustomAuthStandardController(new CustomAuthOperatingContext(config));
await customAuthController.initialize();
const app = new CustomAuthPublicClientApplication(config, customAuthController);
return app;
}
constructor(config, controller) {
super(config, controller);
this.customAuthController = controller;
}
/**
* Gets the current account from the browser cache.
* @param {AccountRetrievalInputs} accountRetrievalInputs?:AccountRetrievalInputs
* @returns {GetAccountResult} - The result of the get account operation
*/
getCurrentAccount(accountRetrievalInputs) {
return this.customAuthController.getCurrentAccount(accountRetrievalInputs);
}
/**
* Initiates the sign-in flow.
* This method results in sign-in completion, or extra actions (password, code, etc.) required to complete the sign-in.
* Create result with error details if any exception thrown.
* @param {SignInInputs} signInInputs - Inputs for the sign-in flow
* @returns {Promise<SignInResult>} - A promise that resolves to SignInResult
*/
signIn(signInInputs) {
return this.customAuthController.signIn(signInInputs);
}
/**
* Initiates the sign-up flow.
* This method results in sign-up completion, or extra actions (password, code, etc.) required to complete the sign-up.
* Create result with error details if any exception thrown.
* @param {SignUpInputs} signUpInputs
* @returns {Promise<SignUpResult>} - A promise that resolves to SignUpResult
*/
signUp(signUpInputs) {
return this.customAuthController.signUp(signUpInputs);
}
/**
* Initiates the reset password flow.
* This method results in triggering extra action (submit code) to complete the reset password.
* Create result with error details if any exception thrown.
* @param {ResetPasswordInputs} resetPasswordInputs - Inputs for the reset password flow
* @returns {Promise<ResetPasswordStartResult>} - A promise that resolves to ResetPasswordStartResult
*/
resetPassword(resetPasswordInputs) {
return this.customAuthController.resetPassword(resetPasswordInputs);
}
/**
* Starts native auth V2 sign-in and returns the authentication methods
* offered for the first factor.
* @param inputs - Inputs for the sign-in V2 flow.
* @returns A promise that resolves to the sign-in start result.
*/
signInV2(inputs) {
return this.customAuthController.signInV2(inputs);
}
/**
* Starts native auth V2 sign-up.
* @param inputs - Inputs for the sign-up V2 flow.
* @returns A promise that resolves to the sign-up start result.
*/
signUpV2(inputs) {
return this.customAuthController.signUpV2(inputs);
}
/**
* Initiates the native auth V2 self-service password reset flow.
* @param {ResetPasswordInputsV2} inputs - Inputs for the reset-password V2 flow
* @returns {Promise<ResetPasswordStartResultV2>} - A promise that resolves to ResetPasswordStartResultV2
*/
resetPasswordV2(inputs) {
return this.customAuthController.resetPasswordV2(inputs);
}
/**
* Validates the configuration to ensure it is a valid CustomAuthConfiguration object.
* @param {CustomAuthConfiguration} config - The configuration object for the PublicClientApplication.
* @returns {void}
*/
static validateConfig(config) {
// Ensure the configuration object has a valid CIAM authority URL.
if (!config) {
throw new InvalidConfigurationError(MissingConfiguration, "The configuration is missing.");
}
if (!config.auth?.authority) {
throw new InvalidConfigurationError(InvalidAuthority, `The authority URL '${config.auth?.authority}' is not set.`);
}
const challengeTypes = config.customAuth.challengeTypes;
if (!!challengeTypes && challengeTypes.length > 0) {
challengeTypes.forEach((challengeType) => {
const lowerCaseChallengeType = challengeType.toLowerCase();
if (lowerCaseChallengeType !== ChallengeType.PASSWORD &&
lowerCaseChallengeType !== ChallengeType.OOB &&
lowerCaseChallengeType !== ChallengeType.REDIRECT) {
throw new InvalidConfigurationError(InvalidChallengeType, `Challenge type ${challengeType} in the configuration are not valid. Supported challenge types are ${Object.values(ChallengeType)}`);
}
});
}
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
class UserAccountAttributeError extends CustomAuthError {
constructor(error, attributeName, attributeValue) {
const errorDescription = `Failed to set attribute '${attributeName}' with value '${attributeValue}'`;
super(error, errorDescription);
Object.setPrototypeOf(this, UserAccountAttributeError.prototype);
}
}
exports.AttributesRequiredStateV2 = AttributesRequiredStateV2;
exports.AuthFlowActionRequiredStateBase = AuthFlowActionRequiredStateBase;
exports.AuthFlowStateBase = AuthFlowStateBase;
exports.AuthMethodRegistrationChallengeMethodError = AuthMethodRegistrationChallengeMethodError;
exports.AuthMethodRegistrationChallengeMethodResult = AuthMethodRegistrationChallengeMethodResult;
exports.AuthMethodRegistrationCompletedState = AuthMethodRegistrationCompletedState;
exports.AuthMethodRegistrationFailedState = AuthMethodRegistrationFailedState;
exports.AuthMethodRegistrationRequiredState = AuthMethodRegistrationRequiredState;
exports.AuthMethodRegistrationSubmitChallengeError = AuthMethodRegistrationSubmitChallengeError;
exports.AuthMethodRegistrationSubmitChallengeResult = AuthMethodRegistrationSubmitChallengeResult;
exports.AuthMethodSelectionRequiredStateV2 = AuthMethodSelectionRequiredStateV2;
exports.AuthMethodVerificationRequiredState = AuthMethodVerificationRequiredState;
exports.CodeRequiredStateV2 = CodeRequiredStateV2;
exports.CompletedStateV2 = CompletedStateV2;
exports.CustomAuthAccountData = CustomAuthAccountData;
exports.CustomAuthApiError = CustomAuthApiError;
exports.CustomAuthError = CustomAuthError;
exports.CustomAuthFlowScenarioV2 = CustomAuthFlowScenarioV2;
exports.CustomAuthPublicClientApplication = CustomAuthPublicClientApplication;
exports.CustomAuthResultV2 = CustomAuthResultV2;
exports.FailedStateV2 = FailedStateV2;
exports.GetAccessTokenResult = GetAccessTokenResult;
exports.GetAccountError = GetAccountError;
exports.GetAccountResult = GetAccountResult;
exports.GetCurrentAccountAccessTokenError = GetCurrentAccountAccessTokenError;
exports.HttpError = HttpError;
exports.InvalidArgumentError = InvalidArgumentError;
exports.InvalidConfigurationError = InvalidConfigurationError;
exports.MFARequiredStateV2 = MFARequiredStateV2;
exports.MFAVerificationRequiredStateV2 = MFAVerificationRequiredStateV2;
exports.MethodNotImplementedError = MethodNotImplementedError;
exports.MfaAwaitingState = MfaAwaitingState;
exports.MfaCompletedState = MfaCompletedState;
exports.MfaFailedState = MfaFailedState;
exports.MfaRequestChallengeError = MfaRequestChallengeError;
exports.MfaRequestChallengeResult = MfaRequestChallengeResult;
exports.MfaSubmitChallengeError = MfaSubmitChallengeError;
exports.MfaSubmitChallengeResult = MfaSubmitChallengeResult;
exports.MfaVerificationRequiredState = MfaVerificationRequiredState;
exports.MsalCustomAuthError = MsalCustomAuthError;
exports.NewPasswordRequiredStateV2 = NewPasswordRequiredStateV2;
exports.NoCachedAccountFoundError = NoCachedAccountFoundError;
exports.ParsedUrlError = ParsedUrlError;
exports.PasswordRequiredStateV2 = PasswordRequiredStateV2;
exports.RequestChallengeErrorV2 = RequestChallengeErrorV2;
exports.ResetPasswordCodeRequiredState = ResetPasswordCodeRequiredState;
exports.ResetPasswordCompletedState = ResetPasswordCompletedState;
exports.ResetPasswordError = ResetPasswordError;
exports.ResetPasswordFailedState = ResetPasswordFailedState;
exports.ResetPasswordPasswordRequiredState = ResetPasswordPasswordRequiredState;
exports.ResetPasswordResendCodeError = ResetPasswordResendCodeError;
exports.ResetPasswordResendCodeResult = ResetPasswordResendCodeResult;
exports.ResetPasswordStartErrorV2 = ResetPasswordStartErrorV2;
exports.ResetPasswordStartResult = ResetPasswordStartResult;
exports.ResetPasswordState = ResetPasswordState;
exports.ResetPasswordSubmitCodeError = ResetPasswordSubmitCodeError;
exports.ResetPasswordSubmitCodeResult = ResetPasswordSubmitCodeResult;
exports.ResetPasswordSubmitPasswordError = ResetPasswordSubmitPasswordError;
exports.ResetPasswordSubmitPasswordResult = ResetPasswordSubmitPasswordResult;
exports.SignInCodeRequiredState = SignInCodeRequiredState;
exports.SignInCompletedState = SignInCompletedState;
exports.SignInContinuationErrorV2 = SignInContinuationErrorV2;
exports.SignInContinuationState = SignInContinuationState;
exports.SignInContinuationStateV2 = SignInContinuationStateV2;
exports.SignInError = SignInError;
exports.SignInFailedState = SignInFailedState;
exports.SignInPasswordRequiredState = SignInPasswordRequiredState;
exports.SignInResendCodeError = SignInResendCodeError;
exports.SignInResendCodeResult = SignInResendCodeResult;
exports.SignInResult = SignInResult;
exports.SignInStartErrorV2 = SignInStartErrorV2;
exports.SignInState = SignInState;
exports.SignInSubmitCodeError = SignInSubmitCodeError;
exports.SignInSubmitCodeResult = SignInSubmitCodeResult;
exports.SignInSubmitPasswordError = SignInSubmitPasswordError;
exports.SignInSubmitPasswordResult = SignInSubmitPasswordResult;
exports.SignOutError = SignOutError;
exports.SignOutResult = SignOutResult;
exports.SignUpAttributesRequiredState = SignUpAttributesRequiredState;
exports.SignUpCodeRequiredState = SignUpCodeRequiredState;
exports.SignUpCompletedState = SignUpCompletedState;
exports.SignUpError = SignUpError;
exports.SignUpFailedState = SignUpFailedState;
exports.SignUpPasswordRequiredState = SignUpPasswordRequiredState;
exports.SignUpPasswordRequiredStateV2 = SignUpPasswordRequiredStateV2;
exports.SignUpResendCodeError = SignUpResendCodeError;
exports.SignUpResendCodeResult = SignUpResendCodeResult;
exports.SignUpResult = SignUpResult;
exports.SignUpStartErrorV2 = SignUpStartErrorV2;
exports.SignUpState = SignUpState;
exports.SignUpSubmitAttributesError = SignUpSubmitAttributesError;
exports.SignUpSubmitAttributesResult = SignUpSubmitAttributesResult;
exports.SignUpSubmitCodeError = SignUpSubmitCodeError;
exports.SignUpSubmitCodeResult = SignUpSubmitCodeResult;
exports.SignUpSubmitPasswordError = SignUpSubmitPasswordError;
exports.SignUpSubmitPasswordResult = SignUpSubmitPasswordResult;
exports.SubmitAttributesErrorV2 = SubmitAttributesErrorV2;
exports.SubmitNewPasswordErrorV2 = SubmitNewPasswordErrorV2;
exports.SubmitPasswordErrorV2 = SubmitPasswordErrorV2;
exports.UnexpectedError = UnexpectedError;
exports.UnsupportedEnvironmentError = UnsupportedEnvironmentError;
exports.UserAccountAttributeError = UserAccountAttributeError;
exports.UserAlreadySignedInError = UserAlreadySignedInError;
exports.VerifyChallengeErrorV2 = VerifyChallengeErrorV2;
//# sourceMappingURL=msal-custom-auth.cjs.map