/*! @azure/msal-browser v5.15.0 2026-06-23 */
'use strict';
import { ServerTelemetryManager, AADServerParamKeys, TimeUtils, ScopeSet, createClientAuthError, ClientAuthErrorCodes, AuthToken, updateAccountTenantProfileData, UrlString, buildAccountToCache, AccountEntityUtils, AuthorityType, Constants, PopTokenGenerator, CacheHelpers, RequestParameterBuilder, invokeAsync, PerformanceEvents } from '@azure/msal-common/browser';
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 { NativeInteractionClientAcquireToken } from '../telemetry/BrowserPerformanceEvents.mjs';
import { BrowserConstants, CacheLookupPolicy, TemporaryCacheKeys, ApiId, 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 { invalidPopTokenRequest, nativePromptNotSupported } from '../error/BrowserAuthErrorCodes.mjs';
import { userSwitch } from '../error/NativeAuthErrorCodes.mjs';

/*
 * 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) {
        super(config, browserStorage, browserCrypto, logger, eventHandler, navigationClient, performanceClient, correlationId, provider);
        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);
        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);
        try {
            // initialize native request
            const nativeRequest = await this.initializePlatformRequest(request);
            // check if the tokens can be retrieved from internal cache
            try {
                const result = await this.acquireTokensFromCache(this.accountId, nativeRequest);
                nativeATMeasurement.end({
                    success: true,
                    isNativeBroker: false,
                    fromCache: true,
                });
                return result;
            }
            catch (e) {
                if (cacheLookupPolicy === CacheLookupPolicy.AccessToken) {
                    this.logger.info("0eitbc", this.correlationId);
                    nativeATMeasurement.end({
                        success: false,
                        brokerErrorCode: "cache_request_failed",
                    });
                    throw e;
                }
                // continue with a native call for any and all errors
                this.logger.info("0957j1", this.correlationId);
            }
            const validatedResponse = await this.platformAuthProvider.sendMessage(nativeRequest);
            return await this.handleNativeResponse(validatedResponse, nativeRequest, reqTimestamp)
                .then((result) => {
                nativeATMeasurement.end({
                    success: true,
                    isNativeBroker: true,
                    requestId: result.requestId,
                });
                serverTelemetryManager.clearNativeBrokerErrorCode();
                return result;
            })
                .catch((error) => {
                nativeATMeasurement.end({
                    success: false,
                    errorCode: error.errorCode,
                    subErrorCode: error.subError,
                });
                throw error;
            });
        }
        catch (e) {
            if (e instanceof NativeAuthError) {
                serverTelemetryManager.setNativeBrokerErrorCode(e.errorCode);
            }
            nativeATMeasurement.end({
                success: false,
            });
            throw e;
        }
    }
    /**
     * Creates silent flow request
     * @param request
     * @param cachedAccount
     * @returns CommonSilentFlowRequest
     */
    createSilentCacheRequest(request, cachedAccount) {
        return {
            authority: request.authority,
            correlationId: this.correlationId,
            scopes: ScopeSet.fromString(request.scope, this.correlationId).asArray(),
            account: cachedAccount,
            forceRefresh: false,
        };
    }
    /**
     * 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(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 this.initializePlatformRequest(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)) {
                    throw e;
                }
            }
        }
        this.browserStorage.setTemporaryCache(TemporaryCacheKeys.NATIVE_REQUEST, JSON.stringify(nativeRequest), 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;
        }
        const { prompt, ...request } = cachedRequest;
        if (prompt) {
            this.logger.verbose("0ac34v", this.correlationId);
        }
        this.browserStorage.removeItem(this.browserStorage.generateCacheKey(TemporaryCacheKeys.NATIVE_REQUEST));
        const reqTimestamp = TimeUtils.nowSeconds();
        try {
            this.logger.verbose("003x5a", this.correlationId);
            const response = await this.platformAuthProvider.sendMessage(request);
            const authResult = await this.handleNativeResponse(response, request, reqTimestamp);
            const serverTelemetryManager = initializeServerTelemetryManager(this.apiId, this.config.auth.clientId, this.correlationId, this.browserStorage, this.logger, undefined, this.config.system.serverTelemetryEnabled);
            serverTelemetryManager.clearNativeBrokerErrorCode();
            this.performanceClient?.addFields({ isNativeBroker: true }, this.correlationId);
            return authResult;
        }
        catch (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) {
        this.logger.trace("1bojln", this.correlationId);
        // 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 this.generateAuthenticationResult(response, request, idTokenClaims, baseAccount, authority.canonicalAuthority, reqTimestamp);
        // cache accounts and tokens in the appropriate storage
        await this.cacheAccount(baseAccount, AuthToken.isKmsi(idTokenClaims));
        await this.cacheNativeTokens(response, request, homeAccountIdentifier, idTokenClaims, result.tenantId, reqTimestamp, authority.getPreferredCache() // environment
        );
        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.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 tokenType = request.tokenType === Constants.AuthenticationScheme.POP
            ? Constants.AuthenticationScheme.POP
            : Constants.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: TimeUtils.toDateFromSeconds(reqTimestamp + response.expires_in),
            tokenType: tokenType,
            correlationId: this.correlationId,
            state: response.state,
            fromPlatformBroker: true,
            ...(request.resource && { resource: request.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(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) {
        const cachedIdToken = CacheHelpers.createIdTokenEntity(homeAccountIdentifier, environment, response.id_token || "", request.clientId, idTokenClaims.tid || "");
        // 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 cachedAccessToken = CacheHelpers.createAccessTokenEntity(homeAccountIdentifier, environment, response.access_token, request.clientId, idTokenClaims.tid || tenantId, responseScopes.printScopes(), tokenExpirationSeconds, 0, base64Decode, request.correlationId, undefined, request.tokenType, undefined, request.keyId);
        // save idtoken credential in configured browser storage
        if (!!cachedIdToken && request.storeInCache?.idToken !== false) {
            await this.browserStorage.setIdTokenCredential(cachedIdToken, this.correlationId, AuthToken.isKmsi(idTokenClaims));
        }
        // save access token credential in memory storage
        const nativeCacheRecord = {
            accessToken: cachedAccessToken,
        };
        return this.nativeStorageManager.saveCacheRecord(nativeCacheRecord, this.correlationId, AuthToken.isKmsi(idTokenClaims), this.apiId, request.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;
        // 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.
        const { scopes, claims, ...remainingProperties } = request;
        const scopeSet = new ScopeSet(scopes || [], this.correlationId);
        scopeSet.appendScopes(Constants.OIDC_DEFAULT_SCOPES);
        const mergedClaims = RequestParameterBuilder.buildMergedClaims(claims, configClaims?.length ? configClaims : undefined);
        const validatedRequest = {
            ...remainingProperties,
            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,
            tokenType: request.authenticationScheme,
            windowTitleSubstring: document.title,
            extraParameters: {
                ...request.extraParameters,
            },
            extendedExpiryToken: false,
            keyId: request.popKid,
        };
        // 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);
        validatedRequest.extraParameters =
            validatedRequest.extraParameters || {};
        validatedRequest.extraParameters.telemetry =
            PlatformAuthConstants.MATS_TELEMETRY;
        if (request.authenticationScheme === Constants.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.performanceClient);
            // generate reqCnf if not provided in the request
            let reqCnfData;
            if (!validatedRequest.keyId) {
                const generatedReqCnfData = await invokeAsync(popTokenGenerator.generateCnf.bind(popTokenGenerator), PerformanceEvents.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 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 {PlatformAuthRequest}
     * @private
     */
    handleExtraBrokerParams(request) {
        const hasExtraBrokerParams = request.extraParameters &&
            request.extraParameters.hasOwnProperty(AADServerParamKeys.BROKER_CLIENT_ID) &&
            request.extraParameters.hasOwnProperty(AADServerParamKeys.BROKER_REDIRECT_URI) &&
            request.extraParameters.hasOwnProperty(AADServerParamKeys.CLIENT_ID);
        if (!request.embeddedClientId && !hasExtraBrokerParams) {
            return;
        }
        let child_client_id = "";
        const child_redirect_uri = request.redirectUri;
        if (request.embeddedClientId) {
            request.redirectUri = this.config.auth.redirectUri;
            child_client_id = request.embeddedClientId;
        }
        else if (request.extraParameters) {
            request.redirectUri =
                request.extraParameters[AADServerParamKeys.BROKER_REDIRECT_URI];
            child_client_id =
                request.extraParameters[AADServerParamKeys.CLIENT_ID];
        }
        request.extraParameters = {
            child_client_id,
            child_redirect_uri,
        };
        this.performanceClient?.addFields({
            embeddedClientId: child_client_id,
            embeddedRedirectUri: child_redirect_uri,
        }, this.correlationId);
    }
}

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