UNPKG

@azure/msal-browser

Version:
1,179 lines • 60 kB
/*! @azure/msal-browser v5.30.0 2026-11-18 */
'use strict';
import { ServerTelemetryManager, AADServerParamKeys, TimeUtils, invokeAsync, AuthError, ScopeSet, Constants, createClientAuthError, ClientAuthErrorCodes, AuthToken, updateAccountTenantProfileData, UrlString, buildAccountToCache, AccountEntityUtils, AuthorityType, PopTokenGenerator, CacheHelpers, RequestParameterBuilder, PerformanceEvents, createClientConfigurationError, ClientConfigurationErrorCodes, normalizeDpopResourceRequestContext, createAuthError, AuthErrorCodes, JsonWebTokenAlgorithms, DpopProofGenerator } from '@azure/msal-common/browser';
import { createPlatformAuthExtraParametersNoCache, PlatformAuthBindingPreference, PlatformAuthTokenType, PlatformAuthEnclave } from '../broker/nativeBroker/PlatformAuthRequest.mjs';
import { base64Decode } from '../encode/Base64Decode.mjs';
import { createBrowserAuthError } from '../error/BrowserAuthError.mjs';
import { NativeAuthError, isFatalNativeAuthError, createNativeAuthError } from '../error/NativeAuthError.mjs';
import { version } from '../packageMetadata.mjs';
import { isTokenBindingKeyPersistedForRedirect } from '../request/RequestHelpers.mjs';
import { NativeInteractionClientAcquireToken, PlatformAuthInteractionClientInitializeRequest, PlatformAuthHandleNativeResponse, NativeGenerateAuthResult, PlatformAuthCacheAccount, PlatformAuthCacheNativeTokens, PlatformAuthDpopKeyCleanup } from '../telemetry/BrowserPerformanceEvents.mjs';
import { BrowserConstants, ApiId, CacheLookupPolicy, TemporaryCacheKeys, PlatformAuthConstants } from '../utils/BrowserConstants.mjs';
import { getCurrentUri } from '../utils/BrowserUtils.mjs';
import { BaseInteractionClient, initializeServerTelemetryManager, getRedirectUri, getDiscoveredAuthority } from './BaseInteractionClient.mjs';
import { SilentCacheClient } from './SilentCacheClient.mjs';
import { nativePromptNotSupported } from '../error/BrowserAuthErrorCodes.mjs';
import { userSwitch } from '../error/NativeAuthErrorCodes.mjs';

/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License.
 */
