Estructura inicial del proyecto

This commit is contained in:
2026-06-02 16:57:08 +00:00
commit 8b306b9afc
9864 changed files with 1435687 additions and 0 deletions

View File

@ -0,0 +1,283 @@
/*! @azure/msal-common v16.6.2 2026-05-19 */
'use strict';
import { addClientId, addRedirectUri, addScopes, addResource, addAuthorizationCode, addLibraryInfo, addApplicationTelemetry, addThrottling, addServerTelemetry, addCodeVerifier, addClientSecret, addClientAssertion, addClientAssertionType, addGrantType, addClientInfo, addPopToken, addSshJwk, addCcsUpn, addCcsOid, addBrokerParameters, addExtraParameters, instrumentBrokerParams, addClaims, addPostLogoutRedirectUri, addCorrelationId, addIdTokenHint, addState, addLogoutHint, addInstanceAware } from '../request/RequestParameterBuilder.mjs';
import { mapToQueryString } from '../utils/UrlUtils.mjs';
import { CLIENT_INFO_SEPARATOR, AuthenticationScheme, HeaderNames, GrantType } from '../utils/Constants.mjs';
import { RETURN_SPA_CODE, CLIENT_ID } from '../constants/AADServerParamKeys.mjs';
import { buildClientConfiguration, isOidcProtocolMode } from '../config/ClientConfiguration.mjs';
import { ResponseHandler } from '../response/ResponseHandler.mjs';
import { createClientAuthError } from '../error/ClientAuthError.mjs';
import { UrlString } from '../url/UrlString.mjs';
import { PopTokenGenerator } from '../crypto/PopTokenGenerator.mjs';
import { nowSeconds } from '../utils/TimeUtils.mjs';
import { buildClientInfo, buildClientInfoFromHomeAccountId } from '../account/ClientInfo.mjs';
import { CcsCredentialType } from '../account/CcsCredential.mjs';
import { createClientConfigurationError } from '../error/ClientConfigurationError.mjs';
import { UpdateTokenEndpointAuthority, AuthClientExecuteTokenRequest, HandleServerTokenResponse, AuthClientCreateTokenRequestBody, AuthorizationCodeClientExecutePostToTokenEndpoint, PopTokenGenerateCnf } from '../telemetry/performance/PerformanceEvents.mjs';
import { invokeAsync } from '../utils/FunctionWrappers.mjs';
import { getClientAssertion } from '../utils/ClientAssertionUtils.mjs';
import { getRequestThumbprint } from '../network/RequestThumbprint.mjs';
import { createTokenQueryParameters, createTokenRequestHeaders, executePostToTokenEndpoint } from '../protocol/Token.mjs';
import { createDiscoveredInstance } from '../authority/AuthorityFactory.mjs';
import { Logger } from '../logger/Logger.mjs';
import { name, version } from '../packageMetadata.mjs';
import { requestCannotBeMade } from '../error/ClientAuthErrorCodes.mjs';
import { logoutRequestEmpty, redirectUriEmpty, missingSshJwk } from '../error/ClientConfigurationErrorCodes.mjs';
/*
* 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, version);
// 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);
}
// 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);
// 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", request.correlationId);
}
}
const headers = createTokenRequestHeaders(this.logger, this.config.systemOptions.preventCorsPreflight, ccsCredential || request.ccsCredential);
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);
}
}
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, true, this.oidcDefaultScopes);
addResource(parameters, request.resource);
// 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.AUTHORIZATION_CODE_GRANT);
addClientInfo(parameters);
if (request.authenticationScheme === AuthenticationScheme.POP) {
const popTokenGenerator = new PopTokenGenerator(this.cryptoUtils, 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);
}
}
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", 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", 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.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;
}
}
export { AuthorizationCodeClient };
//# sourceMappingURL=AuthorizationCodeClient.mjs.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,249 @@
/*! @azure/msal-common v16.6.2 2026-05-19 */
'use strict';
import { buildClientConfiguration, isOidcProtocolMode } from '../config/ClientConfiguration.mjs';
import { addClientId, addRedirectUri, addScopes, addGrantType, addClientInfo, addLibraryInfo, addApplicationTelemetry, addThrottling, addServerTelemetry, addRefreshToken, addClientSecret, addClientAssertion, addClientAssertionType, addPopToken, addSshJwk, addCcsUpn, addCcsOid, addBrokerParameters, addExtraParameters, instrumentBrokerParams, addClaims } from '../request/RequestParameterBuilder.mjs';
import { mapToQueryString } from '../utils/UrlUtils.mjs';
import { AuthenticationScheme, HeaderNames, INVALID_GRANT_ERROR, CLIENT_MISMATCH_ERROR, GrantType } from '../utils/Constants.mjs';
import { CLIENT_ID } from '../constants/AADServerParamKeys.mjs';
import { ResponseHandler } from '../response/ResponseHandler.mjs';
import { PopTokenGenerator } from '../crypto/PopTokenGenerator.mjs';
import { createClientConfigurationError } from '../error/ClientConfigurationError.mjs';
import { createClientAuthError } from '../error/ClientAuthError.mjs';
import { ServerError } from '../error/ServerError.mjs';
import { nowSeconds, isTokenExpired } from '../utils/TimeUtils.mjs';
import { UrlString } from '../url/UrlString.mjs';
import { CcsCredentialType } from '../account/CcsCredential.mjs';
import { buildClientInfoFromHomeAccountId } from '../account/ClientInfo.mjs';
import { createInteractionRequiredAuthError, InteractionRequiredAuthError } from '../error/InteractionRequiredAuthError.mjs';
import { RefreshTokenClientAcquireTokenWithCachedRefreshToken, RefreshTokenClientAcquireToken, RefreshTokenClientExecuteTokenRequest, HandleServerTokenResponse, CacheManagerGetRefreshToken, RefreshTokenClientCreateTokenRequestBody, RefreshTokenClientExecutePostToTokenEndpoint, PopTokenGenerateCnf } from '../telemetry/performance/PerformanceEvents.mjs';
import { invokeAsync, invoke } from '../utils/FunctionWrappers.mjs';
import { getClientAssertion } from '../utils/ClientAssertionUtils.mjs';
import { getRequestThumbprint } from '../network/RequestThumbprint.mjs';
import { createTokenQueryParameters, createTokenRequestHeaders, executePostToTokenEndpoint } from '../protocol/Token.mjs';
import { Logger } from '../logger/Logger.mjs';
import { name, version } from '../packageMetadata.mjs';
import { badToken, noTokensFound, refreshTokenExpired } from '../error/InteractionRequiredAuthErrorCodes.mjs';
import { tokenRequestEmpty, missingSshJwk } from '../error/ClientConfigurationErrorCodes.mjs';
import { noAccountInSilentRequest } from '../error/ClientAuthErrorCodes.mjs';
/*
* 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, version);
// 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);
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);
}
// 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);
}
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);
}
}
// 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,
},
};
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);
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, true, this.config.authOptions.authority.options.OIDCOptions?.defaultScopes);
addGrantType(parameters, GrantType.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 (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.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);
}
}
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", 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.claims, this.config.authOptions.clientCapabilities, request.skipBrokerClaims);
return mapToQueryString(parameters);
}
}
export { RefreshTokenClient };
//# sourceMappingURL=RefreshTokenClient.mjs.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,132 @@
/*! @azure/msal-common v16.6.2 2026-05-19 */
'use strict';
import { buildClientConfiguration } from '../config/ClientConfiguration.mjs';
import { wasClockTurnedBack, isTokenExpired } from '../utils/TimeUtils.mjs';
import { createClientAuthError } from '../error/ClientAuthError.mjs';
import { ResponseHandler } from '../response/ResponseHandler.mjs';
import { CacheOutcome } from '../utils/Constants.mjs';
import { StringUtils } from '../utils/StringUtils.mjs';
import { extractTokenClaims, checkMaxAge } from '../account/AuthToken.mjs';
import { SilentFlowClientGenerateResultFromCacheRecord } from '../telemetry/performance/PerformanceEvents.mjs';
import { invokeAsync } from '../utils/FunctionWrappers.mjs';
import { getTenantFromAuthorityString } from '../authority/Authority.mjs';
import { Logger } from '../logger/Logger.mjs';
import { name, version } from '../packageMetadata.mjs';
import { tokenRefreshRequired, noAccountInSilentRequest, authTimeNotFound } from '../error/ClientAuthErrorCodes.mjs';
/*
* 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, version);
// 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);
}
// 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);
}
const requestTenantId = request.account.tenantId ||
getTenantFromAuthorityString(request.authority);
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);
}
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);
}
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);
}
}
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 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", 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);
}
// token max_age check
if (request.maxAge || request.maxAge === 0) {
const authTime = idTokenClaims?.auth_time;
if (!authTime) {
throw createClientAuthError(authTimeNotFound);
}
checkMaxAge(authTime, request.maxAge);
}
return ResponseHandler.generateAuthenticationResult(this.cryptoUtils, this.authority, cacheRecord, true, request, this.performanceClient, idTokenClaims);
}
}
export { SilentFlowClient };
//# sourceMappingURL=SilentFlowClient.mjs.map

View File

@ -0,0 +1 @@
{"version":3,"file":"SilentFlowClient.mjs","sources":["../../src/client/SilentFlowClient.ts"],"sourcesContent":[null],"names":["ClientAuthErrorCodes.tokenRefreshRequired","ClientAuthErrorCodes.noAccountInSilentRequest","TimeUtils.wasClockTurnedBack","TimeUtils.isTokenExpired","PerformanceEvents.SilentFlowClientGenerateResultFromCacheRecord","ClientAuthErrorCodes.authTimeNotFound"],"mappings":";;;;;;;;;;;;;;;;AAAA;;;AAGG;AAkCH;MACa,gBAAgB,CAAA;IAyBzB,WACI,CAAA,aAAkC,EAClC,iBAAqC,EAAA;;AAGrC,QAAA,IAAI,CAAC,MAAM,GAAG,wBAAwB,CAAC,aAAa,CAAC,CAAC;;AAGtD,QAAA,IAAI,CAAC,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,aAAa,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;;QAGnE,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,MAAM,CAAC,eAAe,CAAC;;QAG/C,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,MAAM,CA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