const DPOP_POP_KID_NOT_SUPPORTED = "dpop_pop_kid_not_supported";
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,
            [AADServerParamKeys.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 = TimeUtils.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;
        }
        if (this.apiId === ApiId.acquireTokenSilent_silentFlow) {
            let cachedResult;
            try {
                cachedResult = await this.acquireTokensFromCache(this.accountId, nativeRequest, cacheLookupPolicy);
            }
            catch (e) {
                if (cacheLookupPolicy === CacheLookupPolicy.AccessToken) {
                    this.logger.info("0eitbc", this.correlationId);
                    nativeATMeasurement.add({
                        isNativeBroker: false,
                    });
                    nativeATMeasurement.end({
                        success: false,
                    });
                    await this.resetGeneratedDpopRequestKeyBestEffort(nativeRequest);
                    throw e;
                }
                // continue with a native call for any and all errors
                this.logger.info("0957j1", this.correlationId);
            }
            if (cachedResult) {
                // Served from the native internal cache; token did not come directly from the broker
                nativeATMeasurement.add({
                    isNativeBroker: false,
                });
                nativeATMeasurement.end({
                    success: true,
                    fromCache: true,
                });
                await this.resetGeneratedDpopRequestKey(nativeRequest);
                return cachedResult;
            }
        }
        // dispatch the request to the broker
        try {
            await this.prepareDpopBrokerRequest(nativeRequest);
            this.addDpopBrokerAttemptTelemetry(nativeRequest);
            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);
            await this.resetGeneratedDpopRequestKeyBestEffort(nativeRequest);
            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,
            ...this.createSilentCacheTokenBindingParameters(request),
            resource: request.extraParameters?.resource,
        };
        // Preserve FMI partition semantics for silent cache filtering.
        if (request.attributeTokens) {
            silentRequest.attributeTokens = request.attributeTokens.split(" ");
        }
        return silentRequest;
    }
    /**
     * Maps platform-broker token-binding state to silent-cache request fields.
     * @param request
     */
    createSilentCacheTokenBindingParameters(request) {
        const authenticationScheme = this.isDpopBrokerRequest(request)
            ? Constants.AuthenticationScheme.DPOP
            : request.tokenType;
        if (authenticationScheme !== Constants.AuthenticationScheme.DPOP &&
            authenticationScheme !== Constants.AuthenticationScheme.POP) {
            return { authenticationScheme };
        }
        return {
            authenticationScheme,
            ...(authenticationScheme === Constants.AuthenticationScheme.DPOP &&
                request.keyId && { dpopJkt: request.keyId }),
            ...(authenticationScheme === Constants.AuthenticationScheme.POP &&
                request.signPopToken === false &&
                request.keyId && { popKid: request.keyId }),
            resourceRequestMethod: request.resourceRequestMethod,
            resourceRequestUri: request.resourceRequestUri,
        };
    }
    /**
     * Fetches unexpired tokens when allowed by cache policy.
     * @param nativeAccountId
     * @param request
     * @param cacheLookupPolicy
     * @returns Cached result, or undefined when cache policy bypasses lookup.
     */
    async acquireTokensFromCache(nativeAccountId, request, cacheLookupPolicy = CacheLookupPolicy.Default) {
        if (cacheLookupPolicy === CacheLookupPolicy.RefreshTokenAndNetwork ||
            cacheLookupPolicy === CacheLookupPolicy.Skip) {
            this.logger.verbose("03uwyk", this.correlationId);
            return undefined;
        }
        if (!nativeAccountId) {
            this.logger.warning("1ndf3e", this.correlationId);
            throw createClientAuthError(ClientAuthErrorCodes.noAccountFound, this.correlationId);
        }
        // fetch the account from browser cache
        const account = this.browserStorage.getBaseAccountInfo({
            nativeAccountId,
        }, this.correlationId);
        if (!account) {
            throw createClientAuthError(ClientAuthErrorCodes.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 = AuthToken.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.prepareDpopBrokerRequest(nativeRequest);
            this.addDpopBrokerAttemptTelemetry(nativeRequest);
            const response = await this.platformAuthProvider.sendMessage(nativeRequest);
            const dpopBrokerOutcome = this.validateDpopBrokerOutcome(response, nativeRequest);
            if (dpopBrokerOutcome === "L3") {
                await this.resetGeneratedDpopRequestKey(nativeRequest);
            }
        }
        catch (e) {
            /*
             * Raw persistent/transient broker errors are retrieved again in
             * phase two. Availability errors are thrown for controller-managed
             * web fallback, while translated cancellation, network, and
             * interaction-required errors are surfaced without being swallowed.
             */
            await this.resetGeneratedDpopRequestKeyBestEffort(nativeRequest);
            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;
                }
            }
            else if (this.isDpopBrokerRequest(nativeRequest)) {
                throw e;
            }
        }
        try {
            await this.ensureRedirectDpopKeyIsPersisted(nativeRequest);
        }
        catch (e) {
            await this.resetGeneratedDpopRequestKeyBestEffort(nativeRequest);
            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 });
        try {
            await this.navigationClient.navigateExternal(redirectUri, navigationOptions); // Need to treat this as external to ensure handleRedirectPromise is run again
        }
        catch (e) {
            this.browserStorage.removeItem(this.browserStorage.generateCacheKey(TemporaryCacheKeys.NATIVE_REQUEST));
            await this.resetGeneratedDpopRequestKeyBestEffort(nativeRequest);
            throw e;
        }
    }
    /**
     * 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 = TimeUtils.nowSeconds();
        try {
            await this.prepareDpopBrokerRequest(request, true);
            this.addDpopBrokerAttemptTelemetry(request);
            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) {
            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);
            }
            this.setBrokerErrorTelemetry(e);
            await this.resetGeneratedDpopRequestKeyBestEffort(request);
            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);
        const dpopBrokerOutcome = this.validateDpopBrokerOutcome(response, request);
        // generate identifiers
        const idTokenClaims = AuthToken.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);
        const isL3DpopResponse = dpopBrokerOutcome === "L3";
        // cache accounts and tokens in the appropriate storage
        const shouldRemoveGeneratedDpopKey = isL3DpopResponse ||
            (this.isDpopBrokerRequest(request) &&
                storeInCache?.accessToken === false);
        if (shouldRemoveGeneratedDpopKey) {
            await this.resetGeneratedDpopRequestKey(request);
        }
        await invokeAsync(this.cacheAccount.bind(this), PlatformAuthCacheAccount, this.logger, this.performanceClient, this.correlationId)(baseAccount, AuthToken.isKmsi(idTokenClaims), !isL3DpopResponse);
        await invokeAsync(this.cacheNativeTokens.bind(this), PlatformAuthCacheNativeTokens, this.logger, this.performanceClient, this.correlationId)(response, request, homeAccountIdentifier, idTokenClaims, result.tenantId, reqTimestamp, authority.getPreferredCache(), // environment
        storeInCache, dpopBrokerOutcome);
        return result;
    }
    /**
     * creates an homeAccountIdentifier for the account
     * @param response
     * @param idTokenObj
     * @returns
     */
    createHomeAccountIdentifier(response, idTokenClaims) {
        // Save account in browser storage
        const homeAccountIdentifier = AccountEntityUtils.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 === Constants.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(ClientAuthErrorCodes.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(AccountEntityUtils.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 isDpopRequest = this.isDpopBrokerRequest(request);
        let tokenType = Constants.AuthenticationScheme.BEARER;
        if (isDpopRequest) {
            tokenType = Constants.AuthenticationScheme.DPOP;
        }
        else if (request.tokenType === Constants.AuthenticationScheme.POP) {
            tokenType = Constants.AuthenticationScheme.POP;
        }
        const dpopProof = isDpopRequest
            ? await this.generateDpopProof(response, request)
            : undefined;
        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: TimeUtils.toDateFromSeconds(reqTimestamp + response.expires_in),
            tokenType: tokenType,
            dpopProof,
            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, clearExistingTokens = true) {
        // Store the account info and hence `nativeAccountId` in browser cache
        await this.browserStorage.setAccount(accountEntity, this.correlationId, kmsi, this.apiId);
        // Remove cached web access and refresh tokens, preserving ID tokens.
        if (clearExistingTokens) {
            this.browserStorage.removeAccountContext(AccountEntityUtils.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, dpopBrokerOutcome = "none") {
        const cachedIdToken = CacheHelpers.createIdTokenEntity(homeAccountIdentifier, environment, response.id_token || "", request.clientId, idTokenClaims.tid || "");
        // save idtoken credential in configured browser storage
        if (!!cachedIdToken && storeInCache?.idToken !== false) {
            await this.browserStorage.setIdTokenCredential(cachedIdToken, this.correlationId, AuthToken.isKmsi(idTokenClaims));
        }
        if (dpopBrokerOutcome === "L3") {
            return;
        }
        if (storeInCache?.accessToken === false) {
            return;
        }
        // cache accessToken in inmemory storage
        const expiresIn = request.tokenType === Constants.AuthenticationScheme.POP
            ? Constants.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 = CacheHelpers.createAccessTokenEntity(homeAccountIdentifier, environment, response.access_token, request.clientId, idTokenClaims.tid || tenantId, responseScopes.printScopes(), tokenExpirationSeconds, 0, base64Decode, request.correlationId, undefined, this.isDpopBrokerRequest(request)
            ? Constants.AuthenticationScheme.DPOP
            : request.tokenType, undefined, request.keyId, additionalCacheKeyComponents);
        if (request.extraParameters?.resource) {
            cachedAccessToken.resource = request.extraParameters.resource;
        }
        // save access token credential in memory storage
        const nativeCacheRecord = {
            accessToken: cachedAccessToken,
        };
        return this.nativeStorageManager.saveCacheRecord(nativeCacheRecord, this.correlationId, AuthToken.isKmsi(idTokenClaims), this.apiId, storeInCache);
    }
    getExpiresInValue(tokenType, expiresIn) {
        return tokenType === Constants.AuthenticationScheme.POP
            ? Constants.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;
        const { scopes, claims, dpopNonce } = request;
        const scopeSet = new ScopeSet([...(scopes || []), ...Constants.OIDC_DEFAULT_SCOPES], this.correlationId);
        const mergedClaims = RequestParameterBuilder.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,
                // Native broker resource is set for MCP scenarios.
                ...(request.resource && { resource: request.resource }),
            },
            extendedExpiryToken: false,
            keyId: request.popKid,
        };
        if (hasAttributeTokens) {
            validatedRequest.attributeTokens =
                CacheHelpers.serializeAttributeTokens(request.attributeTokens);
        }
        this.handleExtraBrokerParams(validatedRequest, request.embeddedClientId);
        validatedRequest.extraParameters =
            validatedRequest.extraParameters || {};
        validatedRequest.extraParameters.telemetry =
            PlatformAuthConstants.MATS_TELEMETRY;
        if (request.authenticationScheme === Constants.AuthenticationScheme.POP) {
            const shrParameters = {
                resourceRequestMethod: request.resourceRequestMethod,
                resourceRequestUri: request.resourceRequestUri,
                shrClaims: request.shrClaims,
                shrNonce: request.shrNonce,
                correlationId: this.correlationId,
            };
            const popTokenGenerator = new PopTokenGenerator(this.browserCrypto, this.tokenBindingKeyManager, this.performanceClient);
            if (!validatedRequest.keyId) {
                const generatedReqCnfData = await invokeAsync(popTokenGenerator.generateCnf.bind(popTokenGenerator), PerformanceEvents.PopTokenGenerateCnf, this.logger, this.performanceClient, this.correlationId)(shrParameters, this.logger);
                validatedRequest.reqCnf = generatedReqCnfData.reqCnfString;
                validatedRequest.keyId = generatedReqCnfData.kid;
                validatedRequest.signPopToken = true;
            }
            else {
                validatedRequest.reqCnf = this.browserCrypto.base64UrlEncode(JSON.stringify({ kid: validatedRequest.keyId }));
                validatedRequest.signPopToken = false;
            }
            validatedRequest.resourceRequestMethod =
                request.resourceRequestMethod;
            validatedRequest.resourceRequestUri = request.resourceRequestUri;
            validatedRequest.shrClaims = request.shrClaims;
            validatedRequest.shrNonce = request.shrNonce;
        }
        else if (request.authenticationScheme === Constants.AuthenticationScheme.DPOP) {
            Object.assign(validatedRequest, this.createDpopRequestParameters(request));
        }
        validatedRequest.extraParametersNoCache =
            createPlatformAuthExtraParametersNoCache(validatedRequest.tokenType, validatedRequest.resourceRequestMethod, validatedRequest.resourceRequestUri, dpopNonce);
        this.addRequestSKUs(validatedRequest);
        return validatedRequest;
    }
    /**
     * Creates and validates the broker-specific parameters for a DPoP request.
     * @param request - Developer-provided token request.
     * @returns Broker parameters for a DPoP token and resource proof.
     */
    createDpopRequestParameters(request) {
        if (request.popKid) {
            throw createBrowserAuthError(DPOP_POP_KID_NOT_SUPPORTED, this.correlationId);
        }
        if (!request.resourceRequestMethod?.trim() ||
            !request.resourceRequestUri?.trim()) {
            throw createClientConfigurationError(ClientConfigurationErrorCodes.dpopMissingResourceContext, this.correlationId);
        }
        const resourceContext = normalizeDpopResourceRequestContext({
            htm: request.resourceRequestMethod,
            htu: request.resourceRequestUri,
        }, this.correlationId);
        return {
            tokenType: PlatformAuthTokenType.DPOP_WITH_PROOF,
            preferBinding: PlatformAuthBindingPreference.ATTESTED,
            keyId: request.dpopJkt,
            resourceRequestMethod: resourceContext.htm,
            resourceRequestUri: resourceContext.htu,
        };
    }
    /**
     * Provisions the local key and confirmation data for a DPoP broker request.
     * @param request - Broker request to prepare.
     * @param reuseExistingKey - Whether a complete existing key binding may be reused.
     */
    async prepareDpopBrokerRequest(request, reuseExistingKey = false) {
        if (request.tokenType !== PlatformAuthTokenType.DPOP_WITH_PROOF) {
            return;
        }
        /*
         * Phase one clears both fields after an L3 response or non-fatal broker
         * error. In that case phase two must provision a replacement. If either
         * field remains, treat it as a retained binding and validate it fully.
         */
        if (reuseExistingKey && (request.keyId || request.reqCnf)) {
            if (!request.keyId || !request.reqCnf) {
                throw createAuthError(AuthErrorCodes.unexpectedError, this.correlationId, "DPoP request key binding is incomplete after redirect.");
            }
            const expectedReqCnf = this.createDpopBrokerReqCnf(request.keyId);
            if (request.reqCnf !== expectedReqCnf) {
                throw createAuthError(AuthErrorCodes.unexpectedError, this.correlationId, "DPoP request key binding is invalid after redirect.");
            }
            const hasKey = this.tokenBindingKeyManager.hasTokenBindingKey !== undefined
                ? await this.tokenBindingKeyManager.hasTokenBindingKey(request.keyId, this.correlationId)
                : await this.tokenBindingKeyManager
                    .getTokenBindingPublicKeyJwk(request.keyId, this.correlationId)
                    .then(() => true, () => false);
            if (!hasKey) {
                throw createAuthError(AuthErrorCodes.unexpectedError, this.correlationId, "DPoP request key is unavailable after redirect.");
            }
            return;
        }
        if (request.reqCnf) {
            throw createAuthError(AuthErrorCodes.unexpectedError, this.correlationId, "Unexpected preexisting DPoP request key.");
        }
        if (!request.keyId) {
            request.keyId =
                await this.tokenBindingKeyManager.provisionTokenBindingKey({
                    tokenBindingKeyType: Constants.AuthenticationScheme.DPOP.toLowerCase(),
                    tokenBindingKeyAlgorithm: JsonWebTokenAlgorithms.ES256,
                    correlationId: this.correlationId,
                });
        }
        request.reqCnf = this.createDpopBrokerReqCnf(request.keyId);
    }
    /**
     * Creates the confirmation claim for an MSAL-owned broker DPoP key.
     * @param keyId - Browser-managed DPoP key identifier.
     * @returns Encoded broker confirmation claim.
     */
    createDpopBrokerReqCnf(keyId) {
        return this.browserCrypto.base64UrlEncode(JSON.stringify({
            kid: keyId,
            xms_ksl: PlatformAuthInteractionClient.MSAL_DPOP_KEY_STORAGE_LOCATION,
        }));
    }
    /**
     * Ensures an owned DPoP key can survive redirect navigation before the
     * request metadata is persisted for phase two.
     */
    async ensureRedirectDpopKeyIsPersisted(request) {
        if (!this.isDpopBrokerRequest(request) || !request.keyId) {
            return;
        }
        if (!(await isTokenBindingKeyPersistedForRedirect(request, this.tokenBindingKeyManager))) {
            throw createAuthError(AuthErrorCodes.unexpectedError, this.correlationId, "DPoP request key could not be persisted for redirect.");
        }
    }
    /**
     * Validates and normalizes the DPoP binding outcome returned by the broker.
     * @param response - Broker response to validate.
     * @param request - Broker request associated with the response.
     * @returns The validated DPoP binding level, or `none` for non-DPoP requests.
     */
    validateDpopBrokerOutcome(response, request) {
        const isDpopRequest = this.isDpopBrokerRequest(request);
        const normalizedResponse = this.normalizeDpopBrokerResponse(response);
        const normalizedRequestTokenType = request.tokenType
            ?.trim()
            .toLowerCase();
        const bindingPreferenceSent = request.bindingPreferenceSent ??
            request.preferBinding !== undefined;
        const hasDpopResponse = this.isDpopBrokerTokenType(normalizedResponse.tokenType) ||
            normalizedResponse.proof !== undefined ||
            normalizedResponse.hasBindingAttested;
        if (!isDpopRequest) {
            if (hasDpopResponse) {
                this.throwInvalidDpopResponse("unexpected_response", "Unexpected DPoP broker response.");
            }
            return "none";
        }
        if (!this.isDpopBrokerTokenType(normalizedResponse.tokenType)) {
            this.throwInvalidDpopResponse("unknown_token_type", "Unknown DPoP broker response.");
        }
        this.validateNormalizedDpopBrokerResponse(normalizedResponse, bindingPreferenceSent);
        if (normalizedResponse.tokenType ===
            PlatformAuthTokenType.DPOP_WITH_PROOF.toLowerCase()) {
            return this.validateDpopBrokerL3Outcome(normalizedRequestTokenType, normalizedResponse);
        }
        return this.validateDpopBrokerL1Outcome(request, normalizedRequestTokenType, normalizedResponse, bindingPreferenceSent);
    }
    /**
     * Normalizes the canonical DPoP fields returned under response properties.
     */
    normalizeDpopBrokerResponse(response) {
        const responseProperties = response.properties;
        const rawTokenType = responseProperties?.token_type;
        const tokenType = typeof rawTokenType === "string"
            ? rawTokenType.trim().toLowerCase()
            : undefined;
        const rawBindingAttested = responseProperties?.binding_attested;
        let bindingAttested;
        if (typeof rawBindingAttested === "string") {
            const normalizedBindingAttested = rawBindingAttested
                .trim()
                .toLowerCase();
            if (normalizedBindingAttested === "true") {
                bindingAttested = true;
            }
            else if (normalizedBindingAttested === "false") {
                bindingAttested = false;
            }
        }
        return {
            tokenType,
            proof: responseProperties?.DPoP,
            bindingAttested,
            hasBindingAttested: rawBindingAttested !== undefined,
            hasMalformedBindingAttested: rawBindingAttested !== undefined &&
                bindingAttested === undefined,
        };
    }
    /**
     * Validates normalized fields shared by L1 and L3 broker DPoP responses.
     */
    validateNormalizedDpopBrokerResponse(normalizedResponse, bindingPreferenceSent) {
        if (normalizedResponse.hasMalformedBindingAttested) {
            this.throwInvalidDpopResponse("invalid_attestation", "Conflicting DPoP broker response.");
        }
        if (bindingPreferenceSent &&
            normalizedResponse.bindingAttested === undefined) {
            this.throwInvalidDpopResponse("missing_attestation", "Conflicting DPoP broker response.");
        }
    }
    /**
     * Validates a broker-returned L3 DPoP proof outcome.
     */
    validateDpopBrokerL3Outcome(normalizedRequestTokenType, normalizedResponse) {
        const dpopWithProofTokenType = PlatformAuthTokenType.DPOP_WITH_PROOF.toLowerCase();
        if (typeof normalizedResponse.proof !== "string" ||
            normalizedResponse.proof.trim().length === 0) {
            this.throwInvalidDpopResponse("missing_proof", "Malformed DPoP broker response.");
        }
        if (normalizedResponse.bindingAttested !== true) {
            this.throwInvalidDpopResponse("invalid_attestation", "Malformed DPoP broker response.");
        }
        if (normalizedRequestTokenType !== dpopWithProofTokenType ||
            normalizedResponse.tokenType !== dpopWithProofTokenType) {
            this.throwInvalidDpopResponse("conflicting_fields", "Malformed DPoP broker response.");
        }
        this.performanceClient.addFields({
            "ext.brokerDpopOutcome": "l3",
            "ext.brokerDpopBindingLevel": "L3",
        }, this.correlationId);
        return "L3";
    }
    /**
     * Validates an L1 DPoP outcome that MSAL will sign with its local key.
     */
    validateDpopBrokerL1Outcome(request, normalizedRequestTokenType, normalizedResponse, bindingPreferenceSent) {
        if (normalizedResponse.proof !== undefined) {
            this.throwInvalidDpopResponse("conflicting_fields", "Malformed DPoP broker L1 response.");
        }
        if (normalizedRequestTokenType !==
            PlatformAuthTokenType.DPOP_WITH_PROOF.toLowerCase()) {
            this.throwInvalidDpopResponse("conflicting_fields", "Malformed DPoP broker L1 response.");
        }
        if (normalizedResponse.bindingAttested !== false &&
            !(!bindingPreferenceSent &&
                normalizedResponse.bindingAttested === undefined)) {
            this.throwInvalidDpopResponse("invalid_attestation", "Malformed DPoP broker L1 response.");
        }
        if (!request.reqCnf || !request.keyId) {
            this.throwInvalidDpopResponse("missing_l1_binding", "Malformed DPoP broker L1 response.");
        }
        this.performanceClient.addFields({
            "ext.brokerDpopOutcome": "l1",
            "ext.brokerDpopBindingLevel": "L1",
        }, this.correlationId);
        return "L1";
    }
    /**
     * Emits bounded failure telemetry and rejects an invalid DPoP response.
     */
    throwInvalidDpopResponse(failureReason, message) {
        this.performanceClient.addFields({
            "ext.brokerDpopOutcome": "invalid_response",
            "ext.brokerDpopFailureReason": failureReason,
        }, this.correlationId);
        throw createAuthError(AuthErrorCodes.unexpectedError, this.correlationId, message);
    }
    /**
     * Returns the broker proof or signs an L1 resource proof with the local key.
     * @param response - Broker response containing the access token and optional proof.
     * @param request - Broker request containing the proof context and local key.
     * @returns The resource proof for the broker access token.
     */
    async generateDpopProof(response, request) {
        const brokerProof = response.properties?.DPoP;
        if (brokerProof !== undefined) {
            return brokerProof;
        }
        const dpopProofGenerator = new DpopProofGenerator(this.browserCrypto, this.tokenBindingKeyManager);
        return dpopProofGenerator.generateResourceProof({
            htu: request.resourceRequestUri,
            htm: request.resourceRequestMethod,
            accessToken: response.access_token,
            nonce: request.extraParametersNoCache?.pop_nonce,
        }, request.keyId, this.correlationId);
    }
    /**
     * Removes a generated DPoP request key and clears its request metadata.
     * @param request - Broker request whose generated key should be removed.
     */
    async resetGeneratedDpopRequestKey(request) {
        if (!this.isDpopBrokerRequest(request) || !request.keyId) {
            return;
        }
        const cleanupMeasurement = this.performanceClient.startMeasurement(PlatformAuthDpopKeyCleanup, this.correlationId);
        this.performanceClient.incrementFields({ "ext.brokerDpopKeyCleanupAttemptCount": 1 }, this.correlationId);
        try {
            if (request.keyId && !(await this.removeDpopKey(request.keyId))) {
                throw createAuthError(AuthErrorCodes.unexpectedError, this.correlationId, "Failed to remove generated DPoP request key.");
            }
            this.performanceClient.addFields({
                "ext.brokerDpopKeyCleanupOutcome": "succeeded",
            }, this.correlationId);
            cleanupMeasurement.end({ success: true });
            request.keyId = undefined;
            request.reqCnf = undefined;
        }
        catch (error) {
            this.performanceClient.addFields({
                "ext.brokerDpopKeyCleanupOutcome": "failed",
            }, this.correlationId);
            this.performanceClient.incrementFields({ "ext.brokerDpopKeyCleanupFailureCount": 1 }, this.correlationId);
            cleanupMeasurement.end({ success: false }, error);
            throw error;
        }
    }
    /**
     * Attempts to remove a generated DPoP request key without replacing an
     * existing operation error with a cleanup failure.
     * @param request - Broker request whose generated key should be removed.
     */
    async resetGeneratedDpopRequestKeyBestEffort(request) {
        try {
            await this.resetGeneratedDpopRequestKey(request);
        }
        catch {
            this.logger.error("1kxxak", this.correlationId);
            this.performanceClient.incrementFields({ removeTokenBindingKeyFailure: 1 }, this.correlationId);
            request.keyId = undefined;
            request.reqCnf = undefined;
        }
    }
    /**
     * Records that a DPoP request is about to be dispatched to the platform broker.
     * @param request - Broker request about to cross the provider boundary.
     */
    addDpopBrokerAttemptTelemetry(request) {
        if (!this.isDpopBrokerRequest(request)) {
            return;
        }
        this.performanceClient.addFields({
            "ext.brokerDpopAttempted": 1,
        }, this.correlationId);
    }
    /**
     * Determines whether a request uses the DPoP broker protocol.
     * @param request - Broker request to inspect.
     * @returns Whether the request uses a DPoP token type.
     */
    isDpopBrokerRequest(request) {
        return this.isDpopBrokerTokenType(request.tokenType);
    }
    /**
     * Determines whether a token type represents a DPoP broker request.
     * @param tokenType - Token type to inspect.
     * @returns Whether the token type is a supported DPoP broker token type.
     */
    isDpopBrokerTokenType(tokenType) {
        const normalizedTokenType = tokenType?.trim().toLowerCase();
        return (normalizedTokenType === PlatformAuthTokenType.DPOP_WITH_PROOF ||
            normalizedTokenType ===
                Constants.AuthenticationScheme.DPOP.toLowerCase());
    }
    /**
     * Removes a DPoP key while reporting cleanup failures.
     * @param keyId - Identifier of the DPoP key to remove.
     * @returns Whether the key was removed successfully.
     */
    async removeDpopKey(keyId) {
        try {
            await this.tokenBindingKeyManager.removeTokenBindingKey(keyId, this.correlationId);
            return true;
        }
        catch {
            this.logger.error("1w60e4", this.correlationId);
            return false;
        }
    }
    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 Constants.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 Constants.PromptValue.NONE:
            case Constants.PromptValue.CONSENT:
            case Constants.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 - Platform broker request.
     * @param embeddedClientId - Embedded application client identifier.
     */
    handleExtraBrokerParams(request, embeddedClientId) {
        const hasOwnParameter = (parameter) => Object.prototype.hasOwnProperty.call(request.extraParameters, parameter);
        const hasExtraBrokerParams = hasOwnParameter(AADServerParamKeys.BROKER_CLIENT_ID) &&
            hasOwnParameter(AADServerParamKeys.BROKER_REDIRECT_URI) &&
            hasOwnParameter(AADServerParamKeys.CLIENT_ID);
        if (!embeddedClientId && !hasExtraBrokerParams) {
            return;
        }
        const childRedirectUri = request.redirectUri;
        const childClientId = embeddedClientId ||
            request.extraParameters?.[AADServerParamKeys.CLIENT_ID] ||
            "";
        if (embeddedClientId) {
            request.redirectUri = this.config.auth.redirectUri;
        }
        else if (request.extraParameters) {
            request.redirectUri =
                request.extraParameters[AADServerParamKeys.BROKER_REDIRECT_URI];
        }
        const { 
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        [AADServerParamKeys.BROKER_CLIENT_ID]: _brkClientId, 
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        [AADServerParamKeys.BROKER_REDIRECT_URI]: _brkRedirectUri, 
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        [AADServerParamKeys.CLIENT_ID]: _clientId, ...remainingExtraParameters } = request.extraParameters || {};
        request.extraParameters = {
            ...remainingExtraParameters,
            child_client_id: childClientId,
            child_redirect_uri: childRedirectUri,
        };
        this.performanceClient?.addFields({
            embeddedClientId: childClientId,
            embeddedRedirectUri: childRedirectUri,
        }, this.correlationId);
    }
}
/**
 * Storage location reported for MSAL-owned browser DPoP keys in reqCnf.
 * This does not constrain the binding selected by the platform broker.
 */
PlatformAuthInteractionClient.MSAL_DPOP_KEY_STORAGE_LOCATION = PlatformAuthEnclave.SOFTWARE;

export { PlatformAuthInteractionClient };
//# sourceMappingURL=PlatformAuthInteractionClient.mjs.map