Socket
Socket
Sign inDemoInstall

@azure/msal-common

Package Overview
Dependencies
Maintainers
3
Versions
121
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@azure/msal-common - npm Package Compare versions

Comparing version 13.0.0 to 14.0.0-alpha.1

4

dist/account/AccountInfo.d.ts

@@ -15,3 +15,3 @@ import { TokenClaims } from "./TokenClaims";

*/
export declare type AccountInfo = {
export type AccountInfo = {
homeAccountId: string;

@@ -29,3 +29,3 @@ environment: string;

};
export declare type ActiveAccountFilters = {
export type ActiveAccountFilters = {
homeAccountId: string;

@@ -32,0 +32,0 @@ localAccountId: string;

@@ -1,2 +0,2 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';

@@ -13,4 +13,4 @@ import { ClientAuthError } from '../error/ClientAuthError.js';

*/
var AuthToken = /** @class */ (function () {
function AuthToken(rawToken, crypto) {
class AuthToken {
constructor(rawToken, crypto) {
if (StringUtils.isEmpty(rawToken)) {

@@ -27,9 +27,9 @@ throw ClientAuthError.createTokenNullOrEmptyError(rawToken);

*/
AuthToken.extractTokenClaims = function (encodedToken, crypto) {
var decodedToken = StringUtils.decodeAuthToken(encodedToken);
static extractTokenClaims(encodedToken, crypto) {
const decodedToken = StringUtils.decodeAuthToken(encodedToken);
// token will be decoded to get the username
try {
var base64TokenPayload = decodedToken.JWSPayload;
const base64TokenPayload = decodedToken.JWSPayload;
// base64Decode() should throw an error if there is an issue
var base64Decoded = crypto.base64Decode(base64TokenPayload);
const base64Decoded = crypto.base64Decode(base64TokenPayload);
return JSON.parse(base64Decoded);

@@ -40,7 +40,7 @@ }

}
};
}
/**
* Determine if the token's max_age has transpired
*/
AuthToken.checkMaxAge = function (authTime, maxAge) {
static checkMaxAge(authTime, maxAge) {
/*

@@ -51,11 +51,10 @@ * per https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest

*/
var fiveMinuteSkew = 300000; // five minutes in milliseconds
if ((maxAge === 0) || ((Date.now() - fiveMinuteSkew) > (authTime + maxAge))) {
const fiveMinuteSkew = 300000; // five minutes in milliseconds
if (maxAge === 0 || Date.now() - fiveMinuteSkew > authTime + maxAge) {
throw ClientAuthError.createMaxAgeTranspiredError();
}
};
return AuthToken;
}());
}
}
export { AuthToken };
//# sourceMappingURL=AuthToken.js.map

@@ -1,2 +0,2 @@

export declare type CcsCredential = {
export type CcsCredential = {
credential: string;

@@ -3,0 +3,0 @@ type: CcsCredentialType;

@@ -1,2 +0,2 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';

@@ -3,0 +3,0 @@ /*

/**
* Client Assertion credential for Confidential Clients
*/
export declare type ClientAssertion = {
export type ClientAssertion = {
assertion: string;

@@ -11,3 +11,3 @@ assertionType: string;

*/
export declare type ClientCredentials = {
export type ClientCredentials = {
clientSecret?: string;

@@ -14,0 +14,0 @@ clientAssertion?: ClientAssertion;

@@ -5,3 +5,3 @@ import { ICrypto } from "../crypto/ICrypto";

*/
export declare type ClientInfo = {
export type ClientInfo = {
uid: string;

@@ -8,0 +8,0 @@ utid: string;

@@ -1,2 +0,2 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';

@@ -21,3 +21,3 @@ import { ClientAuthError } from '../error/ClientAuthError.js';

try {
var decodedClientInfo = crypto.base64Decode(rawClientInfo);
const decodedClientInfo = crypto.base64Decode(rawClientInfo);
return JSON.parse(decodedClientInfo);

@@ -37,6 +37,8 @@ }

}
var clientInfoParts = homeAccountId.split(Separators.CLIENT_INFO_SEPARATOR, 2);
const clientInfoParts = homeAccountId.split(Separators.CLIENT_INFO_SEPARATOR, 2);
return {
uid: clientInfoParts[0],
utid: clientInfoParts.length < 2 ? Constants.EMPTY_STRING : clientInfoParts[1]
utid: clientInfoParts.length < 2
? Constants.EMPTY_STRING
: clientInfoParts[1],
};

@@ -43,0 +45,0 @@ }

/**
* Type which describes Id Token claims known by MSAL.
*/
export declare type TokenClaims = {
export type TokenClaims = {
/**

@@ -6,0 +6,0 @@ * Audience

@@ -1,4 +0,3 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';
import { __awaiter, __generator, __assign } from '../_virtual/_tslib.js';
import { AuthorityType } from './AuthorityType.js';

@@ -28,4 +27,4 @@ import { isOpenIdConfigResponse } from './OpenIdConfigResponse.js';

*/
var Authority = /** @class */ (function () {
function Authority(authority, networkInterface, cacheManager, authorityOptions, logger, performanceClient, correlationId) {
class Authority {
constructor(authority, networkInterface, cacheManager, authorityOptions, logger, performanceClient, correlationId) {
this.canonicalAuthority = authority;

@@ -36,3 +35,7 @@ this._canonicalAuthority.validateAsUri();

this.authorityOptions = authorityOptions;
this.regionDiscoveryMetadata = { region_used: undefined, region_source: undefined, region_outcome: undefined };
this.regionDiscoveryMetadata = {
region_used: undefined,
region_source: undefined,
region_outcome: undefined,
};
this.logger = logger;

@@ -43,198 +46,147 @@ this.performanceClient = performanceClient;

}
Object.defineProperty(Authority.prototype, "authorityType", {
// See above for AuthorityType
get: function () {
// CIAM auth url pattern is being standardized as: <tenant>.ciamlogin.com
if (this.canonicalAuthorityUrlComponents.HostNameAndPort.endsWith(Constants.CIAM_AUTH_URL)) {
return AuthorityType.Ciam;
// See above for AuthorityType
get authorityType() {
const pathSegments = this.canonicalAuthorityUrlComponents.PathSegments;
// CIAM auth url pattern is being standardized as: <tenant>.ciamlogin.com
if (this.canonicalAuthorityUrlComponents.HostNameAndPort.endsWith(Constants.CIAM_AUTH_URL)) {
return AuthorityType.Ciam;
}
if (pathSegments.length) {
switch (pathSegments[0].toLowerCase()) {
case Constants.ADFS:
return AuthorityType.Adfs;
case Constants.DSTS:
return AuthorityType.Dsts;
}
var pathSegments = this.canonicalAuthorityUrlComponents.PathSegments;
if (pathSegments.length) {
switch (pathSegments[0].toLowerCase()) {
case Constants.ADFS:
return AuthorityType.Adfs;
case Constants.DSTS:
return AuthorityType.Dsts;
}
}
return AuthorityType.Default;
}
/**
* ProtocolMode enum representing the way endpoints are constructed.
*/
get protocolMode() {
return this.authorityOptions.protocolMode;
}
/**
* Returns authorityOptions which can be used to reinstantiate a new authority instance
*/
get options() {
return this.authorityOptions;
}
/**
* A URL that is the authority set by the developer
*/
get canonicalAuthority() {
return this._canonicalAuthority.urlString;
}
/**
* Sets canonical authority.
*/
set canonicalAuthority(url) {
this._canonicalAuthority = new UrlString(url);
this._canonicalAuthority.validateAsUri();
this._canonicalAuthorityUrlComponents = null;
}
/**
* Get authority components.
*/
get canonicalAuthorityUrlComponents() {
if (!this._canonicalAuthorityUrlComponents) {
this._canonicalAuthorityUrlComponents =
this._canonicalAuthority.getUrlComponents();
}
return this._canonicalAuthorityUrlComponents;
}
/**
* Get hostname and port i.e. login.microsoftonline.com
*/
get hostnameAndPort() {
return this.canonicalAuthorityUrlComponents.HostNameAndPort.toLowerCase();
}
/**
* Get tenant for authority.
*/
get tenant() {
return this.canonicalAuthorityUrlComponents.PathSegments[0];
}
/**
* OAuth /authorize endpoint for requests
*/
get authorizationEndpoint() {
if (this.discoveryComplete()) {
const endpoint = this.replacePath(this.metadata.authorization_endpoint);
return this.replaceTenant(endpoint);
}
else {
throw ClientAuthError.createEndpointDiscoveryIncompleteError("Discovery incomplete.");
}
}
/**
* OAuth /token endpoint for requests
*/
get tokenEndpoint() {
if (this.discoveryComplete()) {
const endpoint = this.replacePath(this.metadata.token_endpoint);
return this.replaceTenant(endpoint);
}
else {
throw ClientAuthError.createEndpointDiscoveryIncompleteError("Discovery incomplete.");
}
}
get deviceCodeEndpoint() {
if (this.discoveryComplete()) {
const endpoint = this.replacePath(this.metadata.token_endpoint.replace("/token", "/devicecode"));
return this.replaceTenant(endpoint);
}
else {
throw ClientAuthError.createEndpointDiscoveryIncompleteError("Discovery incomplete.");
}
}
/**
* OAuth logout endpoint for requests
*/
get endSessionEndpoint() {
if (this.discoveryComplete()) {
// ROPC policies may not have end_session_endpoint set
if (!this.metadata.end_session_endpoint) {
throw ClientAuthError.createLogoutNotSupportedError();
}
return AuthorityType.Default;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Authority.prototype, "protocolMode", {
/**
* ProtocolMode enum representing the way endpoints are constructed.
*/
get: function () {
return this.authorityOptions.protocolMode;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Authority.prototype, "options", {
/**
* Returns authorityOptions which can be used to reinstantiate a new authority instance
*/
get: function () {
return this.authorityOptions;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Authority.prototype, "canonicalAuthority", {
/**
* A URL that is the authority set by the developer
*/
get: function () {
return this._canonicalAuthority.urlString;
},
/**
* Sets canonical authority.
*/
set: function (url) {
this._canonicalAuthority = new UrlString(url);
this._canonicalAuthority.validateAsUri();
this._canonicalAuthorityUrlComponents = null;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Authority.prototype, "canonicalAuthorityUrlComponents", {
/**
* Get authority components.
*/
get: function () {
if (!this._canonicalAuthorityUrlComponents) {
this._canonicalAuthorityUrlComponents = this._canonicalAuthority.getUrlComponents();
}
return this._canonicalAuthorityUrlComponents;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Authority.prototype, "hostnameAndPort", {
/**
* Get hostname and port i.e. login.microsoftonline.com
*/
get: function () {
return this.canonicalAuthorityUrlComponents.HostNameAndPort.toLowerCase();
},
enumerable: false,
configurable: true
});
Object.defineProperty(Authority.prototype, "tenant", {
/**
* Get tenant for authority.
*/
get: function () {
return this.canonicalAuthorityUrlComponents.PathSegments[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(Authority.prototype, "authorizationEndpoint", {
/**
* OAuth /authorize endpoint for requests
*/
get: function () {
if (this.discoveryComplete()) {
var endpoint = this.replacePath(this.metadata.authorization_endpoint);
return this.replaceTenant(endpoint);
}
else {
throw ClientAuthError.createEndpointDiscoveryIncompleteError("Discovery incomplete.");
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(Authority.prototype, "tokenEndpoint", {
/**
* OAuth /token endpoint for requests
*/
get: function () {
if (this.discoveryComplete()) {
var endpoint = this.replacePath(this.metadata.token_endpoint);
return this.replaceTenant(endpoint);
}
else {
throw ClientAuthError.createEndpointDiscoveryIncompleteError("Discovery incomplete.");
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(Authority.prototype, "deviceCodeEndpoint", {
get: function () {
if (this.discoveryComplete()) {
var endpoint = this.replacePath(this.metadata.token_endpoint.replace("/token", "/devicecode"));
return this.replaceTenant(endpoint);
}
else {
throw ClientAuthError.createEndpointDiscoveryIncompleteError("Discovery incomplete.");
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(Authority.prototype, "endSessionEndpoint", {
/**
* OAuth logout endpoint for requests
*/
get: function () {
if (this.discoveryComplete()) {
// ROPC policies may not have end_session_endpoint set
if (!this.metadata.end_session_endpoint) {
throw ClientAuthError.createLogoutNotSupportedError();
}
var endpoint = this.replacePath(this.metadata.end_session_endpoint);
return this.replaceTenant(endpoint);
}
else {
throw ClientAuthError.createEndpointDiscoveryIncompleteError("Discovery incomplete.");
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(Authority.prototype, "selfSignedJwtAudience", {
/**
* OAuth issuer for requests
*/
get: function () {
if (this.discoveryComplete()) {
var endpoint = this.replacePath(this.metadata.issuer);
return this.replaceTenant(endpoint);
}
else {
throw ClientAuthError.createEndpointDiscoveryIncompleteError("Discovery incomplete.");
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(Authority.prototype, "jwksUri", {
/**
* Jwks_uri for token signing keys
*/
get: function () {
if (this.discoveryComplete()) {
var endpoint = this.replacePath(this.metadata.jwks_uri);
return this.replaceTenant(endpoint);
}
else {
throw ClientAuthError.createEndpointDiscoveryIncompleteError("Discovery incomplete.");
}
},
enumerable: false,
configurable: true
});
const endpoint = this.replacePath(this.metadata.end_session_endpoint);
return this.replaceTenant(endpoint);
}
else {
throw ClientAuthError.createEndpointDiscoveryIncompleteError("Discovery incomplete.");
}
}
/**
* OAuth issuer for requests
*/
get selfSignedJwtAudience() {
if (this.discoveryComplete()) {
const endpoint = this.replacePath(this.metadata.issuer);
return this.replaceTenant(endpoint);
}
else {
throw ClientAuthError.createEndpointDiscoveryIncompleteError("Discovery incomplete.");
}
}
/**
* Jwks_uri for token signing keys
*/
get jwksUri() {
if (this.discoveryComplete()) {
const endpoint = this.replacePath(this.metadata.jwks_uri);
return this.replaceTenant(endpoint);
}
else {
throw ClientAuthError.createEndpointDiscoveryIncompleteError("Discovery incomplete.");
}
}
/**
* Replaces tenant in url path with current tenant. Defaults to common.
* @param urlString
*/
Authority.prototype.replaceTenant = function (urlString) {
replaceTenant(urlString) {
return urlString.replace(/{tenant}|{tenantid}/g, this.tenant);
};
}
/**

@@ -244,36 +196,31 @@ * Replaces path such as tenant or policy with the current tenant or policy.

*/
Authority.prototype.replacePath = function (urlString) {
var endpoint = urlString;
var cachedAuthorityUrl = new UrlString(this.metadata.canonical_authority);
var cachedAuthorityParts = cachedAuthorityUrl.getUrlComponents().PathSegments;
var currentAuthorityParts = this.canonicalAuthorityUrlComponents.PathSegments;
currentAuthorityParts.forEach(function (currentPart, index) {
var cachedPart = cachedAuthorityParts[index];
replacePath(urlString) {
let endpoint = urlString;
const cachedAuthorityUrl = new UrlString(this.metadata.canonical_authority);
const cachedAuthorityParts = cachedAuthorityUrl.getUrlComponents().PathSegments;
const currentAuthorityParts = this.canonicalAuthorityUrlComponents.PathSegments;
currentAuthorityParts.forEach((currentPart, index) => {
const cachedPart = cachedAuthorityParts[index];
if (currentPart !== cachedPart) {
endpoint = endpoint.replace("/" + cachedPart + "/", "/" + currentPart + "/");
endpoint = endpoint.replace(`/${cachedPart}/`, `/${currentPart}/`);
}
});
return endpoint;
};
Object.defineProperty(Authority.prototype, "defaultOpenIdConfigurationEndpoint", {
/**
* The default open id configuration endpoint for any canonical authority.
*/
get: function () {
if (this.authorityType === AuthorityType.Adfs ||
this.authorityType === AuthorityType.Dsts ||
this.protocolMode === ProtocolMode.OIDC) {
return this.canonicalAuthority + ".well-known/openid-configuration";
}
return this.canonicalAuthority + "v2.0/.well-known/openid-configuration";
},
enumerable: false,
configurable: true
});
}
/**
* The default open id configuration endpoint for any canonical authority.
*/
get defaultOpenIdConfigurationEndpoint() {
if (this.authorityType === AuthorityType.Adfs ||
this.protocolMode === ProtocolMode.OIDC) {
return `${this.canonicalAuthority}.well-known/openid-configuration`;
}
return `${this.canonicalAuthority}v2.0/.well-known/openid-configuration`;
}
/**
* Boolean that returns whethr or not tenant discovery has been completed.
*/
Authority.prototype.discoveryComplete = function () {
discoveryComplete() {
return !!this.metadata;
};
}
/**

@@ -283,37 +230,24 @@ * Perform endpoint discovery to discover aliases, preferred_cache, preferred_network

*/
Authority.prototype.resolveEndpointsAsync = function () {
var _a, _b, _c;
return __awaiter(this, void 0, void 0, function () {
var metadataEntity, cloudDiscoverySource, endpointSource, cacheKey;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
(_a = this.performanceClient) === null || _a === void 0 ? void 0 : _a.addQueueMeasurement(PerformanceEvents.AuthorityResolveEndpointsAsync, this.correlationId);
metadataEntity = this.cacheManager.getAuthorityMetadataByAlias(this.hostnameAndPort);
if (!metadataEntity) {
metadataEntity = new AuthorityMetadataEntity();
metadataEntity.updateCanonicalAuthority(this.canonicalAuthority);
}
(_b = this.performanceClient) === null || _b === void 0 ? void 0 : _b.setPreQueueTime(PerformanceEvents.AuthorityUpdateCloudDiscoveryMetadata, this.correlationId);
return [4 /*yield*/, this.updateCloudDiscoveryMetadata(metadataEntity)];
case 1:
cloudDiscoverySource = _d.sent();
this.canonicalAuthority = this.canonicalAuthority.replace(this.hostnameAndPort, metadataEntity.preferred_network);
(_c = this.performanceClient) === null || _c === void 0 ? void 0 : _c.setPreQueueTime(PerformanceEvents.AuthorityUpdateEndpointMetadata, this.correlationId);
return [4 /*yield*/, this.updateEndpointMetadata(metadataEntity)];
case 2:
endpointSource = _d.sent();
if (cloudDiscoverySource !== AuthorityMetadataSource.CACHE && endpointSource !== AuthorityMetadataSource.CACHE) {
// Reset the expiration time unless both values came from a successful cache lookup
metadataEntity.resetExpiresAt();
metadataEntity.updateCanonicalAuthority(this.canonicalAuthority);
}
cacheKey = this.cacheManager.generateAuthorityMetadataCacheKey(metadataEntity.preferred_cache);
this.cacheManager.setAuthorityMetadata(cacheKey, metadataEntity);
this.metadata = metadataEntity;
return [2 /*return*/];
}
});
});
};
async resolveEndpointsAsync() {
this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityResolveEndpointsAsync, this.correlationId);
let metadataEntity = this.cacheManager.getAuthorityMetadataByAlias(this.hostnameAndPort);
if (!metadataEntity) {
metadataEntity = new AuthorityMetadataEntity();
metadataEntity.updateCanonicalAuthority(this.canonicalAuthority);
}
this.performanceClient?.setPreQueueTime(PerformanceEvents.AuthorityUpdateCloudDiscoveryMetadata, this.correlationId);
const cloudDiscoverySource = await this.updateCloudDiscoveryMetadata(metadataEntity);
this.canonicalAuthority = this.canonicalAuthority.replace(this.hostnameAndPort, metadataEntity.preferred_network);
this.performanceClient?.setPreQueueTime(PerformanceEvents.AuthorityUpdateEndpointMetadata, this.correlationId);
const endpointSource = await this.updateEndpointMetadata(metadataEntity);
if (cloudDiscoverySource !== AuthorityMetadataSource.CACHE &&
endpointSource !== AuthorityMetadataSource.CACHE) {
// Reset the expiration time unless both values came from a successful cache lookup
metadataEntity.resetExpiresAt();
metadataEntity.updateCanonicalAuthority(this.canonicalAuthority);
}
const cacheKey = this.cacheManager.generateAuthorityMetadataCacheKey(metadataEntity.preferred_cache);
this.cacheManager.setAuthorityMetadata(cacheKey, metadataEntity);
this.metadata = metadataEntity;
}
/**

@@ -323,50 +257,42 @@ * Update AuthorityMetadataEntity with new endpoints and return where the information came from

*/
Authority.prototype.updateEndpointMetadata = function (metadataEntity) {
var _a, _b, _c, _d, _e, _f;
return __awaiter(this, void 0, void 0, function () {
var metadata, harcodedMetadata;
return __generator(this, function (_g) {
switch (_g.label) {
case 0:
(_a = this.performanceClient) === null || _a === void 0 ? void 0 : _a.addQueueMeasurement(PerformanceEvents.AuthorityUpdateEndpointMetadata, this.correlationId);
metadata = this.getEndpointMetadataFromConfig();
if (metadata) {
metadataEntity.updateEndpointMetadata(metadata, false);
return [2 /*return*/, AuthorityMetadataSource.CONFIG];
}
if (this.isAuthoritySameType(metadataEntity) && metadataEntity.endpointsFromNetwork && !metadataEntity.isExpired()) {
// No need to update
return [2 /*return*/, AuthorityMetadataSource.CACHE];
}
(_b = this.performanceClient) === null || _b === void 0 ? void 0 : _b.setPreQueueTime(PerformanceEvents.AuthorityGetEndpointMetadataFromNetwork, this.correlationId);
return [4 /*yield*/, this.getEndpointMetadataFromNetwork()];
case 1:
metadata = _g.sent();
if (!metadata) return [3 /*break*/, 4];
if (!((_c = this.authorityOptions.azureRegionConfiguration) === null || _c === void 0 ? void 0 : _c.azureRegion)) return [3 /*break*/, 3];
(_d = this.performanceClient) === null || _d === void 0 ? void 0 : _d.setPreQueueTime(PerformanceEvents.AuthorityUpdateMetadataWithRegionalInformation, this.correlationId);
return [4 /*yield*/, this.updateMetadataWithRegionalInformation(metadata)];
case 2:
metadata = _g.sent();
_g.label = 3;
case 3:
metadataEntity.updateEndpointMetadata(metadata, true);
return [2 /*return*/, AuthorityMetadataSource.NETWORK];
case 4:
harcodedMetadata = this.getEndpointMetadataFromHardcodedValues();
if (!(harcodedMetadata && !this.authorityOptions.skipAuthorityMetadataCache)) return [3 /*break*/, 7];
if (!((_e = this.authorityOptions.azureRegionConfiguration) === null || _e === void 0 ? void 0 : _e.azureRegion)) return [3 /*break*/, 6];
(_f = this.performanceClient) === null || _f === void 0 ? void 0 : _f.setPreQueueTime(PerformanceEvents.AuthorityUpdateMetadataWithRegionalInformation, this.correlationId);
return [4 /*yield*/, this.updateMetadataWithRegionalInformation(harcodedMetadata)];
case 5:
harcodedMetadata = _g.sent();
_g.label = 6;
case 6:
metadataEntity.updateEndpointMetadata(harcodedMetadata, false);
return [2 /*return*/, AuthorityMetadataSource.HARDCODED_VALUES];
case 7: throw ClientAuthError.createUnableToGetOpenidConfigError(this.defaultOpenIdConfigurationEndpoint);
}
});
});
};
async updateEndpointMetadata(metadataEntity) {
this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityUpdateEndpointMetadata, this.correlationId);
let metadata = this.getEndpointMetadataFromConfig();
if (metadata) {
metadataEntity.updateEndpointMetadata(metadata, false);
return AuthorityMetadataSource.CONFIG;
}
if (this.isAuthoritySameType(metadataEntity) &&
metadataEntity.endpointsFromNetwork &&
!metadataEntity.isExpired()) {
// No need to update
return AuthorityMetadataSource.CACHE;
}
this.performanceClient?.setPreQueueTime(PerformanceEvents.AuthorityGetEndpointMetadataFromNetwork, this.correlationId);
metadata = await this.getEndpointMetadataFromNetwork();
if (metadata) {
// If the user prefers to use an azure region replace the global endpoints with regional information.
if (this.authorityOptions.azureRegionConfiguration?.azureRegion) {
this.performanceClient?.setPreQueueTime(PerformanceEvents.AuthorityUpdateMetadataWithRegionalInformation, this.correlationId);
metadata = await this.updateMetadataWithRegionalInformation(metadata);
}
metadataEntity.updateEndpointMetadata(metadata, true);
return AuthorityMetadataSource.NETWORK;
}
let harcodedMetadata = this.getEndpointMetadataFromHardcodedValues();
if (harcodedMetadata &&
!this.authorityOptions.skipAuthorityMetadataCache) {
// If the user prefers to use an azure region replace the global endpoints with regional information.
if (this.authorityOptions.azureRegionConfiguration?.azureRegion) {
this.performanceClient?.setPreQueueTime(PerformanceEvents.AuthorityUpdateMetadataWithRegionalInformation, this.correlationId);
harcodedMetadata =
await this.updateMetadataWithRegionalInformation(harcodedMetadata);
}
metadataEntity.updateEndpointMetadata(harcodedMetadata, false);
return AuthorityMetadataSource.HARDCODED_VALUES;
}
else {
throw ClientAuthError.createUnableToGetOpenidConfigError(this.defaultOpenIdConfigurationEndpoint);
}
}
/**

@@ -378,11 +304,12 @@ * Compares the number of url components after the domain to determine if the cached

*/
Authority.prototype.isAuthoritySameType = function (metadataEntity) {
var cachedAuthorityUrl = new UrlString(metadataEntity.canonical_authority);
var cachedParts = cachedAuthorityUrl.getUrlComponents().PathSegments;
return cachedParts.length === this.canonicalAuthorityUrlComponents.PathSegments.length;
};
isAuthoritySameType(metadataEntity) {
const cachedAuthorityUrl = new UrlString(metadataEntity.canonical_authority);
const cachedParts = cachedAuthorityUrl.getUrlComponents().PathSegments;
return (cachedParts.length ===
this.canonicalAuthorityUrlComponents.PathSegments.length);
}
/**
* Parse authorityMetadata config option
*/
Authority.prototype.getEndpointMetadataFromConfig = function () {
getEndpointMetadataFromConfig() {
if (this.authorityOptions.authorityMetadata) {

@@ -397,3 +324,3 @@ try {

return null;
};
}
/**

@@ -404,31 +331,35 @@ * Gets OAuth endpoints from the given OpenID configuration endpoint.

*/
Authority.prototype.getEndpointMetadataFromNetwork = function () {
var _a;
return __awaiter(this, void 0, void 0, function () {
var options, response;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
(_a = this.performanceClient) === null || _a === void 0 ? void 0 : _a.addQueueMeasurement(PerformanceEvents.AuthorityGetEndpointMetadataFromNetwork, this.correlationId);
options = {};
_b.label = 1;
case 1:
_b.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.networkInterface.
sendGetRequestAsync(this.defaultOpenIdConfigurationEndpoint, options)];
case 2:
response = _b.sent();
return [2 /*return*/, isOpenIdConfigResponse(response.body) ? response.body : null];
case 3:
_b.sent();
return [2 /*return*/, null];
case 4: return [2 /*return*/];
}
});
});
};
async getEndpointMetadataFromNetwork() {
this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityGetEndpointMetadataFromNetwork, this.correlationId);
const perfEvent = this.performanceClient?.startMeasurement(PerformanceEvents.AuthorityGetEndpointMetadataFromNetwork, this.correlationId);
const options = {};
/*
* TODO: Add a timeout if the authority exists in our library's
* hardcoded list of metadata
*/
const openIdConfigurationEndpoint = this.defaultOpenIdConfigurationEndpoint;
this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: attempting to retrieve OAuth endpoints from ${openIdConfigurationEndpoint}`);
try {
const response = await this.networkInterface.sendGetRequestAsync(openIdConfigurationEndpoint, options);
const isValidResponse = isOpenIdConfigResponse(response.body);
if (isValidResponse) {
perfEvent?.endMeasurement({ success: true });
return response.body;
}
else {
perfEvent?.endMeasurement({ success: false, errorCode: "invalid_response" });
this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: could not parse response as OpenID configuration`);
return null;
}
}
catch (e) {
perfEvent?.endMeasurement({ success: false, errorCode: "request_failure" });
this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: ${e}`);
return null;
}
}
/**
* Get OAuth endpoints for common authorities.
*/
Authority.prototype.getEndpointMetadataFromHardcodedValues = function () {
getEndpointMetadataFromHardcodedValues() {
if (this.canonicalAuthority in EndpointMetadata) {

@@ -438,45 +369,39 @@ return EndpointMetadata[this.canonicalAuthority];

return null;
};
}
/**
* Update the retrieved metadata with regional information.
*/
Authority.prototype.updateMetadataWithRegionalInformation = function (metadata) {
var _a, _b, _c, _d, _e, _f, _g;
return __awaiter(this, void 0, void 0, function () {
var autodetectedRegionName, azureRegion;
return __generator(this, function (_h) {
switch (_h.label) {
case 0:
(_a = this.performanceClient) === null || _a === void 0 ? void 0 : _a.addQueueMeasurement(PerformanceEvents.AuthorityUpdateMetadataWithRegionalInformation, this.correlationId);
(_b = this.performanceClient) === null || _b === void 0 ? void 0 : _b.setPreQueueTime(PerformanceEvents.RegionDiscoveryDetectRegion, this.correlationId);
return [4 /*yield*/, this.regionDiscovery.detectRegion((_c = this.authorityOptions.azureRegionConfiguration) === null || _c === void 0 ? void 0 : _c.environmentRegion, this.regionDiscoveryMetadata)];
case 1:
autodetectedRegionName = _h.sent();
azureRegion = ((_d = this.authorityOptions.azureRegionConfiguration) === null || _d === void 0 ? void 0 : _d.azureRegion) === Constants.AZURE_REGION_AUTO_DISCOVER_FLAG
? autodetectedRegionName
: (_e = this.authorityOptions.azureRegionConfiguration) === null || _e === void 0 ? void 0 : _e.azureRegion;
if (((_f = this.authorityOptions.azureRegionConfiguration) === null || _f === void 0 ? void 0 : _f.azureRegion) === Constants.AZURE_REGION_AUTO_DISCOVER_FLAG) {
this.regionDiscoveryMetadata.region_outcome = autodetectedRegionName ?
RegionDiscoveryOutcomes.AUTO_DETECTION_REQUESTED_SUCCESSFUL :
RegionDiscoveryOutcomes.AUTO_DETECTION_REQUESTED_FAILED;
}
else {
if (autodetectedRegionName) {
this.regionDiscoveryMetadata.region_outcome = (((_g = this.authorityOptions.azureRegionConfiguration) === null || _g === void 0 ? void 0 : _g.azureRegion) === autodetectedRegionName) ?
RegionDiscoveryOutcomes.CONFIGURED_MATCHES_DETECTED :
RegionDiscoveryOutcomes.CONFIGURED_NOT_DETECTED;
}
else {
this.regionDiscoveryMetadata.region_outcome = RegionDiscoveryOutcomes.CONFIGURED_NO_AUTO_DETECTION;
}
}
if (azureRegion) {
this.regionDiscoveryMetadata.region_used = azureRegion;
return [2 /*return*/, Authority.replaceWithRegionalInformation(metadata, azureRegion)];
}
return [2 /*return*/, metadata];
}
});
});
};
async updateMetadataWithRegionalInformation(metadata) {
this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityUpdateMetadataWithRegionalInformation, this.correlationId);
this.performanceClient?.setPreQueueTime(PerformanceEvents.RegionDiscoveryDetectRegion, this.correlationId);
const autodetectedRegionName = await this.regionDiscovery.detectRegion(this.authorityOptions.azureRegionConfiguration?.environmentRegion, this.regionDiscoveryMetadata);
const azureRegion = this.authorityOptions.azureRegionConfiguration?.azureRegion ===
Constants.AZURE_REGION_AUTO_DISCOVER_FLAG
? autodetectedRegionName
: this.authorityOptions.azureRegionConfiguration?.azureRegion;
if (this.authorityOptions.azureRegionConfiguration?.azureRegion ===
Constants.AZURE_REGION_AUTO_DISCOVER_FLAG) {
this.regionDiscoveryMetadata.region_outcome = autodetectedRegionName
? RegionDiscoveryOutcomes.AUTO_DETECTION_REQUESTED_SUCCESSFUL
: RegionDiscoveryOutcomes.AUTO_DETECTION_REQUESTED_FAILED;
}
else {
if (autodetectedRegionName) {
this.regionDiscoveryMetadata.region_outcome =
this.authorityOptions.azureRegionConfiguration
?.azureRegion === autodetectedRegionName
? RegionDiscoveryOutcomes.CONFIGURED_MATCHES_DETECTED
: RegionDiscoveryOutcomes.CONFIGURED_NOT_DETECTED;
}
else {
this.regionDiscoveryMetadata.region_outcome =
RegionDiscoveryOutcomes.CONFIGURED_NO_AUTO_DETECTION;
}
}
if (azureRegion) {
this.regionDiscoveryMetadata.region_used = azureRegion;
return Authority.replaceWithRegionalInformation(metadata, azureRegion);
}
return metadata;
}
/**

@@ -488,60 +413,52 @@ * Updates the AuthorityMetadataEntity with new aliases, preferred_network and preferred_cache

*/
Authority.prototype.updateCloudDiscoveryMetadata = function (metadataEntity) {
var _a, _b;
return __awaiter(this, void 0, void 0, function () {
var metadata, metadataEntityExpired, harcodedMetadata;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
(_a = this.performanceClient) === null || _a === void 0 ? void 0 : _a.addQueueMeasurement(PerformanceEvents.AuthorityUpdateCloudDiscoveryMetadata, this.correlationId);
// attempt to read metadata from the config
this.logger.verbose("Attempting to get cloud discovery metadata in the config");
this.logger.verbosePii("Known Authorities: " + (this.authorityOptions.knownAuthorities || Constants.NOT_APPLICABLE));
this.logger.verbosePii("Authority Metadata: " + (this.authorityOptions.authorityMetadata || Constants.NOT_APPLICABLE));
this.logger.verbosePii("Canonical Authority: " + (metadataEntity.canonical_authority || Constants.NOT_APPLICABLE));
metadata = this.getCloudDiscoveryMetadataFromConfig();
if (metadata) {
this.logger.verbose("Found cloud discovery metadata in the config.");
metadataEntity.updateCloudDiscoveryMetadata(metadata, false);
return [2 /*return*/, AuthorityMetadataSource.CONFIG];
}
// If the cached metadata came from config but that config was not passed to this instance, we must go to the network
this.logger.verbose("Did not find cloud discovery metadata in the config... Attempting to get cloud discovery metadata from the cache.");
metadataEntityExpired = metadataEntity.isExpired();
if (this.isAuthoritySameType(metadataEntity) && metadataEntity.aliasesFromNetwork && !metadataEntityExpired) {
this.logger.verbose("Found metadata in the cache.");
// No need to update
return [2 /*return*/, AuthorityMetadataSource.CACHE];
}
else if (metadataEntityExpired) {
this.logger.verbose("The metadata entity is expired.");
}
this.logger.verbose("Did not find cloud discovery metadata in the cache... Attempting to get cloud discovery metadata from the network.");
(_b = this.performanceClient) === null || _b === void 0 ? void 0 : _b.setPreQueueTime(PerformanceEvents.AuthorityGetCloudDiscoveryMetadataFromNetwork, this.correlationId);
return [4 /*yield*/, this.getCloudDiscoveryMetadataFromNetwork()];
case 1:
metadata = _c.sent();
if (metadata) {
this.logger.verbose("cloud discovery metadata was successfully returned from getCloudDiscoveryMetadataFromNetwork()");
metadataEntity.updateCloudDiscoveryMetadata(metadata, true);
return [2 /*return*/, AuthorityMetadataSource.NETWORK];
}
this.logger.verbose("Did not find cloud discovery metadata from the network... Attempting to get cloud discovery metadata from hardcoded values.");
harcodedMetadata = this.getCloudDiscoveryMetadataFromHarcodedValues();
if (harcodedMetadata && !this.options.skipAuthorityMetadataCache) {
this.logger.verbose("Found cloud discovery metadata from hardcoded values.");
metadataEntity.updateCloudDiscoveryMetadata(harcodedMetadata, false);
return [2 /*return*/, AuthorityMetadataSource.HARDCODED_VALUES];
}
// Metadata could not be obtained from the config, cache, network or hardcoded values
this.logger.error("Did not find cloud discovery metadata from hardcoded values... Metadata could not be obtained from config, cache, network or hardcoded values. Throwing Untrusted Authority Error.");
throw ClientConfigurationError.createUntrustedAuthorityError();
}
});
});
};
async updateCloudDiscoveryMetadata(metadataEntity) {
this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityUpdateCloudDiscoveryMetadata, this.correlationId);
this.logger.verbose("Attempting to get cloud discovery metadata in the config");
this.logger.verbosePii(`Known Authorities: ${this.authorityOptions.knownAuthorities ||
Constants.NOT_APPLICABLE}`);
this.logger.verbosePii(`Authority Metadata: ${this.authorityOptions.authorityMetadata ||
Constants.NOT_APPLICABLE}`);
this.logger.verbosePii(`Canonical Authority: ${metadataEntity.canonical_authority || Constants.NOT_APPLICABLE}`);
let metadata = this.getCloudDiscoveryMetadataFromConfig();
if (metadata) {
this.logger.verbose("Found cloud discovery metadata in the config.");
metadataEntity.updateCloudDiscoveryMetadata(metadata, false);
return AuthorityMetadataSource.CONFIG;
}
// If the cached metadata came from config but that config was not passed to this instance, we must go to the network
this.logger.verbose("Did not find cloud discovery metadata in the config... Attempting to get cloud discovery metadata from the cache.");
const metadataEntityExpired = metadataEntity.isExpired();
if (this.isAuthoritySameType(metadataEntity) &&
metadataEntity.aliasesFromNetwork &&
!metadataEntityExpired) {
this.logger.verbose("Found metadata in the cache.");
// No need to update
return AuthorityMetadataSource.CACHE;
}
else if (metadataEntityExpired) {
this.logger.verbose("The metadata entity is expired.");
}
this.logger.verbose("Did not find cloud discovery metadata in the cache... Attempting to get cloud discovery metadata from the network.");
this.performanceClient?.setPreQueueTime(PerformanceEvents.AuthorityGetCloudDiscoveryMetadataFromNetwork, this.correlationId);
metadata = await this.getCloudDiscoveryMetadataFromNetwork();
if (metadata) {
this.logger.verbose("cloud discovery metadata was successfully returned from getCloudDiscoveryMetadataFromNetwork()");
metadataEntity.updateCloudDiscoveryMetadata(metadata, true);
return AuthorityMetadataSource.NETWORK;
}
this.logger.verbose("Did not find cloud discovery metadata from the network... Attempting to get cloud discovery metadata from hardcoded values.");
const harcodedMetadata = this.getCloudDiscoveryMetadataFromHarcodedValues();
if (harcodedMetadata && !this.options.skipAuthorityMetadataCache) {
this.logger.verbose("Found cloud discovery metadata from hardcoded values.");
metadataEntity.updateCloudDiscoveryMetadata(harcodedMetadata, false);
return AuthorityMetadataSource.HARDCODED_VALUES;
}
// Metadata could not be obtained from the config, cache, network or hardcoded values
this.logger.error("Did not find cloud discovery metadata from hardcoded values... Metadata could not be obtained from config, cache, network or hardcoded values. Throwing Untrusted Authority Error.");
throw ClientConfigurationError.createUntrustedAuthorityError();
}
/**
* Parse cloudDiscoveryMetadata config or check knownAuthorities
*/
Authority.prototype.getCloudDiscoveryMetadataFromConfig = function () {
getCloudDiscoveryMetadataFromConfig() {
// CIAM does not support cloud discovery metadata

@@ -557,4 +474,4 @@ if (this.authorityType === AuthorityType.Ciam) {

this.logger.verbose("Attempting to parse the cloud discovery metadata.");
var parsedResponse = JSON.parse(this.authorityOptions.cloudDiscoveryMetadata);
var metadata = Authority.getCloudDiscoveryMetadataFromNetworkResponse(parsedResponse.metadata, this.hostnameAndPort);
const parsedResponse = JSON.parse(this.authorityOptions.cloudDiscoveryMetadata);
const metadata = Authority.getCloudDiscoveryMetadataFromNetworkResponse(parsedResponse.metadata, this.hostnameAndPort);
this.logger.verbose("Parsed the cloud discovery metadata.");

@@ -580,3 +497,3 @@ if (metadata) {

return null;
};
}
/**

@@ -587,71 +504,63 @@ * Called to get metadata from network if CloudDiscoveryMetadata was not populated by config

*/
Authority.prototype.getCloudDiscoveryMetadataFromNetwork = function () {
var _a;
return __awaiter(this, void 0, void 0, function () {
var instanceDiscoveryEndpoint, options, match, response, typedResponseBody, metadata, error_1, typedError;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
(_a = this.performanceClient) === null || _a === void 0 ? void 0 : _a.addQueueMeasurement(PerformanceEvents.AuthorityGetCloudDiscoveryMetadataFromNetwork, this.correlationId);
instanceDiscoveryEndpoint = "" + Constants.AAD_INSTANCE_DISCOVERY_ENDPT + this.canonicalAuthority + "oauth2/v2.0/authorize";
options = {};
match = null;
_b.label = 1;
case 1:
_b.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.networkInterface.sendGetRequestAsync(instanceDiscoveryEndpoint, options)];
case 2:
response = _b.sent();
typedResponseBody = void 0;
metadata = void 0;
if (isCloudInstanceDiscoveryResponse(response.body)) {
typedResponseBody = response.body;
metadata = typedResponseBody.metadata;
this.logger.verbosePii("tenant_discovery_endpoint is: " + typedResponseBody.tenant_discovery_endpoint);
}
else if (isCloudInstanceDiscoveryErrorResponse(response.body)) {
this.logger.warning("A CloudInstanceDiscoveryErrorResponse was returned. The cloud instance discovery network request's status code is: " + response.status);
typedResponseBody = response.body;
if (typedResponseBody.error === Constants.INVALID_INSTANCE) {
this.logger.error("The CloudInstanceDiscoveryErrorResponse error is invalid_instance.");
return [2 /*return*/, null];
}
this.logger.warning("The CloudInstanceDiscoveryErrorResponse error is " + typedResponseBody.error);
this.logger.warning("The CloudInstanceDiscoveryErrorResponse error description is " + typedResponseBody.error_description);
this.logger.warning("Setting the value of the CloudInstanceDiscoveryMetadata (returned from the network) to []");
metadata = [];
}
else {
this.logger.error("AAD did not return a CloudInstanceDiscoveryResponse or CloudInstanceDiscoveryErrorResponse");
return [2 /*return*/, null];
}
this.logger.verbose("Attempting to find a match between the developer's authority and the CloudInstanceDiscoveryMetadata returned from the network request.");
match = Authority.getCloudDiscoveryMetadataFromNetworkResponse(metadata, this.hostnameAndPort);
return [3 /*break*/, 4];
case 3:
error_1 = _b.sent();
if (error_1 instanceof AuthError) {
this.logger.error("There was a network error while attempting to get the cloud discovery instance metadata.\nError: " + error_1.errorCode + "\nError Description: " + error_1.errorMessage);
}
else {
typedError = error_1;
this.logger.error("A non-MSALJS error was thrown while attempting to get the cloud instance discovery metadata.\nError: " + typedError.name + "\nError Description: " + typedError.message);
}
return [2 /*return*/, null];
case 4:
// Custom Domain scenario, host is trusted because Instance Discovery call succeeded
if (!match) {
this.logger.warning("The developer's authority was not found within the CloudInstanceDiscoveryMetadata returned from the network request.");
this.logger.verbose("Creating custom Authority for custom domain scenario.");
match = Authority.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort);
}
return [2 /*return*/, match];
async getCloudDiscoveryMetadataFromNetwork() {
this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityGetCloudDiscoveryMetadataFromNetwork, this.correlationId);
const instanceDiscoveryEndpoint = `${Constants.AAD_INSTANCE_DISCOVERY_ENDPT}${this.canonicalAuthority}oauth2/v2.0/authorize`;
const options = {};
/*
* TODO: Add a timeout if the authority exists in our library's
* hardcoded list of metadata
*/
let match = null;
try {
const response = await this.networkInterface.sendGetRequestAsync(instanceDiscoveryEndpoint, options);
let typedResponseBody;
let metadata;
if (isCloudInstanceDiscoveryResponse(response.body)) {
typedResponseBody =
response.body;
metadata = typedResponseBody.metadata;
this.logger.verbosePii(`tenant_discovery_endpoint is: ${typedResponseBody.tenant_discovery_endpoint}`);
}
else if (isCloudInstanceDiscoveryErrorResponse(response.body)) {
this.logger.warning(`A CloudInstanceDiscoveryErrorResponse was returned. The cloud instance discovery network request's status code is: ${response.status}`);
typedResponseBody =
response.body;
if (typedResponseBody.error === Constants.INVALID_INSTANCE) {
this.logger.error("The CloudInstanceDiscoveryErrorResponse error is invalid_instance.");
return null;
}
});
});
};
this.logger.warning(`The CloudInstanceDiscoveryErrorResponse error is ${typedResponseBody.error}`);
this.logger.warning(`The CloudInstanceDiscoveryErrorResponse error description is ${typedResponseBody.error_description}`);
this.logger.warning("Setting the value of the CloudInstanceDiscoveryMetadata (returned from the network) to []");
metadata = [];
}
else {
this.logger.error("AAD did not return a CloudInstanceDiscoveryResponse or CloudInstanceDiscoveryErrorResponse");
return null;
}
this.logger.verbose("Attempting to find a match between the developer's authority and the CloudInstanceDiscoveryMetadata returned from the network request.");
match = Authority.getCloudDiscoveryMetadataFromNetworkResponse(metadata, this.hostnameAndPort);
}
catch (error) {
if (error instanceof AuthError) {
this.logger.error(`There was a network error while attempting to get the cloud discovery instance metadata.\nError: ${error.errorCode}\nError Description: ${error.errorMessage}`);
}
else {
const typedError = error;
this.logger.error(`A non-MSALJS error was thrown while attempting to get the cloud instance discovery metadata.\nError: ${typedError.name}\nError Description: ${typedError.message}`);
}
return null;
}
// Custom Domain scenario, host is trusted because Instance Discovery call succeeded
if (!match) {
this.logger.warning("The developer's authority was not found within the CloudInstanceDiscoveryMetadata returned from the network request.");
this.logger.verbose("Creating custom Authority for custom domain scenario.");
match = Authority.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort);
}
return match;
}
/**
* Get cloud discovery metadata for common authorities
*/
Authority.prototype.getCloudDiscoveryMetadataFromHarcodedValues = function () {
getCloudDiscoveryMetadataFromHarcodedValues() {
if (this.canonicalAuthority in InstanceDiscoveryMetadata) {

@@ -661,13 +570,13 @@ return InstanceDiscoveryMetadata[this.canonicalAuthority];

return null;
};
}
/**
* Helper function to determine if this host is included in the knownAuthorities config option
*/
Authority.prototype.isInKnownAuthorities = function () {
var _this = this;
var matches = this.authorityOptions.knownAuthorities.filter(function (authority) {
return UrlString.getDomainFromUrl(authority).toLowerCase() === _this.hostnameAndPort;
isInKnownAuthorities() {
const matches = this.authorityOptions.knownAuthorities.filter((authority) => {
return (UrlString.getDomainFromUrl(authority).toLowerCase() ===
this.hostnameAndPort);
});
return matches.length > 0;
};
}
/**

@@ -678,10 +587,15 @@ * helper function to populate the authority based on azureCloudOptions

*/
Authority.generateAuthority = function (authorityString, azureCloudOptions) {
var authorityAzureCloudInstance;
if (azureCloudOptions && azureCloudOptions.azureCloudInstance !== AzureCloudInstance.None) {
var tenant = azureCloudOptions.tenant ? azureCloudOptions.tenant : Constants.DEFAULT_COMMON_TENANT;
authorityAzureCloudInstance = azureCloudOptions.azureCloudInstance + "/" + tenant + "/";
static generateAuthority(authorityString, azureCloudOptions) {
let authorityAzureCloudInstance;
if (azureCloudOptions &&
azureCloudOptions.azureCloudInstance !== AzureCloudInstance.None) {
const tenant = azureCloudOptions.tenant
? azureCloudOptions.tenant
: Constants.DEFAULT_COMMON_TENANT;
authorityAzureCloudInstance = `${azureCloudOptions.azureCloudInstance}/${tenant}/`;
}
return authorityAzureCloudInstance ? authorityAzureCloudInstance : authorityString;
};
return authorityAzureCloudInstance
? authorityAzureCloudInstance
: authorityString;
}
/**

@@ -691,9 +605,9 @@ * Creates cloud discovery metadata object from a given host

*/
Authority.createCloudDiscoveryMetadataFromHost = function (host) {
static createCloudDiscoveryMetadataFromHost(host) {
return {
preferred_network: host,
preferred_cache: host,
aliases: [host]
aliases: [host],
};
};
}
/**

@@ -704,5 +618,5 @@ * Searches instance discovery network response for the entry that contains the host in the aliases list

*/
Authority.getCloudDiscoveryMetadataFromNetworkResponse = function (response, authority) {
for (var i = 0; i < response.length; i++) {
var metadata = response[i];
static getCloudDiscoveryMetadataFromNetworkResponse(response, authority) {
for (let i = 0; i < response.length; i++) {
const metadata = response[i];
if (metadata.aliases.indexOf(authority) > -1) {

@@ -713,7 +627,7 @@ return metadata;

return null;
};
}
/**
* helper function to generate environment from authority object
*/
Authority.prototype.getPreferredCache = function () {
getPreferredCache() {
if (this.discoveryComplete()) {

@@ -725,3 +639,3 @@ return this.metadata.preferred_cache;

}
};
}
/**

@@ -731,5 +645,5 @@ * Returns whether or not the provided host is an alias of this authority instance

*/
Authority.prototype.isAlias = function (host) {
isAlias(host) {
return this.metadata.aliases.indexOf(host) > -1;
};
}
/**

@@ -741,5 +655,5 @@ * Checks whether the provided host is that of a public cloud authority

*/
Authority.isPublicCloudAuthority = function (host) {
static isPublicCloudAuthority(host) {
return Constants.KNOWN_PUBLIC_CLOUDS.indexOf(host) >= 0;
};
}
/**

@@ -751,18 +665,21 @@ * Rebuild the authority string with the region

*/
Authority.buildRegionalAuthorityString = function (host, region, queryString) {
static buildRegionalAuthorityString(host, region, queryString) {
// Create and validate a Url string object with the initial authority string
var authorityUrlInstance = new UrlString(host);
const authorityUrlInstance = new UrlString(host);
authorityUrlInstance.validateAsUri();
var authorityUrlParts = authorityUrlInstance.getUrlComponents();
var hostNameAndPort = region + "." + authorityUrlParts.HostNameAndPort;
const authorityUrlParts = authorityUrlInstance.getUrlComponents();
let hostNameAndPort = `${region}.${authorityUrlParts.HostNameAndPort}`;
if (this.isPublicCloudAuthority(authorityUrlParts.HostNameAndPort)) {
hostNameAndPort = region + "." + Constants.REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX;
hostNameAndPort = `${region}.${Constants.REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX}`;
}
// Include the query string portion of the url
var url = UrlString.constructAuthorityUriFromObject(__assign(__assign({}, authorityUrlInstance.getUrlComponents()), { HostNameAndPort: hostNameAndPort })).urlString;
const url = UrlString.constructAuthorityUriFromObject({
...authorityUrlInstance.getUrlComponents(),
HostNameAndPort: hostNameAndPort,
}).urlString;
// Add the query string if a query string was provided
if (queryString)
return url + "?" + queryString;
return `${url}?${queryString}`;
return url;
};
}
/**

@@ -774,11 +691,13 @@ * Replace the endpoints in the metadata object with their regional equivalents.

*/
Authority.replaceWithRegionalInformation = function (metadata, azureRegion) {
metadata.authorization_endpoint = Authority.buildRegionalAuthorityString(metadata.authorization_endpoint, azureRegion);
static replaceWithRegionalInformation(metadata, azureRegion) {
metadata.authorization_endpoint =
Authority.buildRegionalAuthorityString(metadata.authorization_endpoint, azureRegion);
// TODO: Enquire on whether we should leave the query string or remove it before releasing the feature
metadata.token_endpoint = Authority.buildRegionalAuthorityString(metadata.token_endpoint, azureRegion, Constants.REGIONAL_AUTH_NON_MSI_QUERY_STRING);
if (metadata.end_session_endpoint) {
metadata.end_session_endpoint = Authority.buildRegionalAuthorityString(metadata.end_session_endpoint, azureRegion);
metadata.end_session_endpoint =
Authority.buildRegionalAuthorityString(metadata.end_session_endpoint, azureRegion);
}
return metadata;
};
}
/**

@@ -793,17 +712,16 @@ * Transform CIAM_AUTHORIY as per the below rules:

*/
Authority.transformCIAMAuthority = function (authority) {
var ciamAuthority = authority.endsWith(Constants.FORWARD_SLASH) ? authority : "" + authority + Constants.FORWARD_SLASH;
var authorityUrl = new UrlString(authority);
var authorityUrlComponents = authorityUrl.getUrlComponents();
static transformCIAMAuthority(authority) {
let ciamAuthority = authority.endsWith(Constants.FORWARD_SLASH) ? authority : `${authority}${Constants.FORWARD_SLASH}`;
const authorityUrl = new UrlString(authority);
const authorityUrlComponents = authorityUrl.getUrlComponents();
// check if transformation is needed
if (authorityUrlComponents.PathSegments.length === 0 && (authorityUrlComponents.HostNameAndPort.endsWith(Constants.CIAM_AUTH_URL))) {
var tenantIdOrDomain = authorityUrlComponents.HostNameAndPort.split(".")[0];
ciamAuthority = "" + ciamAuthority + tenantIdOrDomain + Constants.AAD_TENANT_DOMAIN_SUFFIX;
const tenantIdOrDomain = authorityUrlComponents.HostNameAndPort.split(".")[0];
ciamAuthority = `${ciamAuthority}${tenantIdOrDomain}${Constants.AAD_TENANT_DOMAIN_SUFFIX}`;
}
return ciamAuthority;
};
return Authority;
}());
}
}
export { Authority };
//# sourceMappingURL=Authority.js.map

@@ -1,4 +0,3 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';
import { __awaiter, __generator } from '../_virtual/_tslib.js';
import { Authority } from './Authority.js';

@@ -14,5 +13,3 @@ import { ClientConfigurationError } from '../error/ClientConfigurationError.js';

*/
var AuthorityFactory = /** @class */ (function () {
function AuthorityFactory() {
}
class AuthorityFactory {
/**

@@ -28,27 +25,16 @@ * Create an authority object of the correct type based on the url

*/
AuthorityFactory.createDiscoveredInstance = function (authorityUri, networkClient, cacheManager, authorityOptions, logger, performanceClient, correlationId) {
return __awaiter(this, void 0, void 0, function () {
var authorityUriFinal, acquireTokenAuthority, e_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
performanceClient === null || performanceClient === void 0 ? void 0 : performanceClient.addQueueMeasurement(PerformanceEvents.AuthorityFactoryCreateDiscoveredInstance, correlationId);
authorityUriFinal = Authority.transformCIAMAuthority(authorityUri);
acquireTokenAuthority = AuthorityFactory.createInstance(authorityUriFinal, networkClient, cacheManager, authorityOptions, logger, performanceClient, correlationId);
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
performanceClient === null || performanceClient === void 0 ? void 0 : performanceClient.setPreQueueTime(PerformanceEvents.AuthorityResolveEndpointsAsync, correlationId);
return [4 /*yield*/, acquireTokenAuthority.resolveEndpointsAsync()];
case 2:
_a.sent();
return [2 /*return*/, acquireTokenAuthority];
case 3:
e_1 = _a.sent();
throw ClientAuthError.createEndpointDiscoveryIncompleteError(e_1);
case 4: return [2 /*return*/];
}
});
});
};
static async createDiscoveredInstance(authorityUri, networkClient, cacheManager, authorityOptions, logger, performanceClient, correlationId) {
performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityFactoryCreateDiscoveredInstance, correlationId);
const authorityUriFinal = Authority.transformCIAMAuthority(authorityUri);
// Initialize authority and perform discovery endpoint check.
const acquireTokenAuthority = AuthorityFactory.createInstance(authorityUriFinal, networkClient, cacheManager, authorityOptions, logger, performanceClient, correlationId);
try {
performanceClient?.setPreQueueTime(PerformanceEvents.AuthorityResolveEndpointsAsync, correlationId);
await acquireTokenAuthority.resolveEndpointsAsync();
return acquireTokenAuthority;
}
catch (e) {
throw ClientAuthError.createEndpointDiscoveryIncompleteError(e);
}
}
/**

@@ -64,3 +50,3 @@ * Create an authority object of the correct type based on the url

*/
AuthorityFactory.createInstance = function (authorityUrl, networkInterface, cacheManager, authorityOptions, logger, performanceClient, correlationId) {
static createInstance(authorityUrl, networkInterface, cacheManager, authorityOptions, logger, performanceClient, correlationId) {
// Throw error if authority url is empty

@@ -71,7 +57,6 @@ if (StringUtils.isEmpty(authorityUrl)) {

return new Authority(authorityUrl, networkInterface, cacheManager, authorityOptions, logger, performanceClient, correlationId);
};
return AuthorityFactory;
}());
}
}
export { AuthorityFactory };
//# sourceMappingURL=AuthorityFactory.js.map

@@ -1,2 +0,2 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';

@@ -7,7 +7,876 @@ /*

*/
var rawMetdataJSON = { "endpointMetadata": { "https://login.microsoftonline.com/common/": { "token_endpoint": "https://login.microsoftonline.com/common/oauth2/v2.0/token", "token_endpoint_auth_methods_supported": ["client_secret_post", "private_key_jwt", "client_secret_basic"], "jwks_uri": "https://login.microsoftonline.com/common/discovery/v2.0/keys", "response_modes_supported": ["query", "fragment", "form_post"], "subject_types_supported": ["pairwise"], "id_token_signing_alg_values_supported": ["RS256"], "response_types_supported": ["code", "id_token", "code id_token", "id_token token"], "scopes_supported": ["openid", "profile", "email", "offline_access"], "issuer": "https://login.microsoftonline.com/{tenantid}/v2.0", "request_uri_parameter_supported": false, "userinfo_endpoint": "https://graph.microsoft.com/oidc/userinfo", "authorization_endpoint": "https://login.microsoftonline.com/common/oauth2/v2.0/authorize", "device_authorization_endpoint": "https://login.microsoftonline.com/common/oauth2/v2.0/devicecode", "http_logout_supported": true, "frontchannel_logout_supported": true, "end_session_endpoint": "https://login.microsoftonline.com/common/oauth2/v2.0/logout", "claims_supported": ["sub", "iss", "cloud_instance_name", "cloud_instance_host_name", "cloud_graph_host_name", "msgraph_host", "aud", "exp", "iat", "auth_time", "acr", "nonce", "preferred_username", "name", "tid", "ver", "at_hash", "c_hash", "email"], "kerberos_endpoint": "https://login.microsoftonline.com/common/kerberos", "tenant_region_scope": null, "cloud_instance_name": "microsoftonline.com", "cloud_graph_host_name": "graph.windows.net", "msgraph_host": "graph.microsoft.com", "rbac_url": "https://pas.windows.net" }, "https://login.chinacloudapi.cn/common/": { "token_endpoint": "https://login.chinacloudapi.cn/common/oauth2/v2.0/token", "token_endpoint_auth_methods_supported": ["client_secret_post", "private_key_jwt", "client_secret_basic"], "jwks_uri": "https://login.chinacloudapi.cn/common/discovery/v2.0/keys", "response_modes_supported": ["query", "fragment", "form_post"], "subject_types_supported": ["pairwise"], "id_token_signing_alg_values_supported": ["RS256"], "response_types_supported": ["code", "id_token", "code id_token", "id_token token"], "scopes_supported": ["openid", "profile", "email", "offline_access"], "issuer": "https://login.partner.microsoftonline.cn/{tenantid}/v2.0", "request_uri_parameter_supported": false, "userinfo_endpoint": "https://microsoftgraph.chinacloudapi.cn/oidc/userinfo", "authorization_endpoint": "https://login.chinacloudapi.cn/common/oauth2/v2.0/authorize", "device_authorization_endpoint": "https://login.chinacloudapi.cn/common/oauth2/v2.0/devicecode", "http_logout_supported": true, "frontchannel_logout_supported": true, "end_session_endpoint": "https://login.chinacloudapi.cn/common/oauth2/v2.0/logout", "claims_supported": ["sub", "iss", "cloud_instance_name", "cloud_instance_host_name", "cloud_graph_host_name", "msgraph_host", "aud", "exp", "iat", "auth_time", "acr", "nonce", "preferred_username", "name", "tid", "ver", "at_hash", "c_hash", "email"], "kerberos_endpoint": "https://login.chinacloudapi.cn/common/kerberos", "tenant_region_scope": null, "cloud_instance_name": "partner.microsoftonline.cn", "cloud_graph_host_name": "graph.chinacloudapi.cn", "msgraph_host": "microsoftgraph.chinacloudapi.cn", "rbac_url": "https://pas.chinacloudapi.cn" }, "https://login.microsoftonline.us/common/": { "token_endpoint": "https://login.microsoftonline.us/common/oauth2/v2.0/token", "token_endpoint_auth_methods_supported": ["client_secret_post", "private_key_jwt", "client_secret_basic"], "jwks_uri": "https://login.microsoftonline.us/common/discovery/v2.0/keys", "response_modes_supported": ["query", "fragment", "form_post"], "subject_types_supported": ["pairwise"], "id_token_signing_alg_values_supported": ["RS256"], "response_types_supported": ["code", "id_token", "code id_token", "id_token token"], "scopes_supported": ["openid", "profile", "email", "offline_access"], "issuer": "https://login.microsoftonline.us/{tenantid}/v2.0", "request_uri_parameter_supported": false, "userinfo_endpoint": "https://graph.microsoft.com/oidc/userinfo", "authorization_endpoint": "https://login.microsoftonline.us/common/oauth2/v2.0/authorize", "device_authorization_endpoint": "https://login.microsoftonline.us/common/oauth2/v2.0/devicecode", "http_logout_supported": true, "frontchannel_logout_supported": true, "end_session_endpoint": "https://login.microsoftonline.us/common/oauth2/v2.0/logout", "claims_supported": ["sub", "iss", "cloud_instance_name", "cloud_instance_host_name", "cloud_graph_host_name", "msgraph_host", "aud", "exp", "iat", "auth_time", "acr", "nonce", "preferred_username", "name", "tid", "ver", "at_hash", "c_hash", "email"], "kerberos_endpoint": "https://login.microsoftonline.us/common/kerberos", "tenant_region_scope": null, "cloud_instance_name": "microsoftonline.us", "cloud_graph_host_name": "graph.windows.net", "msgraph_host": "graph.microsoft.com", "rbac_url": "https://pasff.usgovcloudapi.net" }, "https://login.microsoftonline.com/consumers/": { "token_endpoint": "https://login.microsoftonline.com/consumers/oauth2/v2.0/token", "token_endpoint_auth_methods_supported": ["client_secret_post", "private_key_jwt", "client_secret_basic"], "jwks_uri": "https://login.microsoftonline.com/consumers/discovery/v2.0/keys", "response_modes_supported": ["query", "fragment", "form_post"], "subject_types_supported": ["pairwise"], "id_token_signing_alg_values_supported": ["RS256"], "response_types_supported": ["code", "id_token", "code id_token", "id_token token"], "scopes_supported": ["openid", "profile", "email", "offline_access"], "issuer": "https://login.microsoftonline.com/9188040d-6c67-4c5b-b112-36a304b66dad/v2.0", "request_uri_parameter_supported": false, "userinfo_endpoint": "https://graph.microsoft.com/oidc/userinfo", "authorization_endpoint": "https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize", "device_authorization_endpoint": "https://login.microsoftonline.com/consumers/oauth2/v2.0/devicecode", "http_logout_supported": true, "frontchannel_logout_supported": true, "end_session_endpoint": "https://login.microsoftonline.com/consumers/oauth2/v2.0/logout", "claims_supported": ["sub", "iss", "cloud_instance_name", "cloud_instance_host_name", "cloud_graph_host_name", "msgraph_host", "aud", "exp", "iat", "auth_time", "acr", "nonce", "preferred_username", "name", "tid", "ver", "at_hash", "c_hash", "email"], "kerberos_endpoint": "https://login.microsoftonline.com/consumers/kerberos", "tenant_region_scope": null, "cloud_instance_name": "microsoftonline.com", "cloud_graph_host_name": "graph.windows.net", "msgraph_host": "graph.microsoft.com", "rbac_url": "https://pas.windows.net" }, "https://login.chinacloudapi.cn/consumers/": { "token_endpoint": "https://login.chinacloudapi.cn/consumers/oauth2/v2.0/token", "token_endpoint_auth_methods_supported": ["client_secret_post", "private_key_jwt", "client_secret_basic"], "jwks_uri": "https://login.chinacloudapi.cn/consumers/discovery/v2.0/keys", "response_modes_supported": ["query", "fragment", "form_post"], "subject_types_supported": ["pairwise"], "id_token_signing_alg_values_supported": ["RS256"], "response_types_supported": ["code", "id_token", "code id_token", "id_token token"], "scopes_supported": ["openid", "profile", "email", "offline_access"], "issuer": "https://login.partner.microsoftonline.cn/9188040d-6c67-4c5b-b112-36a304b66dad/v2.0", "request_uri_parameter_supported": false, "userinfo_endpoint": "https://microsoftgraph.chinacloudapi.cn/oidc/userinfo", "authorization_endpoint": "https://login.chinacloudapi.cn/consumers/oauth2/v2.0/authorize", "device_authorization_endpoint": "https://login.chinacloudapi.cn/consumers/oauth2/v2.0/devicecode", "http_logout_supported": true, "frontchannel_logout_supported": true, "end_session_endpoint": "https://login.chinacloudapi.cn/consumers/oauth2/v2.0/logout", "claims_supported": ["sub", "iss", "cloud_instance_name", "cloud_instance_host_name", "cloud_graph_host_name", "msgraph_host", "aud", "exp", "iat", "auth_time", "acr", "nonce", "preferred_username", "name", "tid", "ver", "at_hash", "c_hash", "email"], "kerberos_endpoint": "https://login.chinacloudapi.cn/consumers/kerberos", "tenant_region_scope": null, "cloud_instance_name": "partner.microsoftonline.cn", "cloud_graph_host_name": "graph.chinacloudapi.cn", "msgraph_host": "microsoftgraph.chinacloudapi.cn", "rbac_url": "https://pas.chinacloudapi.cn" }, "https://login.microsoftonline.us/consumers/": { "token_endpoint": "https://login.microsoftonline.us/consumers/oauth2/v2.0/token", "token_endpoint_auth_methods_supported": ["client_secret_post", "private_key_jwt", "client_secret_basic"], "jwks_uri": "https://login.microsoftonline.us/consumers/discovery/v2.0/keys", "response_modes_supported": ["query", "fragment", "form_post"], "subject_types_supported": ["pairwise"], "id_token_signing_alg_values_supported": ["RS256"], "response_types_supported": ["code", "id_token", "code id_token", "id_token token"], "scopes_supported": ["openid", "profile", "email", "offline_access"], "issuer": "https://login.microsoftonline.us/9188040d-6c67-4c5b-b112-36a304b66dad/v2.0", "request_uri_parameter_supported": false, "userinfo_endpoint": "https://graph.microsoft.com/oidc/userinfo", "authorization_endpoint": "https://login.microsoftonline.us/consumers/oauth2/v2.0/authorize", "device_authorization_endpoint": "https://login.microsoftonline.us/consumers/oauth2/v2.0/devicecode", "http_logout_supported": true, "frontchannel_logout_supported": true, "end_session_endpoint": "https://login.microsoftonline.us/consumers/oauth2/v2.0/logout", "claims_supported": ["sub", "iss", "cloud_instance_name", "cloud_instance_host_name", "cloud_graph_host_name", "msgraph_host", "aud", "exp", "iat", "auth_time", "acr", "nonce", "preferred_username", "name", "tid", "ver", "at_hash", "c_hash", "email"], "kerberos_endpoint": "https://login.microsoftonline.us/consumers/kerberos", "tenant_region_scope": null, "cloud_instance_name": "microsoftonline.us", "cloud_graph_host_name": "graph.windows.net", "msgraph_host": "graph.microsoft.com", "rbac_url": "https://pasff.usgovcloudapi.net" }, "https://login.microsoftonline.com/organizations/": { "token_endpoint": "https://login.microsoftonline.com/organizations/oauth2/v2.0/token", "token_endpoint_auth_methods_supported": ["client_secret_post", "private_key_jwt", "client_secret_basic"], "jwks_uri": "https://login.microsoftonline.com/organizations/discovery/v2.0/keys", "response_modes_supported": ["query", "fragment", "form_post"], "subject_types_supported": ["pairwise"], "id_token_signing_alg_values_supported": ["RS256"], "response_types_supported": ["code", "id_token", "code id_token", "id_token token"], "scopes_supported": ["openid", "profile", "email", "offline_access"], "issuer": "https://login.microsoftonline.com/{tenantid}/v2.0", "request_uri_parameter_supported": false, "userinfo_endpoint": "https://graph.microsoft.com/oidc/userinfo", "authorization_endpoint": "https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize", "device_authorization_endpoint": "https://login.microsoftonline.com/organizations/oauth2/v2.0/devicecode", "http_logout_supported": true, "frontchannel_logout_supported": true, "end_session_endpoint": "https://login.microsoftonline.com/organizations/oauth2/v2.0/logout", "claims_supported": ["sub", "iss", "cloud_instance_name", "cloud_instance_host_name", "cloud_graph_host_name", "msgraph_host", "aud", "exp", "iat", "auth_time", "acr", "nonce", "preferred_username", "name", "tid", "ver", "at_hash", "c_hash", "email"], "kerberos_endpoint": "https://login.microsoftonline.com/organizations/kerberos", "tenant_region_scope": null, "cloud_instance_name": "microsoftonline.com", "cloud_graph_host_name": "graph.windows.net", "msgraph_host": "graph.microsoft.com", "rbac_url": "https://pas.windows.net" }, "https://login.chinacloudapi.cn/organizations/": { "token_endpoint": "https://login.chinacloudapi.cn/organizations/oauth2/v2.0/token", "token_endpoint_auth_methods_supported": ["client_secret_post", "private_key_jwt", "client_secret_basic"], "jwks_uri": "https://login.chinacloudapi.cn/organizations/discovery/v2.0/keys", "response_modes_supported": ["query", "fragment", "form_post"], "subject_types_supported": ["pairwise"], "id_token_signing_alg_values_supported": ["RS256"], "response_types_supported": ["code", "id_token", "code id_token", "id_token token"], "scopes_supported": ["openid", "profile", "email", "offline_access"], "issuer": "https://login.partner.microsoftonline.cn/{tenantid}/v2.0", "request_uri_parameter_supported": false, "userinfo_endpoint": "https://microsoftgraph.chinacloudapi.cn/oidc/userinfo", "authorization_endpoint": "https://login.chinacloudapi.cn/organizations/oauth2/v2.0/authorize", "device_authorization_endpoint": "https://login.chinacloudapi.cn/organizations/oauth2/v2.0/devicecode", "http_logout_supported": true, "frontchannel_logout_supported": true, "end_session_endpoint": "https://login.chinacloudapi.cn/organizations/oauth2/v2.0/logout", "claims_supported": ["sub", "iss", "cloud_instance_name", "cloud_instance_host_name", "cloud_graph_host_name", "msgraph_host", "aud", "exp", "iat", "auth_time", "acr", "nonce", "preferred_username", "name", "tid", "ver", "at_hash", "c_hash", "email"], "kerberos_endpoint": "https://login.chinacloudapi.cn/organizations/kerberos", "tenant_region_scope": null, "cloud_instance_name": "partner.microsoftonline.cn", "cloud_graph_host_name": "graph.chinacloudapi.cn", "msgraph_host": "microsoftgraph.chinacloudapi.cn", "rbac_url": "https://pas.chinacloudapi.cn" }, "https://login.microsoftonline.us/organizations/": { "token_endpoint": "https://login.microsoftonline.us/organizations/oauth2/v2.0/token", "token_endpoint_auth_methods_supported": ["client_secret_post", "private_key_jwt", "client_secret_basic"], "jwks_uri": "https://login.microsoftonline.us/organizations/discovery/v2.0/keys", "response_modes_supported": ["query", "fragment", "form_post"], "subject_types_supported": ["pairwise"], "id_token_signing_alg_values_supported": ["RS256"], "response_types_supported": ["code", "id_token", "code id_token", "id_token token"], "scopes_supported": ["openid", "profile", "email", "offline_access"], "issuer": "https://login.microsoftonline.us/{tenantid}/v2.0", "request_uri_parameter_supported": false, "userinfo_endpoint": "https://graph.microsoft.com/oidc/userinfo", "authorization_endpoint": "https://login.microsoftonline.us/organizations/oauth2/v2.0/authorize", "device_authorization_endpoint": "https://login.microsoftonline.us/organizations/oauth2/v2.0/devicecode", "http_logout_supported": true, "frontchannel_logout_supported": true, "end_session_endpoint": "https://login.microsoftonline.us/organizations/oauth2/v2.0/logout", "claims_supported": ["sub", "iss", "cloud_instance_name", "cloud_instance_host_name", "cloud_graph_host_name", "msgraph_host", "aud", "exp", "iat", "auth_time", "acr", "nonce", "preferred_username", "name", "tid", "ver", "at_hash", "c_hash", "email"], "kerberos_endpoint": "https://login.microsoftonline.us/organizations/kerberos", "tenant_region_scope": null, "cloud_instance_name": "microsoftonline.us", "cloud_graph_host_name": "graph.windows.net", "msgraph_host": "graph.microsoft.com", "rbac_url": "https://pasff.usgovcloudapi.net" } }, "instanceDiscoveryMetadata": { "https://login.microsoftonline.com/common/": { "tenant_discovery_endpoint": "https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration", "api-version": "1.1", "metadata": [{ "preferred_network": "login.microsoftonline.com", "preferred_cache": "login.windows.net", "aliases": ["login.microsoftonline.com", "login.windows.net", "login.microsoft.com", "sts.windows.net"] }, { "preferred_network": "login.partner.microsoftonline.cn", "preferred_cache": "login.partner.microsoftonline.cn", "aliases": ["login.partner.microsoftonline.cn", "login.chinacloudapi.cn"] }, { "preferred_network": "login.microsoftonline.de", "preferred_cache": "login.microsoftonline.de", "aliases": ["login.microsoftonline.de"] }, { "preferred_network": "login.microsoftonline.us", "preferred_cache": "login.microsoftonline.us", "aliases": ["login.microsoftonline.us", "login.usgovcloudapi.net"] }, { "preferred_network": "login-us.microsoftonline.com", "preferred_cache": "login-us.microsoftonline.com", "aliases": ["login-us.microsoftonline.com"] }] }, "https://login.chinacloudapi.cn/common/": { "tenant_discovery_endpoint": "https://login.chinacloudapi.cn/common/v2.0/.well-known/openid-configuration", "api-version": "1.1", "metadata": [{ "preferred_network": "login.microsoftonline.com", "preferred_cache": "login.windows.net", "aliases": ["login.microsoftonline.com", "login.windows.net", "login.microsoft.com", "sts.windows.net"] }, { "preferred_network": "login.partner.microsoftonline.cn", "preferred_cache": "login.partner.microsoftonline.cn", "aliases": ["login.partner.microsoftonline.cn", "login.chinacloudapi.cn"] }, { "preferred_network": "login.microsoftonline.de", "preferred_cache": "login.microsoftonline.de", "aliases": ["login.microsoftonline.de"] }, { "preferred_network": "login.microsoftonline.us", "preferred_cache": "login.microsoftonline.us", "aliases": ["login.microsoftonline.us", "login.usgovcloudapi.net"] }, { "preferred_network": "login-us.microsoftonline.com", "preferred_cache": "login-us.microsoftonline.com", "aliases": ["login-us.microsoftonline.com"] }] }, "https://login.microsoftonline.us/common/": { "tenant_discovery_endpoint": "https://login.microsoftonline.us/common/v2.0/.well-known/openid-configuration", "api-version": "1.1", "metadata": [{ "preferred_network": "login.microsoftonline.com", "preferred_cache": "login.windows.net", "aliases": ["login.microsoftonline.com", "login.windows.net", "login.microsoft.com", "sts.windows.net"] }, { "preferred_network": "login.partner.microsoftonline.cn", "preferred_cache": "login.partner.microsoftonline.cn", "aliases": ["login.partner.microsoftonline.cn", "login.chinacloudapi.cn"] }, { "preferred_network": "login.microsoftonline.de", "preferred_cache": "login.microsoftonline.de", "aliases": ["login.microsoftonline.de"] }, { "preferred_network": "login.microsoftonline.us", "preferred_cache": "login.microsoftonline.us", "aliases": ["login.microsoftonline.us", "login.usgovcloudapi.net"] }, { "preferred_network": "login-us.microsoftonline.com", "preferred_cache": "login-us.microsoftonline.com", "aliases": ["login-us.microsoftonline.com"] }] }, "https://login.microsoftonline.com/consumers/": { "tenant_discovery_endpoint": "https://login.microsoftonline.com/consumers/v2.0/.well-known/openid-configuration", "api-version": "1.1", "metadata": [{ "preferred_network": "login.microsoftonline.com", "preferred_cache": "login.windows.net", "aliases": ["login.microsoftonline.com", "login.windows.net", "login.microsoft.com", "sts.windows.net"] }, { "preferred_network": "login.partner.microsoftonline.cn", "preferred_cache": "login.partner.microsoftonline.cn", "aliases": ["login.partner.microsoftonline.cn", "login.chinacloudapi.cn"] }, { "preferred_network": "login.microsoftonline.de", "preferred_cache": "login.microsoftonline.de", "aliases": ["login.microsoftonline.de"] }, { "preferred_network": "login.microsoftonline.us", "preferred_cache": "login.microsoftonline.us", "aliases": ["login.microsoftonline.us", "login.usgovcloudapi.net"] }, { "preferred_network": "login-us.microsoftonline.com", "preferred_cache": "login-us.microsoftonline.com", "aliases": ["login-us.microsoftonline.com"] }] }, "https://login.chinacloudapi.cn/consumers/": { "tenant_discovery_endpoint": "https://login.chinacloudapi.cn/consumers/v2.0/.well-known/openid-configuration", "api-version": "1.1", "metadata": [{ "preferred_network": "login.microsoftonline.com", "preferred_cache": "login.windows.net", "aliases": ["login.microsoftonline.com", "login.windows.net", "login.microsoft.com", "sts.windows.net"] }, { "preferred_network": "login.partner.microsoftonline.cn", "preferred_cache": "login.partner.microsoftonline.cn", "aliases": ["login.partner.microsoftonline.cn", "login.chinacloudapi.cn"] }, { "preferred_network": "login.microsoftonline.de", "preferred_cache": "login.microsoftonline.de", "aliases": ["login.microsoftonline.de"] }, { "preferred_network": "login.microsoftonline.us", "preferred_cache": "login.microsoftonline.us", "aliases": ["login.microsoftonline.us", "login.usgovcloudapi.net"] }, { "preferred_network": "login-us.microsoftonline.com", "preferred_cache": "login-us.microsoftonline.com", "aliases": ["login-us.microsoftonline.com"] }] }, "https://login.microsoftonline.us/consumers/": { "tenant_discovery_endpoint": "https://login.microsoftonline.us/consumers/v2.0/.well-known/openid-configuration", "api-version": "1.1", "metadata": [{ "preferred_network": "login.microsoftonline.com", "preferred_cache": "login.windows.net", "aliases": ["login.microsoftonline.com", "login.windows.net", "login.microsoft.com", "sts.windows.net"] }, { "preferred_network": "login.partner.microsoftonline.cn", "preferred_cache": "login.partner.microsoftonline.cn", "aliases": ["login.partner.microsoftonline.cn", "login.chinacloudapi.cn"] }, { "preferred_network": "login.microsoftonline.de", "preferred_cache": "login.microsoftonline.de", "aliases": ["login.microsoftonline.de"] }, { "preferred_network": "login.microsoftonline.us", "preferred_cache": "login.microsoftonline.us", "aliases": ["login.microsoftonline.us", "login.usgovcloudapi.net"] }, { "preferred_network": "login-us.microsoftonline.com", "preferred_cache": "login-us.microsoftonline.com", "aliases": ["login-us.microsoftonline.com"] }] }, "https://login.microsoftonline.com/organizations/": { "tenant_discovery_endpoint": "https://login.microsoftonline.com/organizations/v2.0/.well-known/openid-configuration", "api-version": "1.1", "metadata": [{ "preferred_network": "login.microsoftonline.com", "preferred_cache": "login.windows.net", "aliases": ["login.microsoftonline.com", "login.windows.net", "login.microsoft.com", "sts.windows.net"] }, { "preferred_network": "login.partner.microsoftonline.cn", "preferred_cache": "login.partner.microsoftonline.cn", "aliases": ["login.partner.microsoftonline.cn", "login.chinacloudapi.cn"] }, { "preferred_network": "login.microsoftonline.de", "preferred_cache": "login.microsoftonline.de", "aliases": ["login.microsoftonline.de"] }, { "preferred_network": "login.microsoftonline.us", "preferred_cache": "login.microsoftonline.us", "aliases": ["login.microsoftonline.us", "login.usgovcloudapi.net"] }, { "preferred_network": "login-us.microsoftonline.com", "preferred_cache": "login-us.microsoftonline.com", "aliases": ["login-us.microsoftonline.com"] }] }, "https://login.chinacloudapi.cn/organizations/": { "tenant_discovery_endpoint": "https://login.chinacloudapi.cn/organizations/v2.0/.well-known/openid-configuration", "api-version": "1.1", "metadata": [{ "preferred_network": "login.microsoftonline.com", "preferred_cache": "login.windows.net", "aliases": ["login.microsoftonline.com", "login.windows.net", "login.microsoft.com", "sts.windows.net"] }, { "preferred_network": "login.partner.microsoftonline.cn", "preferred_cache": "login.partner.microsoftonline.cn", "aliases": ["login.partner.microsoftonline.cn", "login.chinacloudapi.cn"] }, { "preferred_network": "login.microsoftonline.de", "preferred_cache": "login.microsoftonline.de", "aliases": ["login.microsoftonline.de"] }, { "preferred_network": "login.microsoftonline.us", "preferred_cache": "login.microsoftonline.us", "aliases": ["login.microsoftonline.us", "login.usgovcloudapi.net"] }, { "preferred_network": "login-us.microsoftonline.com", "preferred_cache": "login-us.microsoftonline.com", "aliases": ["login-us.microsoftonline.com"] }] }, "https://login.microsoftonline.us/organizations/": { "tenant_discovery_endpoint": "https://login.microsoftonline.us/organizations/v2.0/.well-known/openid-configuration", "api-version": "1.1", "metadata": [{ "preferred_network": "login.microsoftonline.com", "preferred_cache": "login.windows.net", "aliases": ["login.microsoftonline.com", "login.windows.net", "login.microsoft.com", "sts.windows.net"] }, { "preferred_network": "login.partner.microsoftonline.cn", "preferred_cache": "login.partner.microsoftonline.cn", "aliases": ["login.partner.microsoftonline.cn", "login.chinacloudapi.cn"] }, { "preferred_network": "login.microsoftonline.de", "preferred_cache": "login.microsoftonline.de", "aliases": ["login.microsoftonline.de"] }, { "preferred_network": "login.microsoftonline.us", "preferred_cache": "login.microsoftonline.us", "aliases": ["login.microsoftonline.us", "login.usgovcloudapi.net"] }, { "preferred_network": "login-us.microsoftonline.com", "preferred_cache": "login-us.microsoftonline.com", "aliases": ["login-us.microsoftonline.com"] }] } } };
var EndpointMetadata = rawMetdataJSON.endpointMetadata;
var InstanceDiscoveryMetadata = rawMetdataJSON.instanceDiscoveryMetadata;
const rawMetdataJSON = {
endpointMetadata: {
"https://login.microsoftonline.com/common/": {
token_endpoint: "https://login.microsoftonline.com/common/oauth2/v2.0/token",
token_endpoint_auth_methods_supported: [
"client_secret_post",
"private_key_jwt",
"client_secret_basic",
],
jwks_uri: "https://login.microsoftonline.com/common/discovery/v2.0/keys",
response_modes_supported: ["query", "fragment", "form_post"],
subject_types_supported: ["pairwise"],
id_token_signing_alg_values_supported: ["RS256"],
response_types_supported: [
"code",
"id_token",
"code id_token",
"id_token token",
],
scopes_supported: ["openid", "profile", "email", "offline_access"],
issuer: "https://login.microsoftonline.com/{tenantid}/v2.0",
request_uri_parameter_supported: false,
userinfo_endpoint: "https://graph.microsoft.com/oidc/userinfo",
authorization_endpoint: "https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
device_authorization_endpoint: "https://login.microsoftonline.com/common/oauth2/v2.0/devicecode",
http_logout_supported: true,
frontchannel_logout_supported: true,
end_session_endpoint: "https://login.microsoftonline.com/common/oauth2/v2.0/logout",
claims_supported: [
"sub",
"iss",
"cloud_instance_name",
"cloud_instance_host_name",
"cloud_graph_host_name",
"msgraph_host",
"aud",
"exp",
"iat",
"auth_time",
"acr",
"nonce",
"preferred_username",
"name",
"tid",
"ver",
"at_hash",
"c_hash",
"email",
],
kerberos_endpoint: "https://login.microsoftonline.com/common/kerberos",
tenant_region_scope: null,
cloud_instance_name: "microsoftonline.com",
cloud_graph_host_name: "graph.windows.net",
msgraph_host: "graph.microsoft.com",
rbac_url: "https://pas.windows.net",
},
"https://login.chinacloudapi.cn/common/": {
token_endpoint: "https://login.chinacloudapi.cn/common/oauth2/v2.0/token",
token_endpoint_auth_methods_supported: [
"client_secret_post",
"private_key_jwt",
"client_secret_basic",
],
jwks_uri: "https://login.chinacloudapi.cn/common/discovery/v2.0/keys",
response_modes_supported: ["query", "fragment", "form_post"],
subject_types_supported: ["pairwise"],
id_token_signing_alg_values_supported: ["RS256"],
response_types_supported: [
"code",
"id_token",
"code id_token",
"id_token token",
],
scopes_supported: ["openid", "profile", "email", "offline_access"],
issuer: "https://login.partner.microsoftonline.cn/{tenantid}/v2.0",
request_uri_parameter_supported: false,
userinfo_endpoint: "https://microsoftgraph.chinacloudapi.cn/oidc/userinfo",
authorization_endpoint: "https://login.chinacloudapi.cn/common/oauth2/v2.0/authorize",
device_authorization_endpoint: "https://login.chinacloudapi.cn/common/oauth2/v2.0/devicecode",
http_logout_supported: true,
frontchannel_logout_supported: true,
end_session_endpoint: "https://login.chinacloudapi.cn/common/oauth2/v2.0/logout",
claims_supported: [
"sub",
"iss",
"cloud_instance_name",
"cloud_instance_host_name",
"cloud_graph_host_name",
"msgraph_host",
"aud",
"exp",
"iat",
"auth_time",
"acr",
"nonce",
"preferred_username",
"name",
"tid",
"ver",
"at_hash",
"c_hash",
"email",
],
kerberos_endpoint: "https://login.chinacloudapi.cn/common/kerberos",
tenant_region_scope: null,
cloud_instance_name: "partner.microsoftonline.cn",
cloud_graph_host_name: "graph.chinacloudapi.cn",
msgraph_host: "microsoftgraph.chinacloudapi.cn",
rbac_url: "https://pas.chinacloudapi.cn",
},
"https://login.microsoftonline.us/common/": {
token_endpoint: "https://login.microsoftonline.us/common/oauth2/v2.0/token",
token_endpoint_auth_methods_supported: [
"client_secret_post",
"private_key_jwt",
"client_secret_basic",
],
jwks_uri: "https://login.microsoftonline.us/common/discovery/v2.0/keys",
response_modes_supported: ["query", "fragment", "form_post"],
subject_types_supported: ["pairwise"],
id_token_signing_alg_values_supported: ["RS256"],
response_types_supported: [
"code",
"id_token",
"code id_token",
"id_token token",
],
scopes_supported: ["openid", "profile", "email", "offline_access"],
issuer: "https://login.microsoftonline.us/{tenantid}/v2.0",
request_uri_parameter_supported: false,
userinfo_endpoint: "https://graph.microsoft.com/oidc/userinfo",
authorization_endpoint: "https://login.microsoftonline.us/common/oauth2/v2.0/authorize",
device_authorization_endpoint: "https://login.microsoftonline.us/common/oauth2/v2.0/devicecode",
http_logout_supported: true,
frontchannel_logout_supported: true,
end_session_endpoint: "https://login.microsoftonline.us/common/oauth2/v2.0/logout",
claims_supported: [
"sub",
"iss",
"cloud_instance_name",
"cloud_instance_host_name",
"cloud_graph_host_name",
"msgraph_host",
"aud",
"exp",
"iat",
"auth_time",
"acr",
"nonce",
"preferred_username",
"name",
"tid",
"ver",
"at_hash",
"c_hash",
"email",
],
kerberos_endpoint: "https://login.microsoftonline.us/common/kerberos",
tenant_region_scope: null,
cloud_instance_name: "microsoftonline.us",
cloud_graph_host_name: "graph.windows.net",
msgraph_host: "graph.microsoft.com",
rbac_url: "https://pasff.usgovcloudapi.net",
},
"https://login.microsoftonline.com/consumers/": {
token_endpoint: "https://login.microsoftonline.com/consumers/oauth2/v2.0/token",
token_endpoint_auth_methods_supported: [
"client_secret_post",
"private_key_jwt",
"client_secret_basic",
],
jwks_uri: "https://login.microsoftonline.com/consumers/discovery/v2.0/keys",
response_modes_supported: ["query", "fragment", "form_post"],
subject_types_supported: ["pairwise"],
id_token_signing_alg_values_supported: ["RS256"],
response_types_supported: [
"code",
"id_token",
"code id_token",
"id_token token",
],
scopes_supported: ["openid", "profile", "email", "offline_access"],
issuer: "https://login.microsoftonline.com/9188040d-6c67-4c5b-b112-36a304b66dad/v2.0",
request_uri_parameter_supported: false,
userinfo_endpoint: "https://graph.microsoft.com/oidc/userinfo",
authorization_endpoint: "https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize",
device_authorization_endpoint: "https://login.microsoftonline.com/consumers/oauth2/v2.0/devicecode",
http_logout_supported: true,
frontchannel_logout_supported: true,
end_session_endpoint: "https://login.microsoftonline.com/consumers/oauth2/v2.0/logout",
claims_supported: [
"sub",
"iss",
"cloud_instance_name",
"cloud_instance_host_name",
"cloud_graph_host_name",
"msgraph_host",
"aud",
"exp",
"iat",
"auth_time",
"acr",
"nonce",
"preferred_username",
"name",
"tid",
"ver",
"at_hash",
"c_hash",
"email",
],
kerberos_endpoint: "https://login.microsoftonline.com/consumers/kerberos",
tenant_region_scope: null,
cloud_instance_name: "microsoftonline.com",
cloud_graph_host_name: "graph.windows.net",
msgraph_host: "graph.microsoft.com",
rbac_url: "https://pas.windows.net",
},
"https://login.chinacloudapi.cn/consumers/": {
token_endpoint: "https://login.chinacloudapi.cn/consumers/oauth2/v2.0/token",
token_endpoint_auth_methods_supported: [
"client_secret_post",
"private_key_jwt",
"client_secret_basic",
],
jwks_uri: "https://login.chinacloudapi.cn/consumers/discovery/v2.0/keys",
response_modes_supported: ["query", "fragment", "form_post"],
subject_types_supported: ["pairwise"],
id_token_signing_alg_values_supported: ["RS256"],
response_types_supported: [
"code",
"id_token",
"code id_token",
"id_token token",
],
scopes_supported: ["openid", "profile", "email", "offline_access"],
issuer: "https://login.partner.microsoftonline.cn/9188040d-6c67-4c5b-b112-36a304b66dad/v2.0",
request_uri_parameter_supported: false,
userinfo_endpoint: "https://microsoftgraph.chinacloudapi.cn/oidc/userinfo",
authorization_endpoint: "https://login.chinacloudapi.cn/consumers/oauth2/v2.0/authorize",
device_authorization_endpoint: "https://login.chinacloudapi.cn/consumers/oauth2/v2.0/devicecode",
http_logout_supported: true,
frontchannel_logout_supported: true,
end_session_endpoint: "https://login.chinacloudapi.cn/consumers/oauth2/v2.0/logout",
claims_supported: [
"sub",
"iss",
"cloud_instance_name",
"cloud_instance_host_name",
"cloud_graph_host_name",
"msgraph_host",
"aud",
"exp",
"iat",
"auth_time",
"acr",
"nonce",
"preferred_username",
"name",
"tid",
"ver",
"at_hash",
"c_hash",
"email",
],
kerberos_endpoint: "https://login.chinacloudapi.cn/consumers/kerberos",
tenant_region_scope: null,
cloud_instance_name: "partner.microsoftonline.cn",
cloud_graph_host_name: "graph.chinacloudapi.cn",
msgraph_host: "microsoftgraph.chinacloudapi.cn",
rbac_url: "https://pas.chinacloudapi.cn",
},
"https://login.microsoftonline.us/consumers/": {
token_endpoint: "https://login.microsoftonline.us/consumers/oauth2/v2.0/token",
token_endpoint_auth_methods_supported: [
"client_secret_post",
"private_key_jwt",
"client_secret_basic",
],
jwks_uri: "https://login.microsoftonline.us/consumers/discovery/v2.0/keys",
response_modes_supported: ["query", "fragment", "form_post"],
subject_types_supported: ["pairwise"],
id_token_signing_alg_values_supported: ["RS256"],
response_types_supported: [
"code",
"id_token",
"code id_token",
"id_token token",
],
scopes_supported: ["openid", "profile", "email", "offline_access"],
issuer: "https://login.microsoftonline.us/9188040d-6c67-4c5b-b112-36a304b66dad/v2.0",
request_uri_parameter_supported: false,
userinfo_endpoint: "https://graph.microsoft.com/oidc/userinfo",
authorization_endpoint: "https://login.microsoftonline.us/consumers/oauth2/v2.0/authorize",
device_authorization_endpoint: "https://login.microsoftonline.us/consumers/oauth2/v2.0/devicecode",
http_logout_supported: true,
frontchannel_logout_supported: true,
end_session_endpoint: "https://login.microsoftonline.us/consumers/oauth2/v2.0/logout",
claims_supported: [
"sub",
"iss",
"cloud_instance_name",
"cloud_instance_host_name",
"cloud_graph_host_name",
"msgraph_host",
"aud",
"exp",
"iat",
"auth_time",
"acr",
"nonce",
"preferred_username",
"name",
"tid",
"ver",
"at_hash",
"c_hash",
"email",
],
kerberos_endpoint: "https://login.microsoftonline.us/consumers/kerberos",
tenant_region_scope: null,
cloud_instance_name: "microsoftonline.us",
cloud_graph_host_name: "graph.windows.net",
msgraph_host: "graph.microsoft.com",
rbac_url: "https://pasff.usgovcloudapi.net",
},
"https://login.microsoftonline.com/organizations/": {
token_endpoint: "https://login.microsoftonline.com/organizations/oauth2/v2.0/token",
token_endpoint_auth_methods_supported: [
"client_secret_post",
"private_key_jwt",
"client_secret_basic",
],
jwks_uri: "https://login.microsoftonline.com/organizations/discovery/v2.0/keys",
response_modes_supported: ["query", "fragment", "form_post"],
subject_types_supported: ["pairwise"],
id_token_signing_alg_values_supported: ["RS256"],
response_types_supported: [
"code",
"id_token",
"code id_token",
"id_token token",
],
scopes_supported: ["openid", "profile", "email", "offline_access"],
issuer: "https://login.microsoftonline.com/{tenantid}/v2.0",
request_uri_parameter_supported: false,
userinfo_endpoint: "https://graph.microsoft.com/oidc/userinfo",
authorization_endpoint: "https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize",
device_authorization_endpoint: "https://login.microsoftonline.com/organizations/oauth2/v2.0/devicecode",
http_logout_supported: true,
frontchannel_logout_supported: true,
end_session_endpoint: "https://login.microsoftonline.com/organizations/oauth2/v2.0/logout",
claims_supported: [
"sub",
"iss",
"cloud_instance_name",
"cloud_instance_host_name",
"cloud_graph_host_name",
"msgraph_host",
"aud",
"exp",
"iat",
"auth_time",
"acr",
"nonce",
"preferred_username",
"name",
"tid",
"ver",
"at_hash",
"c_hash",
"email",
],
kerberos_endpoint: "https://login.microsoftonline.com/organizations/kerberos",
tenant_region_scope: null,
cloud_instance_name: "microsoftonline.com",
cloud_graph_host_name: "graph.windows.net",
msgraph_host: "graph.microsoft.com",
rbac_url: "https://pas.windows.net",
},
"https://login.chinacloudapi.cn/organizations/": {
token_endpoint: "https://login.chinacloudapi.cn/organizations/oauth2/v2.0/token",
token_endpoint_auth_methods_supported: [
"client_secret_post",
"private_key_jwt",
"client_secret_basic",
],
jwks_uri: "https://login.chinacloudapi.cn/organizations/discovery/v2.0/keys",
response_modes_supported: ["query", "fragment", "form_post"],
subject_types_supported: ["pairwise"],
id_token_signing_alg_values_supported: ["RS256"],
response_types_supported: [
"code",
"id_token",
"code id_token",
"id_token token",
],
scopes_supported: ["openid", "profile", "email", "offline_access"],
issuer: "https://login.partner.microsoftonline.cn/{tenantid}/v2.0",
request_uri_parameter_supported: false,
userinfo_endpoint: "https://microsoftgraph.chinacloudapi.cn/oidc/userinfo",
authorization_endpoint: "https://login.chinacloudapi.cn/organizations/oauth2/v2.0/authorize",
device_authorization_endpoint: "https://login.chinacloudapi.cn/organizations/oauth2/v2.0/devicecode",
http_logout_supported: true,
frontchannel_logout_supported: true,
end_session_endpoint: "https://login.chinacloudapi.cn/organizations/oauth2/v2.0/logout",
claims_supported: [
"sub",
"iss",
"cloud_instance_name",
"cloud_instance_host_name",
"cloud_graph_host_name",
"msgraph_host",
"aud",
"exp",
"iat",
"auth_time",
"acr",
"nonce",
"preferred_username",
"name",
"tid",
"ver",
"at_hash",
"c_hash",
"email",
],
kerberos_endpoint: "https://login.chinacloudapi.cn/organizations/kerberos",
tenant_region_scope: null,
cloud_instance_name: "partner.microsoftonline.cn",
cloud_graph_host_name: "graph.chinacloudapi.cn",
msgraph_host: "microsoftgraph.chinacloudapi.cn",
rbac_url: "https://pas.chinacloudapi.cn",
},
"https://login.microsoftonline.us/organizations/": {
token_endpoint: "https://login.microsoftonline.us/organizations/oauth2/v2.0/token",
token_endpoint_auth_methods_supported: [
"client_secret_post",
"private_key_jwt",
"client_secret_basic",
],
jwks_uri: "https://login.microsoftonline.us/organizations/discovery/v2.0/keys",
response_modes_supported: ["query", "fragment", "form_post"],
subject_types_supported: ["pairwise"],
id_token_signing_alg_values_supported: ["RS256"],
response_types_supported: [
"code",
"id_token",
"code id_token",
"id_token token",
],
scopes_supported: ["openid", "profile", "email", "offline_access"],
issuer: "https://login.microsoftonline.us/{tenantid}/v2.0",
request_uri_parameter_supported: false,
userinfo_endpoint: "https://graph.microsoft.com/oidc/userinfo",
authorization_endpoint: "https://login.microsoftonline.us/organizations/oauth2/v2.0/authorize",
device_authorization_endpoint: "https://login.microsoftonline.us/organizations/oauth2/v2.0/devicecode",
http_logout_supported: true,
frontchannel_logout_supported: true,
end_session_endpoint: "https://login.microsoftonline.us/organizations/oauth2/v2.0/logout",
claims_supported: [
"sub",
"iss",
"cloud_instance_name",
"cloud_instance_host_name",
"cloud_graph_host_name",
"msgraph_host",
"aud",
"exp",
"iat",
"auth_time",
"acr",
"nonce",
"preferred_username",
"name",
"tid",
"ver",
"at_hash",
"c_hash",
"email",
],
kerberos_endpoint: "https://login.microsoftonline.us/organizations/kerberos",
tenant_region_scope: null,
cloud_instance_name: "microsoftonline.us",
cloud_graph_host_name: "graph.windows.net",
msgraph_host: "graph.microsoft.com",
rbac_url: "https://pasff.usgovcloudapi.net",
},
},
instanceDiscoveryMetadata: {
"https://login.microsoftonline.com/common/": {
tenant_discovery_endpoint: "https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration",
"api-version": "1.1",
metadata: [
{
preferred_network: "login.microsoftonline.com",
preferred_cache: "login.windows.net",
aliases: [
"login.microsoftonline.com",
"login.windows.net",
"login.microsoft.com",
"sts.windows.net",
],
},
{
preferred_network: "login.partner.microsoftonline.cn",
preferred_cache: "login.partner.microsoftonline.cn",
aliases: [
"login.partner.microsoftonline.cn",
"login.chinacloudapi.cn",
],
},
{
preferred_network: "login.microsoftonline.de",
preferred_cache: "login.microsoftonline.de",
aliases: ["login.microsoftonline.de"],
},
{
preferred_network: "login.microsoftonline.us",
preferred_cache: "login.microsoftonline.us",
aliases: [
"login.microsoftonline.us",
"login.usgovcloudapi.net",
],
},
{
preferred_network: "login-us.microsoftonline.com",
preferred_cache: "login-us.microsoftonline.com",
aliases: ["login-us.microsoftonline.com"],
},
],
},
"https://login.chinacloudapi.cn/common/": {
tenant_discovery_endpoint: "https://login.chinacloudapi.cn/common/v2.0/.well-known/openid-configuration",
"api-version": "1.1",
metadata: [
{
preferred_network: "login.microsoftonline.com",
preferred_cache: "login.windows.net",
aliases: [
"login.microsoftonline.com",
"login.windows.net",
"login.microsoft.com",
"sts.windows.net",
],
},
{
preferred_network: "login.partner.microsoftonline.cn",
preferred_cache: "login.partner.microsoftonline.cn",
aliases: [
"login.partner.microsoftonline.cn",
"login.chinacloudapi.cn",
],
},
{
preferred_network: "login.microsoftonline.de",
preferred_cache: "login.microsoftonline.de",
aliases: ["login.microsoftonline.de"],
},
{
preferred_network: "login.microsoftonline.us",
preferred_cache: "login.microsoftonline.us",
aliases: [
"login.microsoftonline.us",
"login.usgovcloudapi.net",
],
},
{
preferred_network: "login-us.microsoftonline.com",
preferred_cache: "login-us.microsoftonline.com",
aliases: ["login-us.microsoftonline.com"],
},
],
},
"https://login.microsoftonline.us/common/": {
tenant_discovery_endpoint: "https://login.microsoftonline.us/common/v2.0/.well-known/openid-configuration",
"api-version": "1.1",
metadata: [
{
preferred_network: "login.microsoftonline.com",
preferred_cache: "login.windows.net",
aliases: [
"login.microsoftonline.com",
"login.windows.net",
"login.microsoft.com",
"sts.windows.net",
],
},
{
preferred_network: "login.partner.microsoftonline.cn",
preferred_cache: "login.partner.microsoftonline.cn",
aliases: [
"login.partner.microsoftonline.cn",
"login.chinacloudapi.cn",
],
},
{
preferred_network: "login.microsoftonline.de",
preferred_cache: "login.microsoftonline.de",
aliases: ["login.microsoftonline.de"],
},
{
preferred_network: "login.microsoftonline.us",
preferred_cache: "login.microsoftonline.us",
aliases: [
"login.microsoftonline.us",
"login.usgovcloudapi.net",
],
},
{
preferred_network: "login-us.microsoftonline.com",
preferred_cache: "login-us.microsoftonline.com",
aliases: ["login-us.microsoftonline.com"],
},
],
},
"https://login.microsoftonline.com/consumers/": {
tenant_discovery_endpoint: "https://login.microsoftonline.com/consumers/v2.0/.well-known/openid-configuration",
"api-version": "1.1",
metadata: [
{
preferred_network: "login.microsoftonline.com",
preferred_cache: "login.windows.net",
aliases: [
"login.microsoftonline.com",
"login.windows.net",
"login.microsoft.com",
"sts.windows.net",
],
},
{
preferred_network: "login.partner.microsoftonline.cn",
preferred_cache: "login.partner.microsoftonline.cn",
aliases: [
"login.partner.microsoftonline.cn",
"login.chinacloudapi.cn",
],
},
{
preferred_network: "login.microsoftonline.de",
preferred_cache: "login.microsoftonline.de",
aliases: ["login.microsoftonline.de"],
},
{
preferred_network: "login.microsoftonline.us",
preferred_cache: "login.microsoftonline.us",
aliases: [
"login.microsoftonline.us",
"login.usgovcloudapi.net",
],
},
{
preferred_network: "login-us.microsoftonline.com",
preferred_cache: "login-us.microsoftonline.com",
aliases: ["login-us.microsoftonline.com"],
},
],
},
"https://login.chinacloudapi.cn/consumers/": {
tenant_discovery_endpoint: "https://login.chinacloudapi.cn/consumers/v2.0/.well-known/openid-configuration",
"api-version": "1.1",
metadata: [
{
preferred_network: "login.microsoftonline.com",
preferred_cache: "login.windows.net",
aliases: [
"login.microsoftonline.com",
"login.windows.net",
"login.microsoft.com",
"sts.windows.net",
],
},
{
preferred_network: "login.partner.microsoftonline.cn",
preferred_cache: "login.partner.microsoftonline.cn",
aliases: [
"login.partner.microsoftonline.cn",
"login.chinacloudapi.cn",
],
},
{
preferred_network: "login.microsoftonline.de",
preferred_cache: "login.microsoftonline.de",
aliases: ["login.microsoftonline.de"],
},
{
preferred_network: "login.microsoftonline.us",
preferred_cache: "login.microsoftonline.us",
aliases: [
"login.microsoftonline.us",
"login.usgovcloudapi.net",
],
},
{
preferred_network: "login-us.microsoftonline.com",
preferred_cache: "login-us.microsoftonline.com",
aliases: ["login-us.microsoftonline.com"],
},
],
},
"https://login.microsoftonline.us/consumers/": {
tenant_discovery_endpoint: "https://login.microsoftonline.us/consumers/v2.0/.well-known/openid-configuration",
"api-version": "1.1",
metadata: [
{
preferred_network: "login.microsoftonline.com",
preferred_cache: "login.windows.net",
aliases: [
"login.microsoftonline.com",
"login.windows.net",
"login.microsoft.com",
"sts.windows.net",
],
},
{
preferred_network: "login.partner.microsoftonline.cn",
preferred_cache: "login.partner.microsoftonline.cn",
aliases: [
"login.partner.microsoftonline.cn",
"login.chinacloudapi.cn",
],
},
{
preferred_network: "login.microsoftonline.de",
preferred_cache: "login.microsoftonline.de",
aliases: ["login.microsoftonline.de"],
},
{
preferred_network: "login.microsoftonline.us",
preferred_cache: "login.microsoftonline.us",
aliases: [
"login.microsoftonline.us",
"login.usgovcloudapi.net",
],
},
{
preferred_network: "login-us.microsoftonline.com",
preferred_cache: "login-us.microsoftonline.com",
aliases: ["login-us.microsoftonline.com"],
},
],
},
"https://login.microsoftonline.com/organizations/": {
tenant_discovery_endpoint: "https://login.microsoftonline.com/organizations/v2.0/.well-known/openid-configuration",
"api-version": "1.1",
metadata: [
{
preferred_network: "login.microsoftonline.com",
preferred_cache: "login.windows.net",
aliases: [
"login.microsoftonline.com",
"login.windows.net",
"login.microsoft.com",
"sts.windows.net",
],
},
{
preferred_network: "login.partner.microsoftonline.cn",
preferred_cache: "login.partner.microsoftonline.cn",
aliases: [
"login.partner.microsoftonline.cn",
"login.chinacloudapi.cn",
],
},
{
preferred_network: "login.microsoftonline.de",
preferred_cache: "login.microsoftonline.de",
aliases: ["login.microsoftonline.de"],
},
{
preferred_network: "login.microsoftonline.us",
preferred_cache: "login.microsoftonline.us",
aliases: [
"login.microsoftonline.us",
"login.usgovcloudapi.net",
],
},
{
preferred_network: "login-us.microsoftonline.com",
preferred_cache: "login-us.microsoftonline.com",
aliases: ["login-us.microsoftonline.com"],
},
],
},
"https://login.chinacloudapi.cn/organizations/": {
tenant_discovery_endpoint: "https://login.chinacloudapi.cn/organizations/v2.0/.well-known/openid-configuration",
"api-version": "1.1",
metadata: [
{
preferred_network: "login.microsoftonline.com",
preferred_cache: "login.windows.net",
aliases: [
"login.microsoftonline.com",
"login.windows.net",
"login.microsoft.com",
"sts.windows.net",
],
},
{
preferred_network: "login.partner.microsoftonline.cn",
preferred_cache: "login.partner.microsoftonline.cn",
aliases: [
"login.partner.microsoftonline.cn",
"login.chinacloudapi.cn",
],
},
{
preferred_network: "login.microsoftonline.de",
preferred_cache: "login.microsoftonline.de",
aliases: ["login.microsoftonline.de"],
},
{
preferred_network: "login.microsoftonline.us",
preferred_cache: "login.microsoftonline.us",
aliases: [
"login.microsoftonline.us",
"login.usgovcloudapi.net",
],
},
{
preferred_network: "login-us.microsoftonline.com",
preferred_cache: "login-us.microsoftonline.com",
aliases: ["login-us.microsoftonline.com"],
},
],
},
"https://login.microsoftonline.us/organizations/": {
tenant_discovery_endpoint: "https://login.microsoftonline.us/organizations/v2.0/.well-known/openid-configuration",
"api-version": "1.1",
metadata: [
{
preferred_network: "login.microsoftonline.com",
preferred_cache: "login.windows.net",
aliases: [
"login.microsoftonline.com",
"login.windows.net",
"login.microsoft.com",
"sts.windows.net",
],
},
{
preferred_network: "login.partner.microsoftonline.cn",
preferred_cache: "login.partner.microsoftonline.cn",
aliases: [
"login.partner.microsoftonline.cn",
"login.chinacloudapi.cn",
],
},
{
preferred_network: "login.microsoftonline.de",
preferred_cache: "login.microsoftonline.de",
aliases: ["login.microsoftonline.de"],
},
{
preferred_network: "login.microsoftonline.us",
preferred_cache: "login.microsoftonline.us",
aliases: [
"login.microsoftonline.us",
"login.usgovcloudapi.net",
],
},
{
preferred_network: "login-us.microsoftonline.com",
preferred_cache: "login-us.microsoftonline.com",
aliases: ["login-us.microsoftonline.com"],
},
],
},
},
};
const EndpointMetadata = rawMetdataJSON.endpointMetadata;
const InstanceDiscoveryMetadata = rawMetdataJSON.instanceDiscoveryMetadata;
export { EndpointMetadata, InstanceDiscoveryMetadata, rawMetdataJSON };
//# sourceMappingURL=AuthorityMetadata.js.map
import { ProtocolMode } from "./ProtocolMode";
import { AzureRegionConfiguration } from "./AzureRegionConfiguration";
export declare type AuthorityOptions = {
export type AuthorityOptions = {
protocolMode: ProtocolMode;

@@ -5,0 +5,0 @@ knownAuthorities: Array<string>;

@@ -1,2 +0,2 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';

@@ -3,0 +3,0 @@ /*

@@ -1,2 +0,2 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';

@@ -3,0 +3,0 @@ /*

@@ -1,2 +0,2 @@

export declare type AzureRegion = string;
export type AzureRegion = string;
//# sourceMappingURL=AzureRegion.d.ts.map
import { AzureRegion } from "./AzureRegion";
export declare type AzureRegionConfiguration = {
export type AzureRegionConfiguration = {
azureRegion?: AzureRegion;

@@ -4,0 +4,0 @@ environmentRegion: string | undefined;

@@ -1,2 +0,2 @@

export declare type CloudDiscoveryMetadata = {
export type CloudDiscoveryMetadata = {
preferred_network: string;

@@ -3,0 +3,0 @@ preferred_cache: string;

/**
* The OpenID Configuration Endpoint Response type. Used by the authority class to get relevant OAuth endpoints.
*/
export declare type CloudInstanceDiscoveryErrorResponse = {
export type CloudInstanceDiscoveryErrorResponse = {
error: String;

@@ -6,0 +6,0 @@ error_description: String;

@@ -1,2 +0,2 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';

@@ -3,0 +3,0 @@ /*

@@ -5,3 +5,3 @@ import { CloudDiscoveryMetadata } from "./CloudDiscoveryMetadata";

*/
export declare type CloudInstanceDiscoveryResponse = {
export type CloudInstanceDiscoveryResponse = {
tenant_discovery_endpoint: string;

@@ -8,0 +8,0 @@ metadata: Array<CloudDiscoveryMetadata>;

@@ -1,2 +0,2 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';

@@ -3,0 +3,0 @@ /*

@@ -1,2 +0,2 @@

export declare type ImdsOptions = {
export type ImdsOptions = {
headers?: {

@@ -3,0 +3,0 @@ Metadata: string;

/**
* Tenant Discovery Response which contains the relevant OAuth endpoints and data needed for authentication and authorization.
*/
export declare type OpenIdConfigResponse = {
export type OpenIdConfigResponse = {
authorization_endpoint: string;

@@ -6,0 +6,0 @@ token_endpoint: string;

@@ -1,2 +0,2 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';

@@ -3,0 +3,0 @@ /*

@@ -1,2 +0,2 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';

@@ -3,0 +3,0 @@ /*

@@ -1,5 +0,4 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';
import { __awaiter, __generator } from '../_virtual/_tslib.js';
import { RegionDiscoverySources, ResponseCodes, Constants } from '../utils/Constants.js';
import { Constants, ResponseCodes, RegionDiscoverySources } from '../utils/Constants.js';
import { PerformanceEvents } from '../telemetry/performance/PerformanceEvent.js';

@@ -11,4 +10,4 @@

*/
var RegionDiscovery = /** @class */ (function () {
function RegionDiscovery(networkInterface, performanceClient, correlationId) {
class RegionDiscovery {
constructor(networkInterface, performanceClient, correlationId) {
this.networkInterface = networkInterface;

@@ -23,61 +22,56 @@ this.performanceClient = performanceClient;

*/
RegionDiscovery.prototype.detectRegion = function (environmentRegion, regionDiscoveryMetadata) {
var _a, _b, _c, _d;
return __awaiter(this, void 0, void 0, function () {
var autodetectedRegionName, options, localIMDSVersionResponse, currentIMDSVersion, currentIMDSVersionResponse;
return __generator(this, function (_e) {
switch (_e.label) {
case 0:
(_a = this.performanceClient) === null || _a === void 0 ? void 0 : _a.addQueueMeasurement(PerformanceEvents.RegionDiscoveryDetectRegion, this.correlationId);
autodetectedRegionName = environmentRegion;
if (!!autodetectedRegionName) return [3 /*break*/, 8];
options = RegionDiscovery.IMDS_OPTIONS;
_e.label = 1;
case 1:
_e.trys.push([1, 6, , 7]);
(_b = this.performanceClient) === null || _b === void 0 ? void 0 : _b.setPreQueueTime(PerformanceEvents.RegionDiscoveryGetRegionFromIMDS, this.correlationId);
return [4 /*yield*/, this.getRegionFromIMDS(Constants.IMDS_VERSION, options)];
case 2:
localIMDSVersionResponse = _e.sent();
if (localIMDSVersionResponse.status === ResponseCodes.httpSuccess) {
autodetectedRegionName = localIMDSVersionResponse.body;
regionDiscoveryMetadata.region_source = RegionDiscoverySources.IMDS;
}
if (!(localIMDSVersionResponse.status === ResponseCodes.httpBadRequest)) return [3 /*break*/, 5];
(_c = this.performanceClient) === null || _c === void 0 ? void 0 : _c.setPreQueueTime(PerformanceEvents.RegionDiscoveryGetCurrentVersion, this.correlationId);
return [4 /*yield*/, this.getCurrentVersion(options)];
case 3:
currentIMDSVersion = _e.sent();
if (!currentIMDSVersion) {
regionDiscoveryMetadata.region_source = RegionDiscoverySources.FAILED_AUTO_DETECTION;
return [2 /*return*/, null];
}
(_d = this.performanceClient) === null || _d === void 0 ? void 0 : _d.setPreQueueTime(PerformanceEvents.RegionDiscoveryGetRegionFromIMDS, this.correlationId);
return [4 /*yield*/, this.getRegionFromIMDS(currentIMDSVersion, options)];
case 4:
currentIMDSVersionResponse = _e.sent();
if (currentIMDSVersionResponse.status === ResponseCodes.httpSuccess) {
autodetectedRegionName = currentIMDSVersionResponse.body;
regionDiscoveryMetadata.region_source = RegionDiscoverySources.IMDS;
}
_e.label = 5;
case 5: return [3 /*break*/, 7];
case 6:
_e.sent();
regionDiscoveryMetadata.region_source = RegionDiscoverySources.FAILED_AUTO_DETECTION;
return [2 /*return*/, null];
case 7: return [3 /*break*/, 9];
case 8:
regionDiscoveryMetadata.region_source = RegionDiscoverySources.ENVIRONMENT_VARIABLE;
_e.label = 9;
case 9:
// If no region was auto detected from the environment or from the IMDS endpoint, mark the attempt as a FAILED_AUTO_DETECTION
if (!autodetectedRegionName) {
regionDiscoveryMetadata.region_source = RegionDiscoverySources.FAILED_AUTO_DETECTION;
}
return [2 /*return*/, autodetectedRegionName || null];
async detectRegion(environmentRegion, regionDiscoveryMetadata) {
this.performanceClient?.addQueueMeasurement(PerformanceEvents.RegionDiscoveryDetectRegion, this.correlationId);
// Initialize auto detected region with the region from the envrionment
let autodetectedRegionName = environmentRegion;
// Check if a region was detected from the environment, if not, attempt to get the region from IMDS
if (!autodetectedRegionName) {
const options = RegionDiscovery.IMDS_OPTIONS;
try {
this.performanceClient?.setPreQueueTime(PerformanceEvents.RegionDiscoveryGetRegionFromIMDS, this.correlationId);
const localIMDSVersionResponse = await this.getRegionFromIMDS(Constants.IMDS_VERSION, options);
if (localIMDSVersionResponse.status ===
ResponseCodes.httpSuccess) {
autodetectedRegionName = localIMDSVersionResponse.body;
regionDiscoveryMetadata.region_source =
RegionDiscoverySources.IMDS;
}
});
});
};
// If the response using the local IMDS version failed, try to fetch the current version of IMDS and retry.
if (localIMDSVersionResponse.status ===
ResponseCodes.httpBadRequest) {
this.performanceClient?.setPreQueueTime(PerformanceEvents.RegionDiscoveryGetCurrentVersion, this.correlationId);
const currentIMDSVersion = await this.getCurrentVersion(options);
if (!currentIMDSVersion) {
regionDiscoveryMetadata.region_source =
RegionDiscoverySources.FAILED_AUTO_DETECTION;
return null;
}
this.performanceClient?.setPreQueueTime(PerformanceEvents.RegionDiscoveryGetRegionFromIMDS, this.correlationId);
const currentIMDSVersionResponse = await this.getRegionFromIMDS(currentIMDSVersion, options);
if (currentIMDSVersionResponse.status ===
ResponseCodes.httpSuccess) {
autodetectedRegionName =
currentIMDSVersionResponse.body;
regionDiscoveryMetadata.region_source =
RegionDiscoverySources.IMDS;
}
}
}
catch (e) {
regionDiscoveryMetadata.region_source =
RegionDiscoverySources.FAILED_AUTO_DETECTION;
return null;
}
}
else {
regionDiscoveryMetadata.region_source =
RegionDiscoverySources.ENVIRONMENT_VARIABLE;
}
// If no region was auto detected from the environment or from the IMDS endpoint, mark the attempt as a FAILED_AUTO_DETECTION
if (!autodetectedRegionName) {
regionDiscoveryMetadata.region_source =
RegionDiscoverySources.FAILED_AUTO_DETECTION;
}
return autodetectedRegionName || null;
}
/**

@@ -89,11 +83,6 @@ * Make the call to the IMDS endpoint

*/
RegionDiscovery.prototype.getRegionFromIMDS = function (version, options) {
var _a;
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_b) {
(_a = this.performanceClient) === null || _a === void 0 ? void 0 : _a.addQueueMeasurement(PerformanceEvents.RegionDiscoveryGetRegionFromIMDS, this.correlationId);
return [2 /*return*/, this.networkInterface.sendGetRequestAsync(Constants.IMDS_ENDPOINT + "?api-version=" + version + "&format=text", options, Constants.IMDS_TIMEOUT)];
});
});
};
async getRegionFromIMDS(version, options) {
this.performanceClient?.addQueueMeasurement(PerformanceEvents.RegionDiscoveryGetRegionFromIMDS, this.correlationId);
return this.networkInterface.sendGetRequestAsync(`${Constants.IMDS_ENDPOINT}?api-version=${version}&format=text`, options, Constants.IMDS_TIMEOUT);
}
/**

@@ -104,39 +93,28 @@ * Get the most recent version of the IMDS endpoint available

*/
RegionDiscovery.prototype.getCurrentVersion = function (options) {
var _a;
return __awaiter(this, void 0, void 0, function () {
var response;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
(_a = this.performanceClient) === null || _a === void 0 ? void 0 : _a.addQueueMeasurement(PerformanceEvents.RegionDiscoveryGetCurrentVersion, this.correlationId);
_b.label = 1;
case 1:
_b.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.networkInterface.sendGetRequestAsync(Constants.IMDS_ENDPOINT + "?format=json", options)];
case 2:
response = _b.sent();
// When IMDS endpoint is called without the api version query param, bad request response comes back with latest version.
if (response.status === ResponseCodes.httpBadRequest && response.body && response.body["newest-versions"] && response.body["newest-versions"].length > 0) {
return [2 /*return*/, response.body["newest-versions"][0]];
}
return [2 /*return*/, null];
case 3:
_b.sent();
return [2 /*return*/, null];
case 4: return [2 /*return*/];
}
});
});
};
// Options for the IMDS endpoint request
RegionDiscovery.IMDS_OPTIONS = {
headers: {
Metadata: "true",
},
};
return RegionDiscovery;
}());
async getCurrentVersion(options) {
this.performanceClient?.addQueueMeasurement(PerformanceEvents.RegionDiscoveryGetCurrentVersion, this.correlationId);
try {
const response = await this.networkInterface.sendGetRequestAsync(`${Constants.IMDS_ENDPOINT}?format=json`, options);
// When IMDS endpoint is called without the api version query param, bad request response comes back with latest version.
if (response.status === ResponseCodes.httpBadRequest &&
response.body &&
response.body["newest-versions"] &&
response.body["newest-versions"].length > 0) {
return response.body["newest-versions"][0];
}
return null;
}
catch (e) {
return null;
}
}
}
// Options for the IMDS endpoint request
RegionDiscovery.IMDS_OPTIONS = {
headers: {
Metadata: "true",
},
};
export { RegionDiscovery };
//# sourceMappingURL=RegionDiscovery.js.map
import { RegionDiscoveryOutcomes, RegionDiscoverySources } from "../utils/Constants";
export declare type RegionDiscoveryMetadata = {
export type RegionDiscoveryMetadata = {
region_used?: string;

@@ -4,0 +4,0 @@ region_source?: RegionDiscoverySources;

@@ -1,4 +0,3 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';
import { __awaiter, __generator, __assign, __extends } from '../_virtual/_tslib.js';
import { Separators, CredentialType, AuthenticationScheme, THE_FAMILY_ID, APP_METADATA, AUTHORITY_METADATA_CONSTANTS } from '../utils/Constants.js';

@@ -19,4 +18,4 @@ import { ScopeSet } from '../request/ScopeSet.js';

*/
var CacheManager = /** @class */ (function () {
function CacheManager(clientId, cryptoImpl, logger) {
class CacheManager {
constructor(clientId, cryptoImpl, logger) {
this.clientId = clientId;

@@ -29,10 +28,9 @@ this.cryptoImpl = cryptoImpl;

*/
CacheManager.prototype.getAllAccounts = function () {
var _this = this;
var allAccountKeys = this.getAccountKeys();
getAllAccounts() {
const allAccountKeys = this.getAccountKeys();
if (allAccountKeys.length < 1) {
return [];
}
var accountEntities = allAccountKeys.reduce(function (accounts, key) {
var entity = _this.getAccount(key);
const accountEntities = allAccountKeys.reduce((accounts, key) => {
const entity = this.getAccount(key);
if (!entity) {

@@ -48,13 +46,13 @@ return accounts;

else {
var allAccounts = accountEntities.map(function (accountEntity) {
return _this.getAccountInfoFromEntity(accountEntity);
const allAccounts = accountEntities.map((accountEntity) => {
return this.getAccountInfoFromEntity(accountEntity);
});
return allAccounts;
}
};
}
/**
* Gets accountInfo object based on provided filters
*/
CacheManager.prototype.getAccountInfoFilteredBy = function (accountFilter) {
var allAccounts = this.getAccountsFilteredBy(accountFilter);
getAccountInfoFilteredBy(accountFilter) {
const allAccounts = this.getAccountsFilteredBy(accountFilter);
if (allAccounts.length > 0) {

@@ -66,6 +64,6 @@ return this.getAccountInfoFromEntity(allAccounts[0]);

}
};
CacheManager.prototype.getAccountInfoFromEntity = function (accountEntity) {
var accountInfo = accountEntity.getAccountInfo();
var idToken = this.getIdToken(accountInfo);
}
getAccountInfoFromEntity(accountEntity) {
const accountInfo = accountEntity.getAccountInfo();
const idToken = this.getIdToken(accountInfo);
if (idToken) {

@@ -76,3 +74,3 @@ accountInfo.idToken = idToken.secret;

return accountInfo;
};
}
/**

@@ -82,33 +80,22 @@ * saves a cache record

*/
CacheManager.prototype.saveCacheRecord = function (cacheRecord) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!cacheRecord) {
throw ClientAuthError.createNullOrUndefinedCacheRecord();
}
if (!!cacheRecord.account) {
this.setAccount(cacheRecord.account);
}
if (!!cacheRecord.idToken) {
this.setIdTokenCredential(cacheRecord.idToken);
}
if (!!!cacheRecord.accessToken) return [3 /*break*/, 2];
return [4 /*yield*/, this.saveAccessToken(cacheRecord.accessToken)];
case 1:
_a.sent();
_a.label = 2;
case 2:
if (!!cacheRecord.refreshToken) {
this.setRefreshTokenCredential(cacheRecord.refreshToken);
}
if (!!cacheRecord.appMetadata) {
this.setAppMetadata(cacheRecord.appMetadata);
}
return [2 /*return*/];
}
});
});
};
async saveCacheRecord(cacheRecord) {
if (!cacheRecord) {
throw ClientAuthError.createNullOrUndefinedCacheRecord();
}
if (!!cacheRecord.account) {
this.setAccount(cacheRecord.account);
}
if (!!cacheRecord.idToken) {
this.setIdTokenCredential(cacheRecord.idToken);
}
if (!!cacheRecord.accessToken) {
await this.saveAccessToken(cacheRecord.accessToken);
}
if (!!cacheRecord.refreshToken) {
this.setRefreshTokenCredential(cacheRecord.refreshToken);
}
if (!!cacheRecord.appMetadata) {
this.setAppMetadata(cacheRecord.appMetadata);
}
}
/**

@@ -118,42 +105,31 @@ * saves access token credential

*/
CacheManager.prototype.saveAccessToken = function (credential) {
return __awaiter(this, void 0, void 0, function () {
var accessTokenFilter, tokenKeys, currentScopes, removedAccessTokens;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
accessTokenFilter = {
clientId: credential.clientId,
credentialType: credential.credentialType,
environment: credential.environment,
homeAccountId: credential.homeAccountId,
realm: credential.realm,
tokenType: credential.tokenType,
requestedClaimsHash: credential.requestedClaimsHash
};
tokenKeys = this.getTokenKeys();
currentScopes = ScopeSet.fromString(credential.target);
removedAccessTokens = [];
tokenKeys.accessToken.forEach(function (key) {
if (!_this.accessTokenKeyMatchesFilter(key, accessTokenFilter, false)) {
return;
}
var tokenEntity = _this.getAccessTokenCredential(key);
if (tokenEntity && _this.credentialMatchesFilter(tokenEntity, accessTokenFilter)) {
var tokenScopeSet = ScopeSet.fromString(tokenEntity.target);
if (tokenScopeSet.intersectingScopeSets(currentScopes)) {
removedAccessTokens.push(_this.removeAccessToken(key));
}
}
});
return [4 /*yield*/, Promise.all(removedAccessTokens)];
case 1:
_a.sent();
this.setAccessTokenCredential(credential);
return [2 /*return*/];
async saveAccessToken(credential) {
const accessTokenFilter = {
clientId: credential.clientId,
credentialType: credential.credentialType,
environment: credential.environment,
homeAccountId: credential.homeAccountId,
realm: credential.realm,
tokenType: credential.tokenType,
requestedClaimsHash: credential.requestedClaimsHash,
};
const tokenKeys = this.getTokenKeys();
const currentScopes = ScopeSet.fromString(credential.target);
const removedAccessTokens = [];
tokenKeys.accessToken.forEach((key) => {
if (!this.accessTokenKeyMatchesFilter(key, accessTokenFilter, false)) {
return;
}
const tokenEntity = this.getAccessTokenCredential(key);
if (tokenEntity &&
this.credentialMatchesFilter(tokenEntity, accessTokenFilter)) {
const tokenScopeSet = ScopeSet.fromString(tokenEntity.target);
if (tokenScopeSet.intersectingScopeSets(currentScopes)) {
removedAccessTokens.push(this.removeAccessToken(key));
}
});
}
});
};
await Promise.all(removedAccessTokens);
this.setAccessTokenCredential(credential);
}
/**

@@ -166,31 +142,36 @@ * retrieve accounts matching all provided filters; if no filter is set, get all accounts

*/
CacheManager.prototype.getAccountsFilteredBy = function (accountFilter) {
var _this = this;
var allAccountKeys = this.getAccountKeys();
var matchingAccounts = [];
allAccountKeys.forEach(function (cacheKey) {
if (!_this.isAccountKey(cacheKey, accountFilter.homeAccountId, accountFilter.realm)) {
getAccountsFilteredBy(accountFilter) {
const allAccountKeys = this.getAccountKeys();
const matchingAccounts = [];
allAccountKeys.forEach((cacheKey) => {
if (!this.isAccountKey(cacheKey, accountFilter.homeAccountId, accountFilter.realm)) {
// Don't parse value if the key doesn't match the account filters
return;
}
var entity = _this.getAccount(cacheKey);
const entity = this.getAccount(cacheKey);
if (!entity) {
return;
}
if (!!accountFilter.homeAccountId && !_this.matchHomeAccountId(entity, accountFilter.homeAccountId)) {
if (!!accountFilter.homeAccountId &&
!this.matchHomeAccountId(entity, accountFilter.homeAccountId)) {
return;
}
if (!!accountFilter.localAccountId && !_this.matchLocalAccountId(entity, accountFilter.localAccountId)) {
if (!!accountFilter.localAccountId &&
!this.matchLocalAccountId(entity, accountFilter.localAccountId)) {
return;
}
if (!!accountFilter.username && !_this.matchUsername(entity, accountFilter.username)) {
if (!!accountFilter.username &&
!this.matchUsername(entity, accountFilter.username)) {
return;
}
if (!!accountFilter.environment && !_this.matchEnvironment(entity, accountFilter.environment)) {
if (!!accountFilter.environment &&
!this.matchEnvironment(entity, accountFilter.environment)) {
return;
}
if (!!accountFilter.realm && !_this.matchRealm(entity, accountFilter.realm)) {
if (!!accountFilter.realm &&
!this.matchRealm(entity, accountFilter.realm)) {
return;
}
if (!!accountFilter.nativeAccountId && !_this.matchNativeAccountId(entity, accountFilter.nativeAccountId)) {
if (!!accountFilter.nativeAccountId &&
!this.matchNativeAccountId(entity, accountFilter.nativeAccountId)) {
return;

@@ -201,3 +182,3 @@ }

return matchingAccounts;
};
}
/**

@@ -210,3 +191,3 @@ * Returns true if the given key matches our account key schema. Also matches homeAccountId and/or tenantId if provided

*/
CacheManager.prototype.isAccountKey = function (key, homeAccountId, tenantId) {
isAccountKey(key, homeAccountId, tenantId) {
if (key.split(Separators.CACHE_KEY_SEPARATOR).length < 3) {

@@ -216,3 +197,4 @@ // Account cache keys contain 3 items separated by '-' (each item may also contain '-')

}
if (homeAccountId && !key.toLowerCase().includes(homeAccountId.toLowerCase())) {
if (homeAccountId &&
!key.toLowerCase().includes(homeAccountId.toLowerCase())) {
return false;

@@ -225,3 +207,3 @@ }

return true;
};
}
/**

@@ -231,3 +213,3 @@ * Returns true if the given key matches our credential key schema.

*/
CacheManager.prototype.isCredentialKey = function (key) {
isCredentialKey(key) {
if (key.split(Separators.CACHE_KEY_SEPARATOR).length < 6) {

@@ -237,15 +219,20 @@ // Credential cache keys contain 6 items separated by '-' (each item may also contain '-')

}
var lowerCaseKey = key.toLowerCase();
const lowerCaseKey = key.toLowerCase();
// Credential keys must indicate what credential type they represent
if (lowerCaseKey.indexOf(CredentialType.ID_TOKEN.toLowerCase()) === -1 &&
lowerCaseKey.indexOf(CredentialType.ACCESS_TOKEN.toLowerCase()) === -1 &&
if (lowerCaseKey.indexOf(CredentialType.ID_TOKEN.toLowerCase()) ===
-1 &&
lowerCaseKey.indexOf(CredentialType.ACCESS_TOKEN.toLowerCase()) ===
-1 &&
lowerCaseKey.indexOf(CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME.toLowerCase()) === -1 &&
lowerCaseKey.indexOf(CredentialType.REFRESH_TOKEN.toLowerCase()) === -1) {
lowerCaseKey.indexOf(CredentialType.REFRESH_TOKEN.toLowerCase()) ===
-1) {
return false;
}
if (lowerCaseKey.indexOf(CredentialType.REFRESH_TOKEN.toLowerCase()) > -1) {
if (lowerCaseKey.indexOf(CredentialType.REFRESH_TOKEN.toLowerCase()) >
-1) {
// Refresh tokens must contain the client id or family id
var clientIdValidation = "" + CredentialType.REFRESH_TOKEN + Separators.CACHE_KEY_SEPARATOR + this.clientId + Separators.CACHE_KEY_SEPARATOR;
var familyIdValidation = "" + CredentialType.REFRESH_TOKEN + Separators.CACHE_KEY_SEPARATOR + THE_FAMILY_ID + Separators.CACHE_KEY_SEPARATOR;
if (lowerCaseKey.indexOf(clientIdValidation.toLowerCase()) === -1 && lowerCaseKey.indexOf(familyIdValidation.toLowerCase()) === -1) {
const clientIdValidation = `${CredentialType.REFRESH_TOKEN}${Separators.CACHE_KEY_SEPARATOR}${this.clientId}${Separators.CACHE_KEY_SEPARATOR}`;
const familyIdValidation = `${CredentialType.REFRESH_TOKEN}${Separators.CACHE_KEY_SEPARATOR}${THE_FAMILY_ID}${Separators.CACHE_KEY_SEPARATOR}`;
if (lowerCaseKey.indexOf(clientIdValidation.toLowerCase()) === -1 &&
lowerCaseKey.indexOf(familyIdValidation.toLowerCase()) === -1) {
return false;

@@ -259,3 +246,3 @@ }

return true;
};
}
/**

@@ -267,7 +254,8 @@ * Returns whether or not the given credential entity matches the filter

*/
CacheManager.prototype.credentialMatchesFilter = function (entity, filter) {
credentialMatchesFilter(entity, filter) {
if (!!filter.clientId && !this.matchClientId(entity, filter.clientId)) {
return false;
}
if (!!filter.userAssertionHash && !this.matchUserAssertionHash(entity, filter.userAssertionHash)) {
if (!!filter.userAssertionHash &&
!this.matchUserAssertionHash(entity, filter.userAssertionHash)) {
return false;

@@ -279,6 +267,8 @@ }

*/
if ((typeof filter.homeAccountId === "string") && !this.matchHomeAccountId(entity, filter.homeAccountId)) {
if (typeof filter.homeAccountId === "string" &&
!this.matchHomeAccountId(entity, filter.homeAccountId)) {
return false;
}
if (!!filter.environment && !this.matchEnvironment(entity, filter.environment)) {
if (!!filter.environment &&
!this.matchEnvironment(entity, filter.environment)) {
return false;

@@ -289,3 +279,4 @@ }

}
if (!!filter.credentialType && !this.matchCredentialType(entity, filter.credentialType)) {
if (!!filter.credentialType &&
!this.matchCredentialType(entity, filter.credentialType)) {
return false;

@@ -311,4 +302,6 @@ }

// Access Token with Auth Scheme specific matching
if (entity.credentialType === CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME) {
if (!!filter.tokenType && !this.matchTokenType(entity, filter.tokenType)) {
if (entity.credentialType ===
CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME) {
if (!!filter.tokenType &&
!this.matchTokenType(entity, filter.tokenType)) {
return false;

@@ -324,3 +317,3 @@ }

return true;
};
}
/**

@@ -330,5 +323,5 @@ * retrieve appMetadata matching all provided filters; if no filter is set, get all appMetadata

*/
CacheManager.prototype.getAppMetadataFilteredBy = function (filter) {
getAppMetadataFilteredBy(filter) {
return this.getAppMetadataFilteredByInternal(filter.environment, filter.clientId);
};
}
/**

@@ -339,20 +332,19 @@ * Support function to help match appMetadata

*/
CacheManager.prototype.getAppMetadataFilteredByInternal = function (environment, clientId) {
var _this = this;
var allCacheKeys = this.getKeys();
var matchingAppMetadata = {};
allCacheKeys.forEach(function (cacheKey) {
getAppMetadataFilteredByInternal(environment, clientId) {
const allCacheKeys = this.getKeys();
const matchingAppMetadata = {};
allCacheKeys.forEach((cacheKey) => {
// don't parse any non-appMetadata type cache entities
if (!_this.isAppMetadata(cacheKey)) {
if (!this.isAppMetadata(cacheKey)) {
return;
}
// Attempt retrieval
var entity = _this.getAppMetadata(cacheKey);
const entity = this.getAppMetadata(cacheKey);
if (!entity) {
return;
}
if (!!environment && !_this.matchEnvironment(entity, environment)) {
if (!!environment && !this.matchEnvironment(entity, environment)) {
return;
}
if (!!clientId && !_this.matchClientId(entity, clientId)) {
if (!!clientId && !this.matchClientId(entity, clientId)) {
return;

@@ -363,3 +355,3 @@ }

return matchingAppMetadata;
};
}
/**

@@ -369,13 +361,13 @@ * retrieve authorityMetadata that contains a matching alias

*/
CacheManager.prototype.getAuthorityMetadataByAlias = function (host) {
var _this = this;
var allCacheKeys = this.getAuthorityMetadataKeys();
var matchedEntity = null;
allCacheKeys.forEach(function (cacheKey) {
getAuthorityMetadataByAlias(host) {
const allCacheKeys = this.getAuthorityMetadataKeys();
let matchedEntity = null;
allCacheKeys.forEach((cacheKey) => {
// don't parse any non-authorityMetadata type cache entities
if (!_this.isAuthorityMetadata(cacheKey) || cacheKey.indexOf(_this.clientId) === -1) {
if (!this.isAuthorityMetadata(cacheKey) ||
cacheKey.indexOf(this.clientId) === -1) {
return;
}
// Attempt retrieval
var entity = _this.getAuthorityMetadata(cacheKey);
const entity = this.getAuthorityMetadata(cacheKey);
if (!entity) {

@@ -390,26 +382,14 @@ return;

return matchedEntity;
};
}
/**
* Removes all accounts and related tokens from cache.
*/
CacheManager.prototype.removeAllAccounts = function () {
return __awaiter(this, void 0, void 0, function () {
var allAccountKeys, removedAccounts;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
allAccountKeys = this.getAccountKeys();
removedAccounts = [];
allAccountKeys.forEach(function (cacheKey) {
removedAccounts.push(_this.removeAccount(cacheKey));
});
return [4 /*yield*/, Promise.all(removedAccounts)];
case 1:
_a.sent();
return [2 /*return*/];
}
});
async removeAllAccounts() {
const allAccountKeys = this.getAccountKeys();
const removedAccounts = [];
allAccountKeys.forEach((cacheKey) => {
removedAccounts.push(this.removeAccount(cacheKey));
});
};
await Promise.all(removedAccounts);
}
/**

@@ -419,21 +399,10 @@ * Removes the account and related tokens for a given account key

*/
CacheManager.prototype.removeAccount = function (accountKey) {
return __awaiter(this, void 0, void 0, function () {
var account;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
account = this.getAccount(accountKey);
if (!account) {
throw ClientAuthError.createNoAccountFoundError();
}
return [4 /*yield*/, this.removeAccountContext(account)];
case 1:
_a.sent();
this.removeItem(accountKey);
return [2 /*return*/];
}
});
});
};
async removeAccount(accountKey) {
const account = this.getAccount(accountKey);
if (!account) {
return;
}
await this.removeAccountContext(account);
this.removeItem(accountKey);
}
/**

@@ -443,35 +412,23 @@ * Removes credentials associated with the provided account

*/
CacheManager.prototype.removeAccountContext = function (account) {
return __awaiter(this, void 0, void 0, function () {
var allTokenKeys, accountId, removedCredentials;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
allTokenKeys = this.getTokenKeys();
accountId = account.generateAccountId();
removedCredentials = [];
allTokenKeys.idToken.forEach(function (key) {
if (key.indexOf(accountId) === 0) {
_this.removeIdToken(key);
}
});
allTokenKeys.accessToken.forEach(function (key) {
if (key.indexOf(accountId) === 0) {
removedCredentials.push(_this.removeAccessToken(key));
}
});
allTokenKeys.refreshToken.forEach(function (key) {
if (key.indexOf(accountId) === 0) {
_this.removeRefreshToken(key);
}
});
return [4 /*yield*/, Promise.all(removedCredentials)];
case 1:
_a.sent();
return [2 /*return*/];
}
});
async removeAccountContext(account) {
const allTokenKeys = this.getTokenKeys();
const accountId = account.generateAccountId();
const removedCredentials = [];
allTokenKeys.idToken.forEach((key) => {
if (key.indexOf(accountId) === 0) {
this.removeIdToken(key);
}
});
};
allTokenKeys.accessToken.forEach((key) => {
if (key.indexOf(accountId) === 0) {
removedCredentials.push(this.removeAccessToken(key));
}
});
allTokenKeys.refreshToken.forEach((key) => {
if (key.indexOf(accountId) === 0) {
this.removeRefreshToken(key);
}
});
await Promise.all(removedCredentials);
}
/**

@@ -481,45 +438,37 @@ * returns a boolean if the given credential is removed

*/
CacheManager.prototype.removeAccessToken = function (key) {
return __awaiter(this, void 0, void 0, function () {
var credential, accessTokenWithAuthSchemeEntity, kid;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
credential = this.getAccessTokenCredential(key);
if (!credential) {
return [2 /*return*/];
}
if (!(credential.credentialType.toLowerCase() === CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME.toLowerCase())) return [3 /*break*/, 4];
if (!(credential.tokenType === AuthenticationScheme.POP)) return [3 /*break*/, 4];
accessTokenWithAuthSchemeEntity = credential;
kid = accessTokenWithAuthSchemeEntity.keyId;
if (!kid) return [3 /*break*/, 4];
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.cryptoImpl.removeTokenBindingKey(kid)];
case 2:
_a.sent();
return [3 /*break*/, 4];
case 3:
_a.sent();
async removeAccessToken(key) {
const credential = this.getAccessTokenCredential(key);
if (!credential) {
return;
}
// Remove Token Binding Key from key store for PoP Tokens Credentials
if (credential.credentialType.toLowerCase() ===
CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME.toLowerCase()) {
if (credential.tokenType === AuthenticationScheme.POP) {
const accessTokenWithAuthSchemeEntity = credential;
const kid = accessTokenWithAuthSchemeEntity.keyId;
if (kid) {
try {
await this.cryptoImpl.removeTokenBindingKey(kid);
}
catch (error) {
throw ClientAuthError.createBindingKeyNotRemovedError();
case 4: return [2 /*return*/, this.removeItem(key)];
}
}
});
});
};
}
}
return this.removeItem(key);
}
/**
* Removes all app metadata objects from cache.
*/
CacheManager.prototype.removeAppMetadata = function () {
var _this = this;
var allCacheKeys = this.getKeys();
allCacheKeys.forEach(function (cacheKey) {
if (_this.isAppMetadata(cacheKey)) {
_this.removeItem(cacheKey);
removeAppMetadata() {
const allCacheKeys = this.getKeys();
allCacheKeys.forEach((cacheKey) => {
if (this.isAppMetadata(cacheKey)) {
this.removeItem(cacheKey);
}
});
return true;
};
}
/**

@@ -533,9 +482,9 @@ * Retrieve the cached credentials into a cacherecord

*/
CacheManager.prototype.readCacheRecord = function (account, request, environment) {
var tokenKeys = this.getTokenKeys();
var cachedAccount = this.readAccountFromCache(account);
var cachedIdToken = this.getIdToken(account, tokenKeys);
var cachedAccessToken = this.getAccessToken(account, request, tokenKeys);
var cachedRefreshToken = this.getRefreshToken(account, false, tokenKeys);
var cachedAppMetadata = this.readAppMetadataFromCache(environment);
readCacheRecord(account, request, environment) {
const tokenKeys = this.getTokenKeys();
const cachedAccount = this.readAccountFromCache(account);
const cachedIdToken = this.getIdToken(account, tokenKeys);
const cachedAccessToken = this.getAccessToken(account, request, tokenKeys);
const cachedRefreshToken = this.getRefreshToken(account, false, tokenKeys);
const cachedAppMetadata = this.readAppMetadataFromCache(environment);
if (cachedAccount && cachedIdToken) {

@@ -551,3 +500,3 @@ cachedAccount.idTokenClaims = new AuthToken(cachedIdToken.secret, this.cryptoImpl).claims;

};
};
}
/**

@@ -557,6 +506,6 @@ * Retrieve AccountEntity from cache

*/
CacheManager.prototype.readAccountFromCache = function (account) {
var accountKey = AccountEntity.generateAccountCacheKey(account);
readAccountFromCache(account) {
const accountKey = AccountEntity.generateAccountCacheKey(account);
return this.getAccount(accountKey);
};
}
/**

@@ -568,5 +517,5 @@ * Retrieve IdTokenEntity from cache

*/
CacheManager.prototype.getIdToken = function (account, tokenKeys) {
getIdToken(account, tokenKeys) {
this.commonLogger.trace("CacheManager - getIdToken called");
var idTokenFilter = {
const idTokenFilter = {
homeAccountId: account.homeAccountId,

@@ -578,4 +527,4 @@ environment: account.environment,

};
var idTokens = this.getIdTokensByFilter(idTokenFilter, tokenKeys);
var numIdTokens = idTokens.length;
const idTokens = this.getIdTokensByFilter(idTokenFilter, tokenKeys);
const numIdTokens = idTokens.length;
if (numIdTokens < 1) {

@@ -590,3 +539,3 @@ this.commonLogger.info("CacheManager:getIdToken - No token found");

return idTokens[0];
};
}
/**

@@ -597,12 +546,14 @@ * Gets all idTokens matching the given filter

*/
CacheManager.prototype.getIdTokensByFilter = function (filter, tokenKeys) {
var _this = this;
var idTokenKeys = tokenKeys && tokenKeys.idToken || this.getTokenKeys().idToken;
var idTokens = [];
idTokenKeys.forEach(function (key) {
if (!_this.idTokenKeyMatchesFilter(key, __assign({ clientId: _this.clientId }, filter))) {
getIdTokensByFilter(filter, tokenKeys) {
const idTokenKeys = (tokenKeys && tokenKeys.idToken) || this.getTokenKeys().idToken;
const idTokens = [];
idTokenKeys.forEach((key) => {
if (!this.idTokenKeyMatchesFilter(key, {
clientId: this.clientId,
...filter,
})) {
return;
}
var idToken = _this.getIdTokenCredential(key);
if (idToken && _this.credentialMatchesFilter(idToken, filter)) {
const idToken = this.getIdTokenCredential(key);
if (idToken && this.credentialMatchesFilter(idToken, filter)) {
idTokens.push(idToken);

@@ -612,3 +563,3 @@ }

return idTokens;
};
}
/**

@@ -620,12 +571,14 @@ * Validate the cache key against filter before retrieving and parsing cache value

*/
CacheManager.prototype.idTokenKeyMatchesFilter = function (inputKey, filter) {
var key = inputKey.toLowerCase();
if (filter.clientId && key.indexOf(filter.clientId.toLowerCase()) === -1) {
idTokenKeyMatchesFilter(inputKey, filter) {
const key = inputKey.toLowerCase();
if (filter.clientId &&
key.indexOf(filter.clientId.toLowerCase()) === -1) {
return false;
}
if (filter.homeAccountId && key.indexOf(filter.homeAccountId.toLowerCase()) === -1) {
if (filter.homeAccountId &&
key.indexOf(filter.homeAccountId.toLowerCase()) === -1) {
return false;
}
return true;
};
}
/**

@@ -635,5 +588,5 @@ * Removes idToken from the cache

*/
CacheManager.prototype.removeIdToken = function (key) {
removeIdToken(key) {
this.removeItem(key);
};
}
/**

@@ -643,5 +596,5 @@ * Removes refresh token from the cache

*/
CacheManager.prototype.removeRefreshToken = function (key) {
removeRefreshToken(key) {
this.removeItem(key);
};
}
/**

@@ -654,7 +607,6 @@ * Retrieve AccessTokenEntity from cache

*/
CacheManager.prototype.getAccessToken = function (account, request, tokenKeys) {
var _this = this;
getAccessToken(account, request, tokenKeys) {
this.commonLogger.trace("CacheManager - getAccessToken called");
var scopes = ScopeSet.createSearchScopes(request.scopes);
var authScheme = request.authenticationScheme || AuthenticationScheme.BEARER;
const scopes = ScopeSet.createSearchScopes(request.scopes);
const authScheme = request.authenticationScheme || AuthenticationScheme.BEARER;
/*

@@ -664,4 +616,8 @@ * Distinguish between Bearer and PoP/SSH token cache types

*/
var credentialType = (authScheme && authScheme.toLowerCase() !== AuthenticationScheme.BEARER.toLowerCase()) ? CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME : CredentialType.ACCESS_TOKEN;
var accessTokenFilter = {
const credentialType = authScheme &&
authScheme.toLowerCase() !==
AuthenticationScheme.BEARER.toLowerCase()
? CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME
: CredentialType.ACCESS_TOKEN;
const accessTokenFilter = {
homeAccountId: account.homeAccountId,

@@ -677,10 +633,12 @@ environment: account.environment,

};
var accessTokenKeys = tokenKeys && tokenKeys.accessToken || this.getTokenKeys().accessToken;
var accessTokens = [];
accessTokenKeys.forEach(function (key) {
const accessTokenKeys = (tokenKeys && tokenKeys.accessToken) ||
this.getTokenKeys().accessToken;
const accessTokens = [];
accessTokenKeys.forEach((key) => {
// Validate key
if (_this.accessTokenKeyMatchesFilter(key, accessTokenFilter, true)) {
var accessToken = _this.getAccessTokenCredential(key);
if (this.accessTokenKeyMatchesFilter(key, accessTokenFilter, true)) {
const accessToken = this.getAccessTokenCredential(key);
// Validate value
if (accessToken && _this.credentialMatchesFilter(accessToken, accessTokenFilter)) {
if (accessToken &&
this.credentialMatchesFilter(accessToken, accessTokenFilter)) {
accessTokens.push(accessToken);

@@ -690,3 +648,3 @@ }

});
var numAccessTokens = accessTokens.length;
const numAccessTokens = accessTokens.length;
if (numAccessTokens < 1) {

@@ -701,3 +659,3 @@ this.commonLogger.info("CacheManager:getAccessToken - No token found");

return accessTokens[0];
};
}
/**

@@ -710,8 +668,10 @@ * Validate the cache key against filter before retrieving and parsing cache value

*/
CacheManager.prototype.accessTokenKeyMatchesFilter = function (inputKey, filter, keyMustContainAllScopes) {
var key = inputKey.toLowerCase();
if (filter.clientId && key.indexOf(filter.clientId.toLowerCase()) === -1) {
accessTokenKeyMatchesFilter(inputKey, filter, keyMustContainAllScopes) {
const key = inputKey.toLowerCase();
if (filter.clientId &&
key.indexOf(filter.clientId.toLowerCase()) === -1) {
return false;
}
if (filter.homeAccountId && key.indexOf(filter.homeAccountId.toLowerCase()) === -1) {
if (filter.homeAccountId &&
key.indexOf(filter.homeAccountId.toLowerCase()) === -1) {
return false;

@@ -722,13 +682,16 @@ }

}
if (filter.requestedClaimsHash && key.indexOf(filter.requestedClaimsHash.toLowerCase()) === -1) {
if (filter.requestedClaimsHash &&
key.indexOf(filter.requestedClaimsHash.toLowerCase()) === -1) {
return false;
}
if (filter.target) {
var scopes = filter.target.asArray();
for (var i = 0; i < scopes.length; i++) {
if (keyMustContainAllScopes && !key.includes(scopes[i].toLowerCase())) {
const scopes = filter.target.asArray();
for (let i = 0; i < scopes.length; i++) {
if (keyMustContainAllScopes &&
!key.includes(scopes[i].toLowerCase())) {
// When performing a cache lookup a missing scope would be a cache miss
return false;
}
else if (!keyMustContainAllScopes && key.includes(scopes[i].toLowerCase())) {
else if (!keyMustContainAllScopes &&
key.includes(scopes[i].toLowerCase())) {
// When performing a cache write, any token with a subset of requested scopes should be replaced

@@ -740,3 +703,3 @@ return true;

return true;
};
}
/**

@@ -747,12 +710,12 @@ * Gets all access tokens matching the filter

*/
CacheManager.prototype.getAccessTokensByFilter = function (filter) {
var _this = this;
var tokenKeys = this.getTokenKeys();
var accessTokens = [];
tokenKeys.accessToken.forEach(function (key) {
if (!_this.accessTokenKeyMatchesFilter(key, filter, true)) {
getAccessTokensByFilter(filter) {
const tokenKeys = this.getTokenKeys();
const accessTokens = [];
tokenKeys.accessToken.forEach((key) => {
if (!this.accessTokenKeyMatchesFilter(key, filter, true)) {
return;
}
var accessToken = _this.getAccessTokenCredential(key);
if (accessToken && _this.credentialMatchesFilter(accessToken, filter)) {
const accessToken = this.getAccessTokenCredential(key);
if (accessToken &&
this.credentialMatchesFilter(accessToken, filter)) {
accessTokens.push(accessToken);

@@ -762,3 +725,3 @@ }

return accessTokens;
};
}
/**

@@ -770,7 +733,6 @@ * Helper to retrieve the appropriate refresh token from cache

*/
CacheManager.prototype.getRefreshToken = function (account, familyRT, tokenKeys) {
var _this = this;
getRefreshToken(account, familyRT, tokenKeys) {
this.commonLogger.trace("CacheManager - getRefreshToken called");
var id = familyRT ? THE_FAMILY_ID : undefined;
var refreshTokenFilter = {
const id = familyRT ? THE_FAMILY_ID : undefined;
const refreshTokenFilter = {
homeAccountId: account.homeAccountId,

@@ -782,10 +744,12 @@ environment: account.environment,

};
var refreshTokenKeys = tokenKeys && tokenKeys.refreshToken || this.getTokenKeys().refreshToken;
var refreshTokens = [];
refreshTokenKeys.forEach(function (key) {
const refreshTokenKeys = (tokenKeys && tokenKeys.refreshToken) ||
this.getTokenKeys().refreshToken;
const refreshTokens = [];
refreshTokenKeys.forEach((key) => {
// Validate key
if (_this.refreshTokenKeyMatchesFilter(key, refreshTokenFilter)) {
var refreshToken = _this.getRefreshTokenCredential(key);
if (this.refreshTokenKeyMatchesFilter(key, refreshTokenFilter)) {
const refreshToken = this.getRefreshTokenCredential(key);
// Validate value
if (refreshToken && _this.credentialMatchesFilter(refreshToken, refreshTokenFilter)) {
if (refreshToken &&
this.credentialMatchesFilter(refreshToken, refreshTokenFilter)) {
refreshTokens.push(refreshToken);

@@ -795,3 +759,3 @@ }

});
var numRefreshTokens = refreshTokens.length;
const numRefreshTokens = refreshTokens.length;
if (numRefreshTokens < 1) {

@@ -804,3 +768,3 @@ this.commonLogger.info("CacheManager:getRefreshToken - No refresh token found.");

return refreshTokens[0];
};
}
/**

@@ -811,27 +775,31 @@ * Validate the cache key against filter before retrieving and parsing cache value

*/
CacheManager.prototype.refreshTokenKeyMatchesFilter = function (inputKey, filter) {
var key = inputKey.toLowerCase();
if (filter.familyId && key.indexOf(filter.familyId.toLowerCase()) === -1) {
refreshTokenKeyMatchesFilter(inputKey, filter) {
const key = inputKey.toLowerCase();
if (filter.familyId &&
key.indexOf(filter.familyId.toLowerCase()) === -1) {
return false;
}
// If familyId is used, clientId is not in the key
if (!filter.familyId && filter.clientId && key.indexOf(filter.clientId.toLowerCase()) === -1) {
if (!filter.familyId &&
filter.clientId &&
key.indexOf(filter.clientId.toLowerCase()) === -1) {
return false;
}
if (filter.homeAccountId && key.indexOf(filter.homeAccountId.toLowerCase()) === -1) {
if (filter.homeAccountId &&
key.indexOf(filter.homeAccountId.toLowerCase()) === -1) {
return false;
}
return true;
};
}
/**
* Retrieve AppMetadataEntity from cache
*/
CacheManager.prototype.readAppMetadataFromCache = function (environment) {
var appMetadataFilter = {
environment: environment,
readAppMetadataFromCache(environment) {
const appMetadataFilter = {
environment,
clientId: this.clientId,
};
var appMetadata = this.getAppMetadataFilteredBy(appMetadataFilter);
var appMetadataEntries = Object.keys(appMetadata).map(function (key) { return appMetadata[key]; });
var numAppMetadata = appMetadataEntries.length;
const appMetadata = this.getAppMetadataFilteredBy(appMetadataFilter);
const appMetadataEntries = Object.keys(appMetadata).map((key) => appMetadata[key]);
const numAppMetadata = appMetadataEntries.length;
if (numAppMetadata < 1) {

@@ -844,3 +812,3 @@ return null;

return appMetadataEntries[0];
};
}
/**

@@ -851,6 +819,6 @@ * Return the family_id value associated with FOCI

*/
CacheManager.prototype.isAppMetadataFOCI = function (environment) {
var appMetadata = this.readAppMetadataFromCache(environment);
isAppMetadataFOCI(environment) {
const appMetadata = this.readAppMetadataFromCache(environment);
return !!(appMetadata && appMetadata.familyId === THE_FAMILY_ID);
};
}
/**

@@ -861,5 +829,6 @@ * helper to match account ids

*/
CacheManager.prototype.matchHomeAccountId = function (entity, homeAccountId) {
return !!((typeof entity.homeAccountId === "string") && (homeAccountId === entity.homeAccountId));
};
matchHomeAccountId(entity, homeAccountId) {
return !!(typeof entity.homeAccountId === "string" &&
homeAccountId === entity.homeAccountId);
}
/**

@@ -871,5 +840,6 @@ * helper to match account ids

*/
CacheManager.prototype.matchLocalAccountId = function (entity, localAccountId) {
return !!((typeof entity.localAccountId === "string") && (localAccountId === entity.localAccountId));
};
matchLocalAccountId(entity, localAccountId) {
return !!(typeof entity.localAccountId === "string" &&
localAccountId === entity.localAccountId);
}
/**

@@ -881,5 +851,6 @@ * helper to match usernames

*/
CacheManager.prototype.matchUsername = function (entity, username) {
return !!((typeof entity.username === "string") && (username.toLowerCase() === entity.username.toLowerCase()));
};
matchUsername(entity, username) {
return !!(typeof entity.username === "string" &&
username.toLowerCase() === entity.username.toLowerCase());
}
/**

@@ -890,5 +861,6 @@ * helper to match assertion

*/
CacheManager.prototype.matchUserAssertionHash = function (entity, userAssertionHash) {
return !!(entity.userAssertionHash && userAssertionHash === entity.userAssertionHash);
};
matchUserAssertionHash(entity, userAssertionHash) {
return !!(entity.userAssertionHash &&
userAssertionHash === entity.userAssertionHash);
}
/**

@@ -899,9 +871,10 @@ * helper to match environment

*/
CacheManager.prototype.matchEnvironment = function (entity, environment) {
var cloudMetadata = this.getAuthorityMetadataByAlias(environment);
if (cloudMetadata && cloudMetadata.aliases.indexOf(entity.environment) > -1) {
matchEnvironment(entity, environment) {
const cloudMetadata = this.getAuthorityMetadataByAlias(environment);
if (cloudMetadata &&
cloudMetadata.aliases.indexOf(entity.environment) > -1) {
return true;
}
return false;
};
}
/**

@@ -912,5 +885,6 @@ * helper to match credential type

*/
CacheManager.prototype.matchCredentialType = function (entity, credentialType) {
return (entity.credentialType && credentialType.toLowerCase() === entity.credentialType.toLowerCase());
};
matchCredentialType(entity, credentialType) {
return (entity.credentialType &&
credentialType.toLowerCase() === entity.credentialType.toLowerCase());
}
/**

@@ -921,5 +895,5 @@ * helper to match client ids

*/
CacheManager.prototype.matchClientId = function (entity, clientId) {
matchClientId(entity, clientId) {
return !!(entity.clientId && clientId === entity.clientId);
};
}
/**

@@ -930,5 +904,5 @@ * helper to match family ids

*/
CacheManager.prototype.matchFamilyId = function (entity, familyId) {
matchFamilyId(entity, familyId) {
return !!(entity.familyId && familyId === entity.familyId);
};
}
/**

@@ -939,5 +913,5 @@ * helper to match realm

*/
CacheManager.prototype.matchRealm = function (entity, realm) {
matchRealm(entity, realm) {
return !!(entity.realm && realm === entity.realm);
};
}
/**

@@ -949,5 +923,5 @@ * helper to match nativeAccountId

*/
CacheManager.prototype.matchNativeAccountId = function (entity, nativeAccountId) {
matchNativeAccountId(entity, nativeAccountId) {
return !!(entity.nativeAccountId && nativeAccountId === entity.nativeAccountId);
};
}
/**

@@ -958,10 +932,12 @@ * Returns true if the target scopes are a subset of the current entity's scopes, false otherwise.

*/
CacheManager.prototype.matchTarget = function (entity, target) {
var isNotAccessTokenCredential = (entity.credentialType !== CredentialType.ACCESS_TOKEN && entity.credentialType !== CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME);
matchTarget(entity, target) {
const isNotAccessTokenCredential = entity.credentialType !== CredentialType.ACCESS_TOKEN &&
entity.credentialType !==
CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME;
if (isNotAccessTokenCredential || !entity.target) {
return false;
}
var entityScopeSet = ScopeSet.fromString(entity.target);
const entityScopeSet = ScopeSet.fromString(entity.target);
return entityScopeSet.containsScopeSet(target);
};
}
/**

@@ -972,5 +948,5 @@ * Returns true if the credential's tokenType or Authentication Scheme matches the one in the request, false otherwise

*/
CacheManager.prototype.matchTokenType = function (entity, tokenType) {
matchTokenType(entity, tokenType) {
return !!(entity.tokenType && entity.tokenType === tokenType);
};
}
/**

@@ -981,5 +957,5 @@ * Returns true if the credential's keyId matches the one in the request, false otherwise

*/
CacheManager.prototype.matchKeyId = function (entity, keyId) {
matchKeyId(entity, keyId) {
return !!(entity.keyId && entity.keyId === keyId);
};
}
/**

@@ -989,5 +965,5 @@ * returns if a given cache entity is of the type appmetadata

*/
CacheManager.prototype.isAppMetadata = function (key) {
isAppMetadata(key) {
return key.indexOf(APP_METADATA) !== -1;
};
}
/**

@@ -997,11 +973,11 @@ * returns if a given cache entity is of the type authoritymetadata

*/
CacheManager.prototype.isAuthorityMetadata = function (key) {
isAuthorityMetadata(key) {
return key.indexOf(AUTHORITY_METADATA_CONSTANTS.CACHE_KEY) !== -1;
};
}
/**
* returns cache key used for cloud instance metadata
*/
CacheManager.prototype.generateAuthorityMetadataCacheKey = function (authority) {
return AUTHORITY_METADATA_CONSTANTS.CACHE_KEY + "-" + this.clientId + "-" + authority;
};
generateAuthorityMetadataCacheKey(authority) {
return `${AUTHORITY_METADATA_CONSTANTS.CACHE_KEY}-${this.clientId}-${authority}`;
}
/**

@@ -1012,120 +988,109 @@ * Helper to convert serialized data to object

*/
CacheManager.toObject = function (obj, json) {
for (var propertyName in json) {
static toObject(obj, json) {
for (const propertyName in json) {
obj[propertyName] = json[propertyName];
}
return obj;
};
return CacheManager;
}());
var DefaultStorageClass = /** @class */ (function (_super) {
__extends(DefaultStorageClass, _super);
function DefaultStorageClass() {
return _super !== null && _super.apply(this, arguments) || this;
}
DefaultStorageClass.prototype.setAccount = function () {
var notImplErr = "Storage interface - setAccount() has not been implemented for the cacheStorage interface.";
}
class DefaultStorageClass extends CacheManager {
setAccount() {
const notImplErr = "Storage interface - setAccount() has not been implemented for the cacheStorage interface.";
throw AuthError.createUnexpectedError(notImplErr);
};
DefaultStorageClass.prototype.getAccount = function () {
var notImplErr = "Storage interface - getAccount() has not been implemented for the cacheStorage interface.";
}
getAccount() {
const notImplErr = "Storage interface - getAccount() has not been implemented for the cacheStorage interface.";
throw AuthError.createUnexpectedError(notImplErr);
};
DefaultStorageClass.prototype.setIdTokenCredential = function () {
var notImplErr = "Storage interface - setIdTokenCredential() has not been implemented for the cacheStorage interface.";
}
setIdTokenCredential() {
const notImplErr = "Storage interface - setIdTokenCredential() has not been implemented for the cacheStorage interface.";
throw AuthError.createUnexpectedError(notImplErr);
};
DefaultStorageClass.prototype.getIdTokenCredential = function () {
var notImplErr = "Storage interface - getIdTokenCredential() has not been implemented for the cacheStorage interface.";
}
getIdTokenCredential() {
const notImplErr = "Storage interface - getIdTokenCredential() has not been implemented for the cacheStorage interface.";
throw AuthError.createUnexpectedError(notImplErr);
};
DefaultStorageClass.prototype.setAccessTokenCredential = function () {
var notImplErr = "Storage interface - setAccessTokenCredential() has not been implemented for the cacheStorage interface.";
}
setAccessTokenCredential() {
const notImplErr = "Storage interface - setAccessTokenCredential() has not been implemented for the cacheStorage interface.";
throw AuthError.createUnexpectedError(notImplErr);
};
DefaultStorageClass.prototype.getAccessTokenCredential = function () {
var notImplErr = "Storage interface - getAccessTokenCredential() has not been implemented for the cacheStorage interface.";
}
getAccessTokenCredential() {
const notImplErr = "Storage interface - getAccessTokenCredential() has not been implemented for the cacheStorage interface.";
throw AuthError.createUnexpectedError(notImplErr);
};
DefaultStorageClass.prototype.setRefreshTokenCredential = function () {
var notImplErr = "Storage interface - setRefreshTokenCredential() has not been implemented for the cacheStorage interface.";
}
setRefreshTokenCredential() {
const notImplErr = "Storage interface - setRefreshTokenCredential() has not been implemented for the cacheStorage interface.";
throw AuthError.createUnexpectedError(notImplErr);
};
DefaultStorageClass.prototype.getRefreshTokenCredential = function () {
var notImplErr = "Storage interface - getRefreshTokenCredential() has not been implemented for the cacheStorage interface.";
}
getRefreshTokenCredential() {
const notImplErr = "Storage interface - getRefreshTokenCredential() has not been implemented for the cacheStorage interface.";
throw AuthError.createUnexpectedError(notImplErr);
};
DefaultStorageClass.prototype.setAppMetadata = function () {
var notImplErr = "Storage interface - setAppMetadata() has not been implemented for the cacheStorage interface.";
}
setAppMetadata() {
const notImplErr = "Storage interface - setAppMetadata() has not been implemented for the cacheStorage interface.";
throw AuthError.createUnexpectedError(notImplErr);
};
DefaultStorageClass.prototype.getAppMetadata = function () {
var notImplErr = "Storage interface - getAppMetadata() has not been implemented for the cacheStorage interface.";
}
getAppMetadata() {
const notImplErr = "Storage interface - getAppMetadata() has not been implemented for the cacheStorage interface.";
throw AuthError.createUnexpectedError(notImplErr);
};
DefaultStorageClass.prototype.setServerTelemetry = function () {
var notImplErr = "Storage interface - setServerTelemetry() has not been implemented for the cacheStorage interface.";
}
setServerTelemetry() {
const notImplErr = "Storage interface - setServerTelemetry() has not been implemented for the cacheStorage interface.";
throw AuthError.createUnexpectedError(notImplErr);
};
DefaultStorageClass.prototype.getServerTelemetry = function () {
var notImplErr = "Storage interface - getServerTelemetry() has not been implemented for the cacheStorage interface.";
}
getServerTelemetry() {
const notImplErr = "Storage interface - getServerTelemetry() has not been implemented for the cacheStorage interface.";
throw AuthError.createUnexpectedError(notImplErr);
};
DefaultStorageClass.prototype.setAuthorityMetadata = function () {
var notImplErr = "Storage interface - setAuthorityMetadata() has not been implemented for the cacheStorage interface.";
}
setAuthorityMetadata() {
const notImplErr = "Storage interface - setAuthorityMetadata() has not been implemented for the cacheStorage interface.";
throw AuthError.createUnexpectedError(notImplErr);
};
DefaultStorageClass.prototype.getAuthorityMetadata = function () {
var notImplErr = "Storage interface - getAuthorityMetadata() has not been implemented for the cacheStorage interface.";
}
getAuthorityMetadata() {
const notImplErr = "Storage interface - getAuthorityMetadata() has not been implemented for the cacheStorage interface.";
throw AuthError.createUnexpectedError(notImplErr);
};
DefaultStorageClass.prototype.getAuthorityMetadataKeys = function () {
var notImplErr = "Storage interface - getAuthorityMetadataKeys() has not been implemented for the cacheStorage interface.";
}
getAuthorityMetadataKeys() {
const notImplErr = "Storage interface - getAuthorityMetadataKeys() has not been implemented for the cacheStorage interface.";
throw AuthError.createUnexpectedError(notImplErr);
};
DefaultStorageClass.prototype.setThrottlingCache = function () {
var notImplErr = "Storage interface - setThrottlingCache() has not been implemented for the cacheStorage interface.";
}
setThrottlingCache() {
const notImplErr = "Storage interface - setThrottlingCache() has not been implemented for the cacheStorage interface.";
throw AuthError.createUnexpectedError(notImplErr);
};
DefaultStorageClass.prototype.getThrottlingCache = function () {
var notImplErr = "Storage interface - getThrottlingCache() has not been implemented for the cacheStorage interface.";
}
getThrottlingCache() {
const notImplErr = "Storage interface - getThrottlingCache() has not been implemented for the cacheStorage interface.";
throw AuthError.createUnexpectedError(notImplErr);
};
DefaultStorageClass.prototype.removeItem = function () {
var notImplErr = "Storage interface - removeItem() has not been implemented for the cacheStorage interface.";
}
removeItem() {
const notImplErr = "Storage interface - removeItem() has not been implemented for the cacheStorage interface.";
throw AuthError.createUnexpectedError(notImplErr);
};
DefaultStorageClass.prototype.containsKey = function () {
var notImplErr = "Storage interface - containsKey() has not been implemented for the cacheStorage interface.";
}
containsKey() {
const notImplErr = "Storage interface - containsKey() has not been implemented for the cacheStorage interface.";
throw AuthError.createUnexpectedError(notImplErr);
};
DefaultStorageClass.prototype.getKeys = function () {
var notImplErr = "Storage interface - getKeys() has not been implemented for the cacheStorage interface.";
}
getKeys() {
const notImplErr = "Storage interface - getKeys() has not been implemented for the cacheStorage interface.";
throw AuthError.createUnexpectedError(notImplErr);
};
DefaultStorageClass.prototype.getAccountKeys = function () {
var notImplErr = "Storage interface - getAccountKeys() has not been implemented for the cacheStorage interface.";
}
getAccountKeys() {
const notImplErr = "Storage interface - getAccountKeys() has not been implemented for the cacheStorage interface.";
throw AuthError.createUnexpectedError(notImplErr);
};
DefaultStorageClass.prototype.getTokenKeys = function () {
var notImplErr = "Storage interface - getTokenKeys() has not been implemented for the cacheStorage interface.";
}
getTokenKeys() {
const notImplErr = "Storage interface - getTokenKeys() has not been implemented for the cacheStorage interface.";
throw AuthError.createUnexpectedError(notImplErr);
};
DefaultStorageClass.prototype.clear = function () {
return __awaiter(this, void 0, void 0, function () {
var notImplErr;
return __generator(this, function (_a) {
notImplErr = "Storage interface - clear() has not been implemented for the cacheStorage interface.";
throw AuthError.createUnexpectedError(notImplErr);
});
});
};
DefaultStorageClass.prototype.updateCredentialCacheKey = function () {
var notImplErr = "Storage interface - updateCredentialCacheKey() has not been implemented for the cacheStorage interface.";
}
async clear() {
const notImplErr = "Storage interface - clear() has not been implemented for the cacheStorage interface.";
throw AuthError.createUnexpectedError(notImplErr);
};
return DefaultStorageClass;
}(CacheManager));
}
updateCredentialCacheKey() {
const notImplErr = "Storage interface - updateCredentialCacheKey() has not been implemented for the cacheStorage interface.";
throw AuthError.createUnexpectedError(notImplErr);
}
}
export { CacheManager, DefaultStorageClass };
//# sourceMappingURL=CacheManager.js.map

@@ -1,4 +0,3 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';
import { __extends } from '../../_virtual/_tslib.js';
import { CredentialEntity } from './CredentialEntity.js';

@@ -39,7 +38,3 @@ import { CredentialType, AuthenticationScheme } from '../../utils/Constants.js';

*/
var AccessTokenEntity = /** @class */ (function (_super) {
__extends(AccessTokenEntity, _super);
function AccessTokenEntity() {
return _super !== null && _super.apply(this, arguments) || this;
}
class AccessTokenEntity extends CredentialEntity {
/**

@@ -56,9 +51,8 @@ * Create AccessTokenEntity

*/
AccessTokenEntity.createAccessTokenEntity = function (homeAccountId, environment, accessToken, clientId, tenantId, scopes, expiresOn, extExpiresOn, cryptoUtils, refreshOn, tokenType, userAssertionHash, keyId, requestedClaims, requestedClaimsHash) {
var _a, _b;
var atEntity = new AccessTokenEntity();
static createAccessTokenEntity(homeAccountId, environment, accessToken, clientId, tenantId, scopes, expiresOn, extExpiresOn, cryptoUtils, refreshOn, tokenType, userAssertionHash, keyId, requestedClaims, requestedClaimsHash) {
const atEntity = new AccessTokenEntity();
atEntity.homeAccountId = homeAccountId;
atEntity.credentialType = CredentialType.ACCESS_TOKEN;
atEntity.secret = accessToken;
var currentTime = TimeUtils.nowSeconds();
const currentTime = TimeUtils.nowSeconds();
atEntity.cachedAt = currentTime.toString();

@@ -79,3 +73,5 @@ /*

atEntity.userAssertionHash = userAssertionHash;
atEntity.tokenType = StringUtils.isEmpty(tokenType) ? AuthenticationScheme.BEARER : tokenType;
atEntity.tokenType = StringUtils.isEmpty(tokenType)
? AuthenticationScheme.BEARER
: tokenType;
if (requestedClaims) {

@@ -89,9 +85,11 @@ atEntity.requestedClaims = requestedClaims;

*/
if (((_a = atEntity.tokenType) === null || _a === void 0 ? void 0 : _a.toLowerCase()) !== AuthenticationScheme.BEARER.toLowerCase()) {
atEntity.credentialType = CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME;
if (atEntity.tokenType?.toLowerCase() !==
AuthenticationScheme.BEARER.toLowerCase()) {
atEntity.credentialType =
CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME;
switch (atEntity.tokenType) {
case AuthenticationScheme.POP:
// Make sure keyId is present and add it to credential
var tokenClaims = AuthToken.extractTokenClaims(accessToken, cryptoUtils);
if (!((_b = tokenClaims === null || tokenClaims === void 0 ? void 0 : tokenClaims.cnf) === null || _b === void 0 ? void 0 : _b.kid)) {
const tokenClaims = AuthToken.extractTokenClaims(accessToken, cryptoUtils);
if (!tokenClaims?.cnf?.kid) {
throw ClientAuthError.createTokenClaimsRequiredError();

@@ -106,3 +104,3 @@ }

return atEntity;
};
}
/**

@@ -112,3 +110,3 @@ * Validates an entity: checks for all expected params

*/
AccessTokenEntity.isAccessTokenEntity = function (entity) {
static isAccessTokenEntity(entity) {
if (!entity) {

@@ -124,8 +122,9 @@ return false;

entity.hasOwnProperty("target") &&
(entity["credentialType"] === CredentialType.ACCESS_TOKEN || entity["credentialType"] === CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME));
};
return AccessTokenEntity;
}(CredentialEntity));
(entity["credentialType"] === CredentialType.ACCESS_TOKEN ||
entity["credentialType"] ===
CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME));
}
}
export { AccessTokenEntity };
//# sourceMappingURL=AccessTokenEntity.js.map

@@ -1,2 +0,2 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';

@@ -36,16 +36,14 @@ import { Separators, CacheAccountType, CacheType, Constants } from '../../utils/Constants.js';

*/
var AccountEntity = /** @class */ (function () {
function AccountEntity() {
}
class AccountEntity {
/**
* Generate Account Id key component as per the schema: <home_account_id>-<environment>
*/
AccountEntity.prototype.generateAccountId = function () {
var accountId = [this.homeAccountId, this.environment];
generateAccountId() {
const accountId = [this.homeAccountId, this.environment];
return accountId.join(Separators.CACHE_KEY_SEPARATOR).toLowerCase();
};
}
/**
* Generate Account Cache Key as per the schema: <home_account_id>-<environment>-<realm*>
*/
AccountEntity.prototype.generateAccountKey = function () {
generateAccountKey() {
return AccountEntity.generateAccountCacheKey({

@@ -56,9 +54,9 @@ homeAccountId: this.homeAccountId,

username: this.username,
localAccountId: this.localAccountId
localAccountId: this.localAccountId,
});
};
}
/**
* returns the type of the cache (in this case account)
*/
AccountEntity.prototype.generateType = function () {
generateType() {
switch (this.authorityType) {

@@ -77,7 +75,7 @@ case CacheAccountType.ADFS_ACCOUNT_TYPE:

}
};
}
/**
* Returns the AccountInfo interface for this account.
*/
AccountEntity.prototype.getAccountInfo = function () {
getAccountInfo() {
return {

@@ -91,5 +89,5 @@ homeAccountId: this.homeAccountId,

idTokenClaims: this.idTokenClaims,
nativeAccountId: this.nativeAccountId
nativeAccountId: this.nativeAccountId,
};
};
}
/**

@@ -99,4 +97,4 @@ * Generates account key from interface

*/
AccountEntity.generateAccountCacheKey = function (accountInterface) {
var accountKey = [
static generateAccountCacheKey(accountInterface) {
const accountKey = [
accountInterface.homeAccountId,

@@ -107,3 +105,3 @@ accountInterface.environment || Constants.EMPTY_STRING,

return accountKey.join(Separators.CACHE_KEY_SEPARATOR).toLowerCase();
};
}
/**

@@ -116,5 +114,4 @@ * Build Account cache from IdToken, clientInfo and authority/policy. Associated with AAD.

*/
AccountEntity.createAccount = function (clientInfo, homeAccountId, idToken, authority, cloudGraphHostName, msGraphHost, environment, nativeAccountId) {
var _a, _b, _c, _d, _e, _f;
var account = new AccountEntity();
static createAccount(clientInfo, homeAccountId, idToken, authority, cloudGraphHostName, msGraphHost, environment, nativeAccountId) {
const account = new AccountEntity();
account.authorityType = CacheAccountType.MSSTS_ACCOUNT_TYPE;

@@ -124,3 +121,3 @@ account.clientInfo = clientInfo;

account.nativeAccountId = nativeAccountId;
var env = environment || (authority && authority.getPreferredCache());
const env = environment || (authority && authority.getPreferredCache());
if (!env) {

@@ -131,7 +128,10 @@ throw ClientAuthError.createInvalidCacheEnvironmentError();

// non AAD scenarios can have empty realm
account.realm = ((_a = idToken === null || idToken === void 0 ? void 0 : idToken.claims) === null || _a === void 0 ? void 0 : _a.tid) || Constants.EMPTY_STRING;
account.realm = idToken?.claims?.tid || Constants.EMPTY_STRING;
if (idToken) {
account.idTokenClaims = idToken.claims;
// How do you account for MSA CID here?
account.localAccountId = ((_b = idToken === null || idToken === void 0 ? void 0 : idToken.claims) === null || _b === void 0 ? void 0 : _b.oid) || ((_c = idToken === null || idToken === void 0 ? void 0 : idToken.claims) === null || _c === void 0 ? void 0 : _c.sub) || Constants.EMPTY_STRING;
account.localAccountId =
idToken?.claims?.oid ||
idToken?.claims?.sub ||
Constants.EMPTY_STRING;
/*

@@ -142,6 +142,9 @@ * In B2C scenarios the emails claim is used instead of preferred_username and it is an array.

*/
var preferredUsername = (_d = idToken === null || idToken === void 0 ? void 0 : idToken.claims) === null || _d === void 0 ? void 0 : _d.preferred_username;
var email = ((_e = idToken === null || idToken === void 0 ? void 0 : idToken.claims) === null || _e === void 0 ? void 0 : _e.emails) ? idToken.claims.emails[0] : null;
account.username = preferredUsername || email || Constants.EMPTY_STRING;
account.name = (_f = idToken === null || idToken === void 0 ? void 0 : idToken.claims) === null || _f === void 0 ? void 0 : _f.name;
const preferredUsername = idToken?.claims?.preferred_username;
const email = idToken?.claims?.emails
? idToken.claims.emails[0]
: null;
account.username =
preferredUsername || email || Constants.EMPTY_STRING;
account.name = idToken?.claims?.name;
}

@@ -151,3 +154,3 @@ account.cloudGraphHostName = cloudGraphHostName;

return account;
};
}
/**

@@ -158,11 +161,12 @@ * Builds non-AAD/ADFS account.

*/
AccountEntity.createGenericAccount = function (homeAccountId, idToken, authority, cloudGraphHostName, msGraphHost, environment) {
var _a, _b, _c, _d;
var account = new AccountEntity();
account.authorityType = (authority &&
authority.authorityType === AuthorityType.Adfs) ? CacheAccountType.ADFS_ACCOUNT_TYPE : CacheAccountType.GENERIC_ACCOUNT_TYPE;
static createGenericAccount(homeAccountId, idToken, authority, cloudGraphHostName, msGraphHost, environment) {
const account = new AccountEntity();
account.authorityType =
authority && authority.authorityType === AuthorityType.Adfs
? CacheAccountType.ADFS_ACCOUNT_TYPE
: CacheAccountType.GENERIC_ACCOUNT_TYPE;
account.homeAccountId = homeAccountId;
// non AAD scenarios can have empty realm
account.realm = Constants.EMPTY_STRING;
var env = environment || authority && authority.getPreferredCache();
const env = environment || (authority && authority.getPreferredCache());
if (!env) {

@@ -173,7 +177,10 @@ throw ClientAuthError.createInvalidCacheEnvironmentError();

// How do you account for MSA CID here?
account.localAccountId = ((_a = idToken === null || idToken === void 0 ? void 0 : idToken.claims) === null || _a === void 0 ? void 0 : _a.oid) || ((_b = idToken === null || idToken === void 0 ? void 0 : idToken.claims) === null || _b === void 0 ? void 0 : _b.sub) || Constants.EMPTY_STRING;
account.localAccountId =
idToken?.claims?.oid ||
idToken?.claims?.sub ||
Constants.EMPTY_STRING;
// upn claim for most ADFS scenarios
account.username = ((_c = idToken === null || idToken === void 0 ? void 0 : idToken.claims) === null || _c === void 0 ? void 0 : _c.upn) || Constants.EMPTY_STRING;
account.name = ((_d = idToken === null || idToken === void 0 ? void 0 : idToken.claims) === null || _d === void 0 ? void 0 : _d.name) || Constants.EMPTY_STRING;
account.idTokenClaims = idToken === null || idToken === void 0 ? void 0 : idToken.claims;
account.username = idToken?.claims?.upn || Constants.EMPTY_STRING;
account.name = idToken?.claims?.name || Constants.EMPTY_STRING;
account.idTokenClaims = idToken?.claims;
}

@@ -188,3 +195,3 @@ account.environment = env;

return account;
};
}
/**

@@ -195,7 +202,9 @@ * Generate HomeAccountId from server response

*/
AccountEntity.generateHomeAccountId = function (serverClientInfo, authType, logger, cryptoObj, idToken) {
var _a;
var accountId = ((_a = idToken === null || idToken === void 0 ? void 0 : idToken.claims) === null || _a === void 0 ? void 0 : _a.sub) ? idToken.claims.sub : Constants.EMPTY_STRING;
static generateHomeAccountId(serverClientInfo, authType, logger, cryptoObj, idToken) {
const accountId = idToken?.claims?.sub
? idToken.claims.sub
: Constants.EMPTY_STRING;
// since ADFS does not have tid and does not set client_info
if (authType === AuthorityType.Adfs || authType === AuthorityType.Dsts) {
if (authType === AuthorityType.Adfs ||
authType === AuthorityType.Dsts) {
return accountId;

@@ -206,5 +215,6 @@ }

try {
var clientInfo = buildClientInfo(serverClientInfo, cryptoObj);
if (!StringUtils.isEmpty(clientInfo.uid) && !StringUtils.isEmpty(clientInfo.utid)) {
return "" + clientInfo.uid + Separators.CLIENT_INFO_SEPARATOR + clientInfo.utid;
const clientInfo = buildClientInfo(serverClientInfo, cryptoObj);
if (!StringUtils.isEmpty(clientInfo.uid) &&
!StringUtils.isEmpty(clientInfo.utid)) {
return `${clientInfo.uid}${Separators.CLIENT_INFO_SEPARATOR}${clientInfo.utid}`;
}

@@ -217,3 +227,3 @@ }

return accountId;
};
}
/**

@@ -223,3 +233,3 @@ * Validates an entity: checks for all expected params

*/
AccountEntity.isAccountEntity = function (entity) {
static isAccountEntity(entity) {
if (!entity) {

@@ -234,3 +244,3 @@ return false;

entity.hasOwnProperty("authorityType"));
};
}
/**

@@ -242,26 +252,28 @@ * Helper function to determine whether 2 accountInfo objects represent the same account

*/
AccountEntity.accountInfoIsEqual = function (accountA, accountB, compareClaims) {
static accountInfoIsEqual(accountA, accountB, compareClaims) {
if (!accountA || !accountB) {
return false;
}
var claimsMatch = true; // default to true so as to not fail comparison below if compareClaims: false
let claimsMatch = true; // default to true so as to not fail comparison below if compareClaims: false
if (compareClaims) {
var accountAClaims = (accountA.idTokenClaims || {});
var accountBClaims = (accountB.idTokenClaims || {});
const accountAClaims = (accountA.idTokenClaims ||
{});
const accountBClaims = (accountB.idTokenClaims ||
{});
// issued at timestamp and nonce are expected to change each time a new id token is acquired
claimsMatch = (accountAClaims.iat === accountBClaims.iat) &&
(accountAClaims.nonce === accountBClaims.nonce);
claimsMatch =
accountAClaims.iat === accountBClaims.iat &&
accountAClaims.nonce === accountBClaims.nonce;
}
return (accountA.homeAccountId === accountB.homeAccountId) &&
(accountA.localAccountId === accountB.localAccountId) &&
(accountA.username === accountB.username) &&
(accountA.tenantId === accountB.tenantId) &&
(accountA.environment === accountB.environment) &&
(accountA.nativeAccountId === accountB.nativeAccountId) &&
claimsMatch;
};
return AccountEntity;
}());
return (accountA.homeAccountId === accountB.homeAccountId &&
accountA.localAccountId === accountB.localAccountId &&
accountA.username === accountB.username &&
accountA.tenantId === accountB.tenantId &&
accountA.environment === accountB.environment &&
accountA.nativeAccountId === accountB.nativeAccountId &&
claimsMatch);
}
}
export { AccountEntity };
//# sourceMappingURL=AccountEntity.js.map

@@ -1,2 +0,2 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';

@@ -23,16 +23,14 @@ import { Separators, APP_METADATA } from '../../utils/Constants.js';

*/
var AppMetadataEntity = /** @class */ (function () {
function AppMetadataEntity() {
}
class AppMetadataEntity {
/**
* Generate AppMetadata Cache Key as per the schema: appmetadata-<environment>-<client_id>
*/
AppMetadataEntity.prototype.generateAppMetadataKey = function () {
generateAppMetadataKey() {
return AppMetadataEntity.generateAppMetadataCacheKey(this.environment, this.clientId);
};
}
/**
* Generate AppMetadata Cache Key
*/
AppMetadataEntity.generateAppMetadataCacheKey = function (environment, clientId) {
var appMetaDataKeyArray = [
static generateAppMetadataCacheKey(environment, clientId) {
const appMetaDataKeyArray = [
APP_METADATA,

@@ -42,4 +40,6 @@ environment,

];
return appMetaDataKeyArray.join(Separators.CACHE_KEY_SEPARATOR).toLowerCase();
};
return appMetaDataKeyArray
.join(Separators.CACHE_KEY_SEPARATOR)
.toLowerCase();
}
/**

@@ -51,4 +51,4 @@ * Creates AppMetadataEntity

*/
AppMetadataEntity.createAppMetadataEntity = function (clientId, environment, familyId) {
var appMetadata = new AppMetadataEntity();
static createAppMetadataEntity(clientId, environment, familyId) {
const appMetadata = new AppMetadataEntity();
appMetadata.clientId = clientId;

@@ -60,3 +60,3 @@ appMetadata.environment = environment;

return appMetadata;
};
}
/**

@@ -66,3 +66,3 @@ * Validates an entity: checks for all expected params

*/
AppMetadataEntity.isAppMetadataEntity = function (key, entity) {
static isAppMetadataEntity(key, entity) {
if (!entity) {

@@ -74,7 +74,6 @@ return false;

entity.hasOwnProperty("environment"));
};
return AppMetadataEntity;
}());
}
}
export { AppMetadataEntity };
//# sourceMappingURL=AppMetadataEntity.js.map

@@ -1,2 +0,2 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';

@@ -10,5 +10,7 @@ import { AUTHORITY_METADATA_CONSTANTS } from '../../utils/Constants.js';

*/
var AuthorityMetadataEntity = /** @class */ (function () {
function AuthorityMetadataEntity() {
this.expiresAt = TimeUtils.nowSeconds() + AUTHORITY_METADATA_CONSTANTS.REFRESH_TIME_SECONDS;
class AuthorityMetadataEntity {
constructor() {
this.expiresAt =
TimeUtils.nowSeconds() +
AUTHORITY_METADATA_CONSTANTS.REFRESH_TIME_SECONDS;
}

@@ -20,3 +22,3 @@ /**

*/
AuthorityMetadataEntity.prototype.updateCloudDiscoveryMetadata = function (metadata, fromNetwork) {
updateCloudDiscoveryMetadata(metadata, fromNetwork) {
this.aliases = metadata.aliases;

@@ -26,3 +28,3 @@ this.preferred_cache = metadata.preferred_cache;

this.aliasesFromNetwork = fromNetwork;
};
}
/**

@@ -33,3 +35,3 @@ * Update the entity with new endpoints

*/
AuthorityMetadataEntity.prototype.updateEndpointMetadata = function (metadata, fromNetwork) {
updateEndpointMetadata(metadata, fromNetwork) {
this.authorization_endpoint = metadata.authorization_endpoint;

@@ -41,3 +43,3 @@ this.token_endpoint = metadata.token_endpoint;

this.jwks_uri = metadata.jwks_uri;
};
}
/**

@@ -47,17 +49,19 @@ * Save the authority that was used to create this cache entry

*/
AuthorityMetadataEntity.prototype.updateCanonicalAuthority = function (authority) {
updateCanonicalAuthority(authority) {
this.canonical_authority = authority;
};
}
/**
* Reset the exiresAt value
*/
AuthorityMetadataEntity.prototype.resetExpiresAt = function () {
this.expiresAt = TimeUtils.nowSeconds() + AUTHORITY_METADATA_CONSTANTS.REFRESH_TIME_SECONDS;
};
resetExpiresAt() {
this.expiresAt =
TimeUtils.nowSeconds() +
AUTHORITY_METADATA_CONSTANTS.REFRESH_TIME_SECONDS;
}
/**
* Returns whether or not the data needs to be refreshed
*/
AuthorityMetadataEntity.prototype.isExpired = function () {
isExpired() {
return this.expiresAt <= TimeUtils.nowSeconds();
};
}
/**

@@ -67,3 +71,3 @@ * Validates an entity: checks for all expected params

*/
AuthorityMetadataEntity.isAuthorityMetadataEntity = function (key, entity) {
static isAuthorityMetadataEntity(key, entity) {
if (!entity) {

@@ -84,7 +88,6 @@ return false;

entity.hasOwnProperty("jwks_uri"));
};
return AuthorityMetadataEntity;
}());
}
}
export { AuthorityMetadataEntity };
//# sourceMappingURL=AuthorityMetadataEntity.js.map

@@ -1,2 +0,2 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';

@@ -7,4 +7,4 @@ /*

*/
var CacheRecord = /** @class */ (function () {
function CacheRecord(accountEntity, idTokenEntity, accessTokenEntity, refreshTokenEntity, appMetadataEntity) {
class CacheRecord {
constructor(accountEntity, idTokenEntity, accessTokenEntity, refreshTokenEntity, appMetadataEntity) {
this.account = accountEntity || null;

@@ -16,6 +16,5 @@ this.idToken = idTokenEntity || null;

}
return CacheRecord;
}());
}
export { CacheRecord };
//# sourceMappingURL=CacheRecord.js.map

@@ -1,2 +0,2 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';

@@ -32,33 +32,31 @@ import { CredentialType, CacheType, Separators, Constants, AuthenticationScheme } from '../../utils/Constants.js';

*/
var CredentialEntity = /** @class */ (function () {
function CredentialEntity() {
}
class CredentialEntity {
/**
* Generate Account Id key component as per the schema: <home_account_id>-<environment>
*/
CredentialEntity.prototype.generateAccountId = function () {
generateAccountId() {
return CredentialEntity.generateAccountIdForCacheKey(this.homeAccountId, this.environment);
};
}
/**
* Generate Credential Id key component as per the schema: <credential_type>-<client_id>-<realm>
*/
CredentialEntity.prototype.generateCredentialId = function () {
generateCredentialId() {
return CredentialEntity.generateCredentialIdForCacheKey(this.credentialType, this.clientId, this.realm, this.familyId);
};
}
/**
* Generate target key component as per schema: <target>
*/
CredentialEntity.prototype.generateTarget = function () {
generateTarget() {
return CredentialEntity.generateTargetForCacheKey(this.target);
};
}
/**
* generates credential key
*/
CredentialEntity.prototype.generateCredentialKey = function () {
generateCredentialKey() {
return CredentialEntity.generateCredentialCacheKey(this.homeAccountId, this.environment, this.credentialType, this.clientId, this.realm, this.target, this.familyId, this.tokenType, this.requestedClaimsHash);
};
}
/**
* returns the type of the cache (in this case credential)
*/
CredentialEntity.prototype.generateType = function () {
generateType() {
switch (this.credentialType) {

@@ -76,3 +74,3 @@ case CredentialType.ID_TOKEN:

}
};
}
/**

@@ -82,4 +80,4 @@ * generates credential key

*/
CredentialEntity.generateCredentialCacheKey = function (homeAccountId, environment, credentialType, clientId, realm, target, familyId, tokenType, requestedClaimsHash) {
var credentialKey = [
static generateCredentialCacheKey(homeAccountId, environment, credentialType, clientId, realm, target, familyId, tokenType, requestedClaimsHash) {
const credentialKey = [
this.generateAccountIdForCacheKey(homeAccountId, environment),

@@ -89,6 +87,6 @@ this.generateCredentialIdForCacheKey(credentialType, clientId, realm, familyId),

this.generateClaimsHashForCacheKey(requestedClaimsHash),
this.generateSchemeForCacheKey(tokenType)
this.generateSchemeForCacheKey(tokenType),
];
return credentialKey.join(Separators.CACHE_KEY_SEPARATOR).toLowerCase();
};
}
/**

@@ -99,6 +97,6 @@ * generates Account Id for keys

*/
CredentialEntity.generateAccountIdForCacheKey = function (homeAccountId, environment) {
var accountId = [homeAccountId, environment];
static generateAccountIdForCacheKey(homeAccountId, environment) {
const accountId = [homeAccountId, environment];
return accountId.join(Separators.CACHE_KEY_SEPARATOR).toLowerCase();
};
}
/**

@@ -111,7 +109,7 @@ * Generates Credential Id for keys

*/
CredentialEntity.generateCredentialIdForCacheKey = function (credentialType, clientId, realm, familyId) {
var clientOrFamilyId = credentialType === CredentialType.REFRESH_TOKEN
static generateCredentialIdForCacheKey(credentialType, clientId, realm, familyId) {
const clientOrFamilyId = credentialType === CredentialType.REFRESH_TOKEN
? familyId || clientId
: clientId;
var credentialId = [
const credentialId = [
credentialType,

@@ -122,19 +120,19 @@ clientOrFamilyId,

return credentialId.join(Separators.CACHE_KEY_SEPARATOR).toLowerCase();
};
}
/**
* Generate target key component as per schema: <target>
*/
CredentialEntity.generateTargetForCacheKey = function (scopes) {
static generateTargetForCacheKey(scopes) {
return (scopes || Constants.EMPTY_STRING).toLowerCase();
};
}
/**
* Generate requested claims key component as per schema: <requestedClaims>
*/
CredentialEntity.generateClaimsHashForCacheKey = function (requestedClaimsHash) {
static generateClaimsHashForCacheKey(requestedClaimsHash) {
return (requestedClaimsHash || Constants.EMPTY_STRING).toLowerCase();
};
}
/**
* Generate scheme key componenet as per schema: <scheme>
*/
CredentialEntity.generateSchemeForCacheKey = function (tokenType) {
static generateSchemeForCacheKey(tokenType) {
/*

@@ -144,8 +142,11 @@ * PoP Tokens and SSH certs include scheme in cache key

*/
return (tokenType && tokenType.toLowerCase() !== AuthenticationScheme.BEARER.toLowerCase()) ? tokenType.toLowerCase() : Constants.EMPTY_STRING;
};
return CredentialEntity;
}());
return tokenType &&
tokenType.toLowerCase() !==
AuthenticationScheme.BEARER.toLowerCase()
? tokenType.toLowerCase()
: Constants.EMPTY_STRING;
}
}
export { CredentialEntity };
//# sourceMappingURL=CredentialEntity.js.map

@@ -1,4 +0,3 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';
import { __extends } from '../../_virtual/_tslib.js';
import { CredentialEntity } from './CredentialEntity.js';

@@ -28,7 +27,3 @@ import { CredentialType } from '../../utils/Constants.js';

*/
var IdTokenEntity = /** @class */ (function (_super) {
__extends(IdTokenEntity, _super);
function IdTokenEntity() {
return _super !== null && _super.apply(this, arguments) || this;
}
class IdTokenEntity extends CredentialEntity {
/**

@@ -41,4 +36,4 @@ * Create IdTokenEntity

*/
IdTokenEntity.createIdTokenEntity = function (homeAccountId, environment, idToken, clientId, tenantId) {
var idTokenEntity = new IdTokenEntity();
static createIdTokenEntity(homeAccountId, environment, idToken, clientId, tenantId) {
const idTokenEntity = new IdTokenEntity();
idTokenEntity.credentialType = CredentialType.ID_TOKEN;

@@ -51,3 +46,3 @@ idTokenEntity.homeAccountId = homeAccountId;

return idTokenEntity;
};
}
/**

@@ -57,3 +52,3 @@ * Validates an entity: checks for all expected params

*/
IdTokenEntity.isIdTokenEntity = function (entity) {
static isIdTokenEntity(entity) {
if (!entity) {

@@ -69,7 +64,6 @@ return false;

entity["credentialType"] === CredentialType.ID_TOKEN);
};
return IdTokenEntity;
}(CredentialEntity));
}
}
export { IdTokenEntity };
//# sourceMappingURL=IdTokenEntity.js.map

@@ -1,4 +0,3 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';
import { __extends } from '../../_virtual/_tslib.js';
import { CredentialEntity } from './CredentialEntity.js';

@@ -30,7 +29,3 @@ import { CredentialType } from '../../utils/Constants.js';

*/
var RefreshTokenEntity = /** @class */ (function (_super) {
__extends(RefreshTokenEntity, _super);
function RefreshTokenEntity() {
return _super !== null && _super.apply(this, arguments) || this;
}
class RefreshTokenEntity extends CredentialEntity {
/**

@@ -43,4 +38,4 @@ * Create RefreshTokenEntity

*/
RefreshTokenEntity.createRefreshTokenEntity = function (homeAccountId, environment, refreshToken, clientId, familyId, userAssertionHash) {
var rtEntity = new RefreshTokenEntity();
static createRefreshTokenEntity(homeAccountId, environment, refreshToken, clientId, familyId, userAssertionHash) {
const rtEntity = new RefreshTokenEntity();
rtEntity.clientId = clientId;

@@ -55,3 +50,3 @@ rtEntity.credentialType = CredentialType.REFRESH_TOKEN;

return rtEntity;
};
}
/**

@@ -61,3 +56,3 @@ * Validates an entity: checks for all expected params

*/
RefreshTokenEntity.isRefreshTokenEntity = function (entity) {
static isRefreshTokenEntity(entity) {
if (!entity) {

@@ -72,7 +67,6 @@ return false;

entity["credentialType"] === CredentialType.REFRESH_TOKEN);
};
return RefreshTokenEntity;
}(CredentialEntity));
}
}
export { RefreshTokenEntity };
//# sourceMappingURL=RefreshTokenEntity.js.map

@@ -1,2 +0,2 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';

@@ -9,4 +9,4 @@ import { SERVER_TELEM_CONSTANTS } from '../../utils/Constants.js';

*/
var ServerTelemetryEntity = /** @class */ (function () {
function ServerTelemetryEntity() {
class ServerTelemetryEntity {
constructor() {
this.failedRequests = [];

@@ -21,5 +21,5 @@ this.errors = [];

*/
ServerTelemetryEntity.isServerTelemetryEntity = function (key, entity) {
var validateKey = key.indexOf(SERVER_TELEM_CONSTANTS.CACHE_KEY) === 0;
var validateEntity = true;
static isServerTelemetryEntity(key, entity) {
const validateKey = key.indexOf(SERVER_TELEM_CONSTANTS.CACHE_KEY) === 0;
let validateEntity = true;
if (entity) {

@@ -32,7 +32,6 @@ validateEntity =

return validateKey && validateEntity;
};
return ServerTelemetryEntity;
}());
}
}
export { ServerTelemetryEntity };
//# sourceMappingURL=ServerTelemetryEntity.js.map

@@ -1,2 +0,2 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';

@@ -9,5 +9,3 @@ import { ThrottlingConstants } from '../../utils/Constants.js';

*/
var ThrottlingEntity = /** @class */ (function () {
function ThrottlingEntity() {
}
class ThrottlingEntity {
/**

@@ -18,8 +16,9 @@ * validates if a given cache entry is "Throttling", parses <key,value>

*/
ThrottlingEntity.isThrottlingEntity = function (key, entity) {
var validateKey = false;
static isThrottlingEntity(key, entity) {
let validateKey = false;
if (key) {
validateKey = key.indexOf(ThrottlingConstants.THROTTLING_PREFIX) === 0;
validateKey =
key.indexOf(ThrottlingConstants.THROTTLING_PREFIX) === 0;
}
var validateEntity = true;
let validateEntity = true;
if (entity) {

@@ -29,7 +28,6 @@ validateEntity = entity.hasOwnProperty("throttleTime");

return validateKey && validateEntity;
};
return ThrottlingEntity;
}());
}
}
export { ThrottlingEntity };
//# sourceMappingURL=ThrottlingEntity.js.map

@@ -1,2 +0,2 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';

@@ -10,31 +10,22 @@ /*

* decisions to read from and write to the persistent cache
*/ var TokenCacheContext = /** @class */ (function () {
function TokenCacheContext(tokenCache, hasChanged) {
*/ class TokenCacheContext {
constructor(tokenCache, hasChanged) {
this.cache = tokenCache;
this.hasChanged = hasChanged;
}
Object.defineProperty(TokenCacheContext.prototype, "cacheHasChanged", {
/**
* boolean which indicates the changes in cache
*/
get: function () {
return this.hasChanged;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TokenCacheContext.prototype, "tokenCache", {
/**
* function to retrieve the token cache
*/
get: function () {
return this.cache;
},
enumerable: false,
configurable: true
});
return TokenCacheContext;
}());
/**
* boolean which indicates the changes in cache
*/
get cacheHasChanged() {
return this.hasChanged;
}
/**
* function to retrieve the token cache
*/
get tokenCache() {
return this.cache;
}
}
export { TokenCacheContext };
//# sourceMappingURL=TokenCacheContext.js.map

@@ -11,19 +11,19 @@ import { AccountEntity } from "../entities/AccountEntity";

import { ScopeSet } from "../../request/ScopeSet";
export declare type AccountCache = Record<string, AccountEntity>;
export declare type IdTokenCache = Record<string, IdTokenEntity>;
export declare type AccessTokenCache = Record<string, AccessTokenEntity>;
export declare type RefreshTokenCache = Record<string, RefreshTokenEntity>;
export declare type AppMetadataCache = Record<string, AppMetadataEntity>;
export type AccountCache = Record<string, AccountEntity>;
export type IdTokenCache = Record<string, IdTokenEntity>;
export type AccessTokenCache = Record<string, AccessTokenEntity>;
export type RefreshTokenCache = Record<string, RefreshTokenEntity>;
export type AppMetadataCache = Record<string, AppMetadataEntity>;
/**
* Object type of all accepted cache types
*/
export declare type ValidCacheType = AccountEntity | IdTokenEntity | AccessTokenEntity | RefreshTokenEntity | AppMetadataEntity | AuthorityMetadataEntity | ServerTelemetryEntity | ThrottlingEntity | string;
export type ValidCacheType = AccountEntity | IdTokenEntity | AccessTokenEntity | RefreshTokenEntity | AppMetadataEntity | AuthorityMetadataEntity | ServerTelemetryEntity | ThrottlingEntity | string;
/**
* Object type of all credential types
*/
export declare type ValidCredentialType = IdTokenEntity | AccessTokenEntity | RefreshTokenEntity;
export type ValidCredentialType = IdTokenEntity | AccessTokenEntity | RefreshTokenEntity;
/**
* Account: <home_account_id>-<environment>-<realm*>
*/
export declare type AccountFilter = {
export type AccountFilter = {
homeAccountId?: string;

@@ -39,3 +39,3 @@ localAccountId?: string;

*/
export declare type CredentialFilter = {
export type CredentialFilter = {
homeAccountId?: string;

@@ -56,7 +56,7 @@ environment?: string;

*/
export declare type AppMetadataFilter = {
export type AppMetadataFilter = {
environment?: string;
clientId?: string;
};
export declare type TokenKeys = {
export type TokenKeys = {
idToken: string[];

@@ -63,0 +63,0 @@ accessToken: string[];

@@ -1,7 +0,6 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';
import { __extends, __awaiter, __generator, __assign, __spreadArrays } from '../_virtual/_tslib.js';
import { BaseClient } from './BaseClient.js';
import { RequestParameterBuilder } from '../request/RequestParameterBuilder.js';
import { Separators, AADServerParamKeys, AuthenticationScheme, GrantType, PromptValue, HeaderNames } from '../utils/Constants.js';
import { Separators, GrantType, AuthenticationScheme, AADServerParamKeys, PromptValue, HeaderNames } from '../utils/Constants.js';
import { ResponseHandler } from '../response/ResponseHandler.js';

@@ -26,9 +25,7 @@ import { StringUtils } from '../utils/StringUtils.js';

*/
var AuthorizationCodeClient = /** @class */ (function (_super) {
__extends(AuthorizationCodeClient, _super);
function AuthorizationCodeClient(configuration, performanceClient) {
var _this = _super.call(this, configuration, performanceClient) || this;
class AuthorizationCodeClient extends BaseClient {
constructor(configuration, performanceClient) {
super(configuration, performanceClient);
// Flag to indicate if client is for hybrid spa auth code redemption
_this.includeRedirectUri = true;
return _this;
this.includeRedirectUri = true;
}

@@ -45,19 +42,8 @@ /**

*/
AuthorizationCodeClient.prototype.getAuthCodeUrl = function (request) {
var _a, _b;
return __awaiter(this, void 0, void 0, function () {
var queryString;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
(_a = this.performanceClient) === null || _a === void 0 ? void 0 : _a.addQueueMeasurement(PerformanceEvents.GetAuthCodeUrl, request.correlationId);
(_b = this.performanceClient) === null || _b === void 0 ? void 0 : _b.setPreQueueTime(PerformanceEvents.AuthClientCreateQueryString, request.correlationId);
return [4 /*yield*/, this.createAuthCodeUrlQueryString(request)];
case 1:
queryString = _c.sent();
return [2 /*return*/, UrlString.appendQueryString(this.authority.authorizationEndpoint, queryString)];
}
});
});
};
async getAuthCodeUrl(request) {
this.performanceClient?.addQueueMeasurement(PerformanceEvents.GetAuthCodeUrl, request.correlationId);
this.performanceClient?.setPreQueueTime(PerformanceEvents.AuthClientCreateQueryString, request.correlationId);
const queryString = await this.createAuthCodeUrlQueryString(request);
return UrlString.appendQueryString(this.authority.authorizationEndpoint, queryString);
}
/**

@@ -68,51 +54,44 @@ * API to acquire a token in exchange of 'authorization_code` acquired by the user in the first leg of the

*/
AuthorizationCodeClient.prototype.acquireToken = function (request, authCodePayload) {
var _a, _b, _c, _d, _e, _f;
return __awaiter(this, void 0, void 0, function () {
var atsMeasurement, reqTimestamp, response, requestId, httpVerAuthority, responseHandler;
var _this = this;
return __generator(this, function (_g) {
switch (_g.label) {
case 0:
if (!request || !request.code) {
throw ClientAuthError.createTokenRequestCannotBeMadeError();
}
(_a = this.performanceClient) === null || _a === void 0 ? void 0 : _a.addQueueMeasurement(PerformanceEvents.AuthClientAcquireToken, request.correlationId);
atsMeasurement = (_b = this.performanceClient) === null || _b === void 0 ? void 0 : _b.startMeasurement("AuthCodeClientAcquireToken", request.correlationId);
this.logger.info("in acquireToken call in auth-code client");
reqTimestamp = TimeUtils.nowSeconds();
(_c = this.performanceClient) === null || _c === void 0 ? void 0 : _c.setPreQueueTime(PerformanceEvents.AuthClientExecuteTokenRequest, request.correlationId);
return [4 /*yield*/, this.executeTokenRequest(this.authority, request)];
case 1:
response = _g.sent();
requestId = (_d = response.headers) === null || _d === void 0 ? void 0 : _d[HeaderNames.X_MS_REQUEST_ID];
httpVerAuthority = (_e = response.headers) === null || _e === void 0 ? void 0 : _e[HeaderNames.X_MS_HTTP_VERSION];
if (httpVerAuthority) {
atsMeasurement === null || atsMeasurement === void 0 ? void 0 : atsMeasurement.addStaticFields({
httpVerAuthority: httpVerAuthority
});
}
responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.config.serializableCache, this.config.persistencePlugin, this.performanceClient);
// Validate response. This function throws a server error if an error is returned by the server.
responseHandler.validateTokenResponse(response.body);
(_f = this.performanceClient) === null || _f === void 0 ? void 0 : _f.setPreQueueTime(PerformanceEvents.HandleServerTokenResponse, request.correlationId);
return [2 /*return*/, responseHandler.handleServerTokenResponse(response.body, this.authority, reqTimestamp, request, authCodePayload, undefined, undefined, undefined, requestId).then(function (result) {
atsMeasurement === null || atsMeasurement === void 0 ? void 0 : atsMeasurement.endMeasurement({
success: true
});
return result;
})
.catch(function (error) {
_this.logger.verbose("Error in fetching token in ACC", request.correlationId);
atsMeasurement === null || atsMeasurement === void 0 ? void 0 : atsMeasurement.endMeasurement({
errorCode: error.errorCode,
subErrorCode: error.subError,
success: false
});
throw error;
})];
}
async acquireToken(request, authCodePayload) {
if (!request || !request.code) {
throw ClientAuthError.createTokenRequestCannotBeMadeError();
}
this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthClientAcquireToken, request.correlationId);
const atsMeasurement = this.performanceClient?.startMeasurement(
// @ts-ignore
"AuthCodeClientAcquireToken", request.correlationId);
this.logger.info("in acquireToken call in auth-code client");
const reqTimestamp = TimeUtils.nowSeconds();
this.performanceClient?.setPreQueueTime(PerformanceEvents.AuthClientExecuteTokenRequest, request.correlationId);
const response = await this.executeTokenRequest(this.authority, request);
// Retrieve requestId from response headers
const requestId = response.headers?.[HeaderNames.X_MS_REQUEST_ID];
const httpVerAuthority = response.headers?.[HeaderNames.X_MS_HTTP_VERSION];
if (httpVerAuthority) {
atsMeasurement?.addStaticFields({
httpVerAuthority,
});
}
const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.config.serializableCache, this.config.persistencePlugin, this.performanceClient);
// Validate response. This function throws a server error if an error is returned by the server.
responseHandler.validateTokenResponse(response.body);
this.performanceClient?.setPreQueueTime(PerformanceEvents.HandleServerTokenResponse, request.correlationId);
return responseHandler
.handleServerTokenResponse(response.body, this.authority, reqTimestamp, request, authCodePayload, undefined, undefined, undefined, requestId)
.then((result) => {
atsMeasurement?.endMeasurement({
success: true,
});
return result;
})
.catch((error) => {
this.logger.verbose("Error in fetching token in ACC", request.correlationId);
atsMeasurement?.endMeasurement({
errorCode: error.errorCode,
subErrorCode: error.subError,
success: false,
});
throw error;
});
};
}
/**

@@ -123,9 +102,9 @@ * Handles the hash fragment response from public client code request. Returns a code response used by

*/
AuthorizationCodeClient.prototype.handleFragmentResponse = function (hashFragment, cachedState) {
handleFragmentResponse(hashFragment, cachedState) {
// Handle responses.
var responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, null, null);
const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, null, null);
// Deserialize hash fragment response parameters.
var hashUrlString = new UrlString(hashFragment);
const hashUrlString = new UrlString(hashFragment);
// Deserialize hash fragment response parameters.
var serverParams = UrlString.getDeserializedHash(hashUrlString.getHash());
const serverParams = UrlString.getDeserializedHash(hashUrlString.getHash());
// Get code response

@@ -137,6 +116,8 @@ responseHandler.validateServerAuthorizationCodeResponse(serverParams, cachedState, this.cryptoUtils);

}
return __assign(__assign({}, serverParams), {
return {
...serverParams,
// Code param is optional in ServerAuthorizationCodeResponse but required in AuthorizationCodePaylod
code: serverParams.code });
};
code: serverParams.code,
};
}
/**

@@ -147,3 +128,3 @@ * Used to log out the current user, and redirect the user to the postLogoutRedirectUri.

*/
AuthorizationCodeClient.prototype.getLogoutUri = function (logoutRequest) {
getLogoutUri(logoutRequest) {
// Throw error if logoutRequest is null/undefined

@@ -153,6 +134,6 @@ if (!logoutRequest) {

}
var queryString = this.createLogoutUrlQueryString(logoutRequest);
const queryString = this.createLogoutUrlQueryString(logoutRequest);
// Construct logout URI
return UrlString.appendQueryString(this.authority.endSessionEndpoint, queryString);
};
}
/**

@@ -163,46 +144,35 @@ * Executes POST request to token endpoint

*/
AuthorizationCodeClient.prototype.executeTokenRequest = function (authority, request) {
var _a, _b;
return __awaiter(this, void 0, void 0, function () {
var queryParametersString, endpoint, requestBody, ccsCredential, clientInfo, headers, thumbprint;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
(_a = this.performanceClient) === null || _a === void 0 ? void 0 : _a.addQueueMeasurement(PerformanceEvents.AuthClientExecuteTokenRequest, request.correlationId);
(_b = this.performanceClient) === null || _b === void 0 ? void 0 : _b.setPreQueueTime(PerformanceEvents.AuthClientCreateTokenRequestBody, request.correlationId);
queryParametersString = this.createTokenQueryParameters(request);
endpoint = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString);
return [4 /*yield*/, this.createTokenRequestBody(request)];
case 1:
requestBody = _c.sent();
ccsCredential = undefined;
if (request.clientInfo) {
try {
clientInfo = buildClientInfo(request.clientInfo, this.cryptoUtils);
ccsCredential = {
credential: "" + clientInfo.uid + Separators.CLIENT_INFO_SEPARATOR + clientInfo.utid,
type: CcsCredentialType.HOME_ACCOUNT_ID
};
}
catch (e) {
this.logger.verbose("Could not parse client info for CCS Header: " + e);
}
}
headers = this.createTokenRequestHeaders(ccsCredential || request.ccsCredential);
thumbprint = {
clientId: this.config.authOptions.clientId,
authority: authority.canonicalAuthority,
scopes: request.scopes,
claims: request.claims,
authenticationScheme: request.authenticationScheme,
resourceRequestMethod: request.resourceRequestMethod,
resourceRequestUri: request.resourceRequestUri,
shrClaims: request.shrClaims,
sshKid: request.sshKid
};
return [2 /*return*/, this.executePostToTokenEndpoint(endpoint, requestBody, headers, thumbprint)];
}
});
});
};
async executeTokenRequest(authority, request) {
this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthClientExecuteTokenRequest, request.correlationId);
this.performanceClient?.setPreQueueTime(PerformanceEvents.AuthClientCreateTokenRequestBody, request.correlationId);
const queryParametersString = this.createTokenQueryParameters(request);
const endpoint = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString);
const requestBody = await this.createTokenRequestBody(request);
let ccsCredential = undefined;
if (request.clientInfo) {
try {
const clientInfo = buildClientInfo(request.clientInfo, this.cryptoUtils);
ccsCredential = {
credential: `${clientInfo.uid}${Separators.CLIENT_INFO_SEPARATOR}${clientInfo.utid}`,
type: CcsCredentialType.HOME_ACCOUNT_ID,
};
}
catch (e) {
this.logger.verbose("Could not parse client info for CCS Header: " + e);
}
}
const headers = this.createTokenRequestHeaders(ccsCredential || request.ccsCredential);
const thumbprint = {
clientId: this.config.authOptions.clientId,
authority: authority.canonicalAuthority,
scopes: request.scopes,
claims: request.claims,
authenticationScheme: request.authenticationScheme,
resourceRequestMethod: request.resourceRequestMethod,
resourceRequestUri: request.resourceRequestUri,
shrClaims: request.shrClaims,
sshKid: request.sshKid,
};
return this.executePostToTokenEndpoint(endpoint, requestBody, headers, thumbprint);
}
/**

@@ -212,122 +182,113 @@ * Generates a map for all the params to be sent to the service

*/
AuthorizationCodeClient.prototype.createTokenRequestBody = function (request) {
var _a, _b;
return __awaiter(this, void 0, void 0, function () {
var parameterBuilder, clientAssertion, popTokenGenerator, reqCnfData, correlationId, ccsCred, clientInfo, clientInfo;
var _c;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
(_a = this.performanceClient) === null || _a === void 0 ? void 0 : _a.addQueueMeasurement(PerformanceEvents.AuthClientCreateTokenRequestBody, request.correlationId);
parameterBuilder = new RequestParameterBuilder();
parameterBuilder.addClientId(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
RequestValidator.validateRedirectUri(request.redirectUri);
}
else {
// Validate and include redirect uri
parameterBuilder.addRedirectUri(request.redirectUri);
}
// Add scope array, parameter builder will add default scopes and dedupe
parameterBuilder.addScopes(request.scopes);
// add code: user set, not validated
parameterBuilder.addAuthorizationCode(request.code);
// Add library metadata
parameterBuilder.addLibraryInfo(this.config.libraryInfo);
parameterBuilder.addApplicationTelemetry(this.config.telemetry.application);
parameterBuilder.addThrottling();
if (this.serverTelemetryManager) {
parameterBuilder.addServerTelemetry(this.serverTelemetryManager);
}
// add code_verifier if passed
if (request.codeVerifier) {
parameterBuilder.addCodeVerifier(request.codeVerifier);
}
if (this.config.clientCredentials.clientSecret) {
parameterBuilder.addClientSecret(this.config.clientCredentials.clientSecret);
}
if (this.config.clientCredentials.clientAssertion) {
clientAssertion = this.config.clientCredentials.clientAssertion;
parameterBuilder.addClientAssertion(clientAssertion.assertion);
parameterBuilder.addClientAssertionType(clientAssertion.assertionType);
}
parameterBuilder.addGrantType(GrantType.AUTHORIZATION_CODE_GRANT);
parameterBuilder.addClientInfo();
if (!(request.authenticationScheme === AuthenticationScheme.POP)) return [3 /*break*/, 2];
popTokenGenerator = new PopTokenGenerator(this.cryptoUtils, this.performanceClient);
(_b = this.performanceClient) === null || _b === void 0 ? void 0 : _b.setPreQueueTime(PerformanceEvents.PopTokenGenerateCnf, request.correlationId);
return [4 /*yield*/, popTokenGenerator.generateCnf(request)];
case 1:
reqCnfData = _d.sent();
// SPA PoP requires full Base64Url encoded req_cnf string (unhashed)
parameterBuilder.addPopToken(reqCnfData.reqCnfString);
return [3 /*break*/, 3];
case 2:
if (request.authenticationScheme === AuthenticationScheme.SSH) {
if (request.sshJwk) {
parameterBuilder.addSshJwk(request.sshJwk);
}
else {
throw ClientConfigurationError.createMissingSshJwkError();
}
}
_d.label = 3;
case 3:
correlationId = request.correlationId || this.config.cryptoInterface.createNewGuid();
parameterBuilder.addCorrelationId(correlationId);
if (!StringUtils.isEmptyObj(request.claims) || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) {
parameterBuilder.addClaims(request.claims, this.config.authOptions.clientCapabilities);
}
ccsCred = undefined;
if (request.clientInfo) {
try {
clientInfo = buildClientInfo(request.clientInfo, this.cryptoUtils);
ccsCred = {
credential: "" + clientInfo.uid + Separators.CLIENT_INFO_SEPARATOR + clientInfo.utid,
type: CcsCredentialType.HOME_ACCOUNT_ID
};
}
catch (e) {
this.logger.verbose("Could not parse client info for CCS Header: " + e);
}
}
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 {
clientInfo = buildClientInfoFromHomeAccountId(ccsCred.credential);
parameterBuilder.addCcsOid(clientInfo);
}
catch (e) {
this.logger.verbose("Could not parse home account ID for CCS Header: " + e);
}
break;
case CcsCredentialType.UPN:
parameterBuilder.addCcsUpn(ccsCred.credential);
break;
}
}
if (request.tokenBodyParameters) {
parameterBuilder.addExtraQueryParameters(request.tokenBodyParameters);
}
// Add hybrid spa parameters if not already provided
if (request.enableSpaAuthorizationCode && (!request.tokenBodyParameters || !request.tokenBodyParameters[AADServerParamKeys.RETURN_SPA_CODE])) {
parameterBuilder.addExtraQueryParameters((_c = {},
_c[AADServerParamKeys.RETURN_SPA_CODE] = "1",
_c));
}
return [2 /*return*/, parameterBuilder.createQueryString()];
}
async createTokenRequestBody(request) {
this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthClientCreateTokenRequestBody, request.correlationId);
const parameterBuilder = new RequestParameterBuilder();
parameterBuilder.addClientId(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
RequestValidator.validateRedirectUri(request.redirectUri);
}
else {
// Validate and include redirect uri
parameterBuilder.addRedirectUri(request.redirectUri);
}
// Add scope array, parameter builder will add default scopes and dedupe
parameterBuilder.addScopes(request.scopes);
// add code: user set, not validated
parameterBuilder.addAuthorizationCode(request.code);
// Add library metadata
parameterBuilder.addLibraryInfo(this.config.libraryInfo);
parameterBuilder.addApplicationTelemetry(this.config.telemetry.application);
parameterBuilder.addThrottling();
if (this.serverTelemetryManager) {
parameterBuilder.addServerTelemetry(this.serverTelemetryManager);
}
// add code_verifier if passed
if (request.codeVerifier) {
parameterBuilder.addCodeVerifier(request.codeVerifier);
}
if (this.config.clientCredentials.clientSecret) {
parameterBuilder.addClientSecret(this.config.clientCredentials.clientSecret);
}
if (this.config.clientCredentials.clientAssertion) {
const clientAssertion = this.config.clientCredentials.clientAssertion;
parameterBuilder.addClientAssertion(clientAssertion.assertion);
parameterBuilder.addClientAssertionType(clientAssertion.assertionType);
}
parameterBuilder.addGrantType(GrantType.AUTHORIZATION_CODE_GRANT);
parameterBuilder.addClientInfo();
if (request.authenticationScheme === AuthenticationScheme.POP) {
const popTokenGenerator = new PopTokenGenerator(this.cryptoUtils, this.performanceClient);
this.performanceClient?.setPreQueueTime(PerformanceEvents.PopTokenGenerateCnf, request.correlationId);
const reqCnfData = await popTokenGenerator.generateCnf(request);
// SPA PoP requires full Base64Url encoded req_cnf string (unhashed)
parameterBuilder.addPopToken(reqCnfData.reqCnfString);
}
else if (request.authenticationScheme === AuthenticationScheme.SSH) {
if (request.sshJwk) {
parameterBuilder.addSshJwk(request.sshJwk);
}
else {
throw ClientConfigurationError.createMissingSshJwkError();
}
}
const correlationId = request.correlationId ||
this.config.cryptoInterface.createNewGuid();
parameterBuilder.addCorrelationId(correlationId);
if (!StringUtils.isEmptyObj(request.claims) ||
(this.config.authOptions.clientCapabilities &&
this.config.authOptions.clientCapabilities.length > 0)) {
parameterBuilder.addClaims(request.claims, this.config.authOptions.clientCapabilities);
}
let ccsCred = undefined;
if (request.clientInfo) {
try {
const clientInfo = buildClientInfo(request.clientInfo, this.cryptoUtils);
ccsCred = {
credential: `${clientInfo.uid}${Separators.CLIENT_INFO_SEPARATOR}${clientInfo.utid}`,
type: CcsCredentialType.HOME_ACCOUNT_ID,
};
}
catch (e) {
this.logger.verbose("Could not parse client info for CCS Header: " + e);
}
}
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);
parameterBuilder.addCcsOid(clientInfo);
}
catch (e) {
this.logger.verbose("Could not parse home account ID for CCS Header: " +
e);
}
break;
case CcsCredentialType.UPN:
parameterBuilder.addCcsUpn(ccsCred.credential);
break;
}
}
if (request.tokenBodyParameters) {
parameterBuilder.addExtraQueryParameters(request.tokenBodyParameters);
}
// Add hybrid spa parameters if not already provided
if (request.enableSpaAuthorizationCode &&
(!request.tokenBodyParameters ||
!request.tokenBodyParameters[AADServerParamKeys.RETURN_SPA_CODE])) {
parameterBuilder.addExtraQueryParameters({
[AADServerParamKeys.RETURN_SPA_CODE]: "1",
});
});
};
}
return parameterBuilder.createQueryString();
}
/**

@@ -337,128 +298,127 @@ * This API validates the `AuthorizationCodeUrlRequest` and creates a URL

*/
AuthorizationCodeClient.prototype.createAuthCodeUrlQueryString = function (request) {
var _a;
return __awaiter(this, void 0, void 0, function () {
var parameterBuilder, requestScopes, correlationId, accountSid, accountLoginHintClaim, clientInfo, clientInfo, clientInfo, popTokenGenerator, reqCnfData;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
(_a = this.performanceClient) === null || _a === void 0 ? void 0 : _a.addQueueMeasurement(PerformanceEvents.AuthClientCreateQueryString, request.correlationId);
parameterBuilder = new RequestParameterBuilder();
parameterBuilder.addClientId(this.config.authOptions.clientId);
requestScopes = __spreadArrays(request.scopes || [], request.extraScopesToConsent || []);
parameterBuilder.addScopes(requestScopes);
// validate the redirectUri (to be a non null value)
parameterBuilder.addRedirectUri(request.redirectUri);
correlationId = request.correlationId || this.config.cryptoInterface.createNewGuid();
parameterBuilder.addCorrelationId(correlationId);
// add response_mode. If not passed in it defaults to query.
parameterBuilder.addResponseMode(request.responseMode);
// add response_type = code
parameterBuilder.addResponseTypeCode();
// add library info parameters
parameterBuilder.addLibraryInfo(this.config.libraryInfo);
parameterBuilder.addApplicationTelemetry(this.config.telemetry.application);
// add client_info=1
parameterBuilder.addClientInfo();
if (request.codeChallenge && request.codeChallengeMethod) {
parameterBuilder.addCodeChallengeParams(request.codeChallenge, request.codeChallengeMethod);
}
if (request.prompt) {
parameterBuilder.addPrompt(request.prompt);
}
if (request.domainHint) {
parameterBuilder.addDomainHint(request.domainHint);
}
// Add sid or loginHint with preference for login_hint claim (in request) -> sid -> loginHint (upn/email) -> username of AccountInfo object
if (request.prompt !== PromptValue.SELECT_ACCOUNT) {
// AAD will throw if prompt=select_account is passed with an account hint
if (request.sid && request.prompt === PromptValue.NONE) {
// SessionID is only used in silent calls
this.logger.verbose("createAuthCodeUrlQueryString: Prompt is none, adding sid from request");
parameterBuilder.addSid(request.sid);
}
else if (request.account) {
accountSid = this.extractAccountSid(request.account);
accountLoginHintClaim = this.extractLoginHint(request.account);
// If login_hint claim is present, use it over sid/username
if (accountLoginHintClaim) {
this.logger.verbose("createAuthCodeUrlQueryString: login_hint claim present on account");
parameterBuilder.addLoginHint(accountLoginHintClaim);
try {
clientInfo = buildClientInfoFromHomeAccountId(request.account.homeAccountId);
parameterBuilder.addCcsOid(clientInfo);
}
catch (e) {
this.logger.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header");
}
}
else if (accountSid && request.prompt === PromptValue.NONE) {
/*
* If account and loginHint are provided, we will check account first for sid before adding loginHint
* SessionId is only used in silent calls
*/
this.logger.verbose("createAuthCodeUrlQueryString: Prompt is none, adding sid from account");
parameterBuilder.addSid(accountSid);
try {
clientInfo = buildClientInfoFromHomeAccountId(request.account.homeAccountId);
parameterBuilder.addCcsOid(clientInfo);
}
catch (e) {
this.logger.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header");
}
}
else if (request.loginHint) {
this.logger.verbose("createAuthCodeUrlQueryString: Adding login_hint from request");
parameterBuilder.addLoginHint(request.loginHint);
parameterBuilder.addCcsUpn(request.loginHint);
}
else if (request.account.username) {
// Fallback to account username if provided
this.logger.verbose("createAuthCodeUrlQueryString: Adding login_hint from account");
parameterBuilder.addLoginHint(request.account.username);
try {
clientInfo = buildClientInfoFromHomeAccountId(request.account.homeAccountId);
parameterBuilder.addCcsOid(clientInfo);
}
catch (e) {
this.logger.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header");
}
}
}
else if (request.loginHint) {
this.logger.verbose("createAuthCodeUrlQueryString: No account, adding login_hint from request");
parameterBuilder.addLoginHint(request.loginHint);
parameterBuilder.addCcsUpn(request.loginHint);
}
}
else {
this.logger.verbose("createAuthCodeUrlQueryString: Prompt is select_account, ignoring account hints");
}
if (request.nonce) {
parameterBuilder.addNonce(request.nonce);
}
if (request.state) {
parameterBuilder.addState(request.state);
}
if (!StringUtils.isEmpty(request.claims) || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) {
parameterBuilder.addClaims(request.claims, this.config.authOptions.clientCapabilities);
}
if (request.extraQueryParameters) {
parameterBuilder.addExtraQueryParameters(request.extraQueryParameters);
}
if (!request.nativeBroker) return [3 /*break*/, 2];
// signal ests that this is a WAM call
parameterBuilder.addNativeBroker();
if (!(request.authenticationScheme === AuthenticationScheme.POP)) return [3 /*break*/, 2];
popTokenGenerator = new PopTokenGenerator(this.cryptoUtils);
return [4 /*yield*/, popTokenGenerator.generateCnf(request)];
case 1:
reqCnfData = _b.sent();
parameterBuilder.addPopToken(reqCnfData.reqCnfHash);
_b.label = 2;
case 2: return [2 /*return*/, parameterBuilder.createQueryString()];
async createAuthCodeUrlQueryString(request) {
this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthClientCreateQueryString, request.correlationId);
const parameterBuilder = new RequestParameterBuilder();
parameterBuilder.addClientId(this.config.authOptions.clientId);
const requestScopes = [
...(request.scopes || []),
...(request.extraScopesToConsent || []),
];
parameterBuilder.addScopes(requestScopes);
// validate the redirectUri (to be a non null value)
parameterBuilder.addRedirectUri(request.redirectUri);
// generate the correlationId if not set by the user and add
const correlationId = request.correlationId ||
this.config.cryptoInterface.createNewGuid();
parameterBuilder.addCorrelationId(correlationId);
// add response_mode. If not passed in it defaults to query.
parameterBuilder.addResponseMode(request.responseMode);
// add response_type = code
parameterBuilder.addResponseTypeCode();
// add library info parameters
parameterBuilder.addLibraryInfo(this.config.libraryInfo);
parameterBuilder.addApplicationTelemetry(this.config.telemetry.application);
// add client_info=1
parameterBuilder.addClientInfo();
if (request.codeChallenge && request.codeChallengeMethod) {
parameterBuilder.addCodeChallengeParams(request.codeChallenge, request.codeChallengeMethod);
}
if (request.prompt) {
parameterBuilder.addPrompt(request.prompt);
}
if (request.domainHint) {
parameterBuilder.addDomainHint(request.domainHint);
}
// Add sid or loginHint with preference for login_hint claim (in request) -> sid -> loginHint (upn/email) -> username of AccountInfo object
if (request.prompt !== PromptValue.SELECT_ACCOUNT) {
// AAD will throw if prompt=select_account is passed with an account hint
if (request.sid && request.prompt === PromptValue.NONE) {
// SessionID is only used in silent calls
this.logger.verbose("createAuthCodeUrlQueryString: Prompt is none, adding sid from request");
parameterBuilder.addSid(request.sid);
}
else if (request.account) {
const accountSid = this.extractAccountSid(request.account);
const accountLoginHintClaim = this.extractLoginHint(request.account);
// If login_hint claim is present, use it over sid/username
if (accountLoginHintClaim) {
this.logger.verbose("createAuthCodeUrlQueryString: login_hint claim present on account");
parameterBuilder.addLoginHint(accountLoginHintClaim);
try {
const clientInfo = buildClientInfoFromHomeAccountId(request.account.homeAccountId);
parameterBuilder.addCcsOid(clientInfo);
}
catch (e) {
this.logger.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header");
}
}
});
});
};
else if (accountSid && request.prompt === PromptValue.NONE) {
/*
* If account and loginHint are provided, we will check account first for sid before adding loginHint
* SessionId is only used in silent calls
*/
this.logger.verbose("createAuthCodeUrlQueryString: Prompt is none, adding sid from account");
parameterBuilder.addSid(accountSid);
try {
const clientInfo = buildClientInfoFromHomeAccountId(request.account.homeAccountId);
parameterBuilder.addCcsOid(clientInfo);
}
catch (e) {
this.logger.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header");
}
}
else if (request.loginHint) {
this.logger.verbose("createAuthCodeUrlQueryString: Adding login_hint from request");
parameterBuilder.addLoginHint(request.loginHint);
parameterBuilder.addCcsUpn(request.loginHint);
}
else if (request.account.username) {
// Fallback to account username if provided
this.logger.verbose("createAuthCodeUrlQueryString: Adding login_hint from account");
parameterBuilder.addLoginHint(request.account.username);
try {
const clientInfo = buildClientInfoFromHomeAccountId(request.account.homeAccountId);
parameterBuilder.addCcsOid(clientInfo);
}
catch (e) {
this.logger.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header");
}
}
}
else if (request.loginHint) {
this.logger.verbose("createAuthCodeUrlQueryString: No account, adding login_hint from request");
parameterBuilder.addLoginHint(request.loginHint);
parameterBuilder.addCcsUpn(request.loginHint);
}
}
else {
this.logger.verbose("createAuthCodeUrlQueryString: Prompt is select_account, ignoring account hints");
}
if (request.nonce) {
parameterBuilder.addNonce(request.nonce);
}
if (request.state) {
parameterBuilder.addState(request.state);
}
if (!StringUtils.isEmpty(request.claims) ||
(this.config.authOptions.clientCapabilities &&
this.config.authOptions.clientCapabilities.length > 0)) {
parameterBuilder.addClaims(request.claims, this.config.authOptions.clientCapabilities);
}
if (request.extraQueryParameters) {
parameterBuilder.addExtraQueryParameters(request.extraQueryParameters);
}
if (request.nativeBroker) {
// signal ests that this is a WAM call
parameterBuilder.addNativeBroker();
// pass the req_cnf for POP
if (request.authenticationScheme === AuthenticationScheme.POP) {
const popTokenGenerator = new PopTokenGenerator(this.cryptoUtils);
// to reduce the URL length, it is recommended to send the hash of the req_cnf instead of the whole string
const reqCnfData = await popTokenGenerator.generateCnf(request);
parameterBuilder.addPopToken(reqCnfData.reqCnfHash);
}
}
return parameterBuilder.createQueryString();
}
/**

@@ -468,4 +428,4 @@ * This API validates the `EndSessionRequest` and creates a URL

*/
AuthorizationCodeClient.prototype.createLogoutUrlQueryString = function (request) {
var parameterBuilder = new RequestParameterBuilder();
createLogoutUrlQueryString(request) {
const parameterBuilder = new RequestParameterBuilder();
if (request.postLogoutRedirectUri) {

@@ -490,3 +450,3 @@ parameterBuilder.addPostLogoutRedirectUri(request.postLogoutRedirectUri);

return parameterBuilder.createQueryString();
};
}
/**

@@ -496,14 +456,11 @@ * Helper to get sid from account. Returns null if idTokenClaims are not present or sid is not present.

*/
AuthorizationCodeClient.prototype.extractAccountSid = function (account) {
var _a;
return ((_a = account.idTokenClaims) === null || _a === void 0 ? void 0 : _a.sid) || null;
};
AuthorizationCodeClient.prototype.extractLoginHint = function (account) {
var _a;
return ((_a = account.idTokenClaims) === null || _a === void 0 ? void 0 : _a.login_hint) || null;
};
return AuthorizationCodeClient;
}(BaseClient));
extractAccountSid(account) {
return account.idTokenClaims?.sid || null;
}
extractLoginHint(account) {
return account.idTokenClaims?.login_hint || null;
}
}
export { AuthorizationCodeClient };
//# sourceMappingURL=AuthorizationCodeClient.js.map

@@ -1,4 +0,3 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';
import { __awaiter, __generator } from '../_virtual/_tslib.js';
import { buildClientConfiguration } from '../config/ClientConfiguration.js';

@@ -21,4 +20,4 @@ import { NetworkManager } from '../network/NetworkManager.js';

*/
var BaseClient = /** @class */ (function () {
function BaseClient(configuration, performanceClient) {
class BaseClient {
constructor(configuration, performanceClient) {
// Set the configuration

@@ -46,4 +45,4 @@ this.config = buildClientConfiguration(configuration);

*/
BaseClient.prototype.createTokenRequestHeaders = function (ccsCred) {
var headers = {};
createTokenRequestHeaders(ccsCred) {
const headers = {};
headers[HeaderNames.CONTENT_TYPE] = Constants.URL_FORM_CONTENT_TYPE;

@@ -54,11 +53,12 @@ if (!this.config.systemOptions.preventCorsPreflight && ccsCred) {

try {
var clientInfo = buildClientInfoFromHomeAccountId(ccsCred.credential);
headers[HeaderNames.CCS_HEADER] = "Oid:" + clientInfo.uid + "@" + clientInfo.utid;
const clientInfo = buildClientInfoFromHomeAccountId(ccsCred.credential);
headers[HeaderNames.CCS_HEADER] = `Oid:${clientInfo.uid}@${clientInfo.utid}`;
}
catch (e) {
this.logger.verbose("Could not parse home account ID for CCS Header: " + e);
this.logger.verbose("Could not parse home account ID for CCS Header: " +
e);
}
break;
case CcsCredentialType.UPN:
headers[HeaderNames.CCS_HEADER] = "UPN: " + ccsCred.credential;
headers[HeaderNames.CCS_HEADER] = `UPN: ${ccsCred.credential}`;
break;

@@ -68,3 +68,3 @@ }

return headers;
};
}
/**

@@ -77,19 +77,12 @@ * Http post to token endpoint

*/
BaseClient.prototype.executePostToTokenEndpoint = function (tokenEndpoint, queryString, headers, thumbprint) {
return __awaiter(this, void 0, void 0, function () {
var response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.networkManager.sendPostRequest(thumbprint, tokenEndpoint, { body: queryString, headers: headers })];
case 1:
response = _a.sent();
if (this.config.serverTelemetryManager && response.status < 500 && response.status !== 429) {
// Telemetry data successfully logged by server, clear Telemetry cache
this.config.serverTelemetryManager.clearTelemetryCache();
}
return [2 /*return*/, response];
}
});
});
};
async executePostToTokenEndpoint(tokenEndpoint, queryString, headers, thumbprint) {
const response = await this.networkManager.sendPostRequest(thumbprint, tokenEndpoint, { body: queryString, headers: headers });
if (this.config.serverTelemetryManager &&
response.status < 500 &&
response.status !== 429) {
// Telemetry data successfully logged by server, clear Telemetry cache
this.config.serverTelemetryManager.clearTelemetryCache();
}
return response;
}
/**

@@ -99,3 +92,3 @@ * Updates the authority object of the client. Endpoint discovery must be completed.

*/
BaseClient.prototype.updateAuthority = function (updatedAuthority) {
updateAuthority(updatedAuthority) {
if (!updatedAuthority.discoveryComplete()) {

@@ -105,3 +98,3 @@ throw ClientAuthError.createEndpointDiscoveryIncompleteError("Updated authority has not completed endpoint discovery.");

this.authority = updatedAuthority;
};
}
/**

@@ -111,4 +104,4 @@ * Creates query string for the /token request

*/
BaseClient.prototype.createTokenQueryParameters = function (request) {
var parameterBuilder = new RequestParameterBuilder();
createTokenQueryParameters(request) {
const parameterBuilder = new RequestParameterBuilder();
if (request.tokenQueryParameters) {

@@ -118,7 +111,6 @@ parameterBuilder.addExtraQueryParameters(request.tokenQueryParameters);

return parameterBuilder.createQueryString();
};
return BaseClient;
}());
}
}
export { BaseClient };
//# sourceMappingURL=BaseClient.js.map

@@ -1,7 +0,6 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';
import { __extends, __awaiter, __generator, __assign } from '../_virtual/_tslib.js';
import { BaseClient } from './BaseClient.js';
import { RequestParameterBuilder } from '../request/RequestParameterBuilder.js';
import { AuthenticationScheme, GrantType, HeaderNames, Errors } from '../utils/Constants.js';
import { GrantType, AuthenticationScheme, HeaderNames, Errors } from '../utils/Constants.js';
import { ResponseHandler } from '../response/ResponseHandler.js';

@@ -27,55 +26,45 @@ import { PopTokenGenerator } from '../crypto/PopTokenGenerator.js';

*/
var RefreshTokenClient = /** @class */ (function (_super) {
__extends(RefreshTokenClient, _super);
function RefreshTokenClient(configuration, performanceClient) {
return _super.call(this, configuration, performanceClient) || this;
class RefreshTokenClient extends BaseClient {
constructor(configuration, performanceClient) {
super(configuration, performanceClient);
}
RefreshTokenClient.prototype.acquireToken = function (request) {
var _a, _b, _c, _d, _e, _f, _g;
return __awaiter(this, void 0, void 0, function () {
var atsMeasurement, reqTimestamp, response, httpVerToken, requestId, responseHandler;
var _this = this;
return __generator(this, function (_h) {
switch (_h.label) {
case 0:
(_a = this.performanceClient) === null || _a === void 0 ? void 0 : _a.addQueueMeasurement(PerformanceEvents.RefreshTokenClientAcquireToken, request.correlationId);
atsMeasurement = (_b = this.performanceClient) === null || _b === void 0 ? void 0 : _b.startMeasurement(PerformanceEvents.RefreshTokenClientAcquireToken, request.correlationId);
this.logger.verbose("RefreshTokenClientAcquireToken called", request.correlationId);
reqTimestamp = TimeUtils.nowSeconds();
(_c = this.performanceClient) === null || _c === void 0 ? void 0 : _c.setPreQueueTime(PerformanceEvents.RefreshTokenClientExecuteTokenRequest, request.correlationId);
return [4 /*yield*/, this.executeTokenRequest(request, this.authority)];
case 1:
response = _h.sent();
httpVerToken = (_d = response.headers) === null || _d === void 0 ? void 0 : _d[HeaderNames.X_MS_HTTP_VERSION];
atsMeasurement === null || atsMeasurement === void 0 ? void 0 : atsMeasurement.addStaticFields({
refreshTokenSize: ((_e = response.body.refresh_token) === null || _e === void 0 ? void 0 : _e.length) || 0,
});
if (httpVerToken) {
atsMeasurement === null || atsMeasurement === void 0 ? void 0 : atsMeasurement.addStaticFields({
httpVerToken: httpVerToken,
});
}
requestId = (_f = response.headers) === null || _f === void 0 ? void 0 : _f[HeaderNames.X_MS_REQUEST_ID];
responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.config.serializableCache, this.config.persistencePlugin);
responseHandler.validateTokenResponse(response.body);
(_g = this.performanceClient) === null || _g === void 0 ? void 0 : _g.setPreQueueTime(PerformanceEvents.HandleServerTokenResponse, request.correlationId);
return [2 /*return*/, responseHandler.handleServerTokenResponse(response.body, this.authority, reqTimestamp, request, undefined, undefined, true, request.forceCache, requestId).then(function (result) {
atsMeasurement === null || atsMeasurement === void 0 ? void 0 : atsMeasurement.endMeasurement({
success: true
});
return result;
})
.catch(function (error) {
_this.logger.verbose("Error in fetching refresh token", request.correlationId);
atsMeasurement === null || atsMeasurement === void 0 ? void 0 : atsMeasurement.endMeasurement({
errorCode: error.errorCode,
subErrorCode: error.subError,
success: false
});
throw error;
})];
}
async acquireToken(request) {
this.performanceClient?.addQueueMeasurement(PerformanceEvents.RefreshTokenClientAcquireToken, request.correlationId);
const atsMeasurement = this.performanceClient?.startMeasurement(PerformanceEvents.RefreshTokenClientAcquireToken, request.correlationId);
this.logger.verbose("RefreshTokenClientAcquireToken called", request.correlationId);
const reqTimestamp = TimeUtils.nowSeconds();
this.performanceClient?.setPreQueueTime(PerformanceEvents.RefreshTokenClientExecuteTokenRequest, request.correlationId);
const response = await this.executeTokenRequest(request, this.authority);
const httpVerToken = response.headers?.[HeaderNames.X_MS_HTTP_VERSION];
atsMeasurement?.addStaticFields({
refreshTokenSize: response.body.refresh_token?.length || 0,
});
if (httpVerToken) {
atsMeasurement?.addStaticFields({
httpVerToken,
});
}
// 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.config.serializableCache, this.config.persistencePlugin);
responseHandler.validateTokenResponse(response.body);
this.performanceClient?.setPreQueueTime(PerformanceEvents.HandleServerTokenResponse, request.correlationId);
return responseHandler
.handleServerTokenResponse(response.body, this.authority, reqTimestamp, request, undefined, undefined, true, request.forceCache, requestId)
.then((result) => {
atsMeasurement?.endMeasurement({
success: true,
});
return result;
})
.catch((error) => {
this.logger.verbose("Error in fetching refresh token", request.correlationId);
atsMeasurement?.endMeasurement({
errorCode: error.errorCode,
subErrorCode: error.subError,
success: false,
});
throw error;
});
};
}
/**

@@ -85,43 +74,43 @@ * Gets cached refresh token and attaches to request, then calls acquireToken API

*/
RefreshTokenClient.prototype.acquireTokenByRefreshToken = function (request) {
var _a, _b, _c, _d;
return __awaiter(this, void 0, void 0, function () {
var isFOCI, noFamilyRTInCache, clientMismatchErrorWithFamilyRT;
return __generator(this, function (_e) {
// Cannot renew token if no request object is given.
if (!request) {
throw ClientConfigurationError.createEmptyTokenRequestError();
async acquireTokenByRefreshToken(request) {
// Cannot renew token if no request object is given.
if (!request) {
throw ClientConfigurationError.createEmptyTokenRequestError();
}
this.performanceClient?.addQueueMeasurement(PerformanceEvents.RefreshTokenClientAcquireTokenByRefreshToken, request.correlationId);
// We currently do not support silent flow for account === null use cases; This will be revisited for confidential flow usecases
if (!request.account) {
throw ClientAuthError.createNoAccountInSilentRequestError();
}
// try checking if FOCI is enabled for the given application
const isFOCI = this.cacheManager.isAppMetadataFOCI(request.account.environment);
// if the app is part of the family, retrive a Family refresh token if present and make a refreshTokenRequest
if (isFOCI) {
try {
this.performanceClient?.setPreQueueTime(PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken, request.correlationId);
return this.acquireTokenWithCachedRefreshToken(request, true);
}
catch (e) {
const noFamilyRTInCache = e instanceof InteractionRequiredAuthError &&
e.errorCode ===
InteractionRequiredAuthErrorMessage.noTokensFoundError
.code;
const clientMismatchErrorWithFamilyRT = e instanceof ServerError &&
e.errorCode === Errors.INVALID_GRANT_ERROR &&
e.subError === Errors.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) {
this.performanceClient?.setPreQueueTime(PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken, request.correlationId);
return this.acquireTokenWithCachedRefreshToken(request, false);
// throw in all other cases
}
(_a = this.performanceClient) === null || _a === void 0 ? void 0 : _a.addQueueMeasurement(PerformanceEvents.RefreshTokenClientAcquireTokenByRefreshToken, request.correlationId);
// We currently do not support silent flow for account === null use cases; This will be revisited for confidential flow usecases
if (!request.account) {
throw ClientAuthError.createNoAccountInSilentRequestError();
else {
throw e;
}
isFOCI = this.cacheManager.isAppMetadataFOCI(request.account.environment);
// if the app is part of the family, retrive a Family refresh token if present and make a refreshTokenRequest
if (isFOCI) {
try {
(_b = this.performanceClient) === null || _b === void 0 ? void 0 : _b.setPreQueueTime(PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken, request.correlationId);
return [2 /*return*/, this.acquireTokenWithCachedRefreshToken(request, true)];
}
catch (e) {
noFamilyRTInCache = e instanceof InteractionRequiredAuthError && e.errorCode === InteractionRequiredAuthErrorMessage.noTokensFoundError.code;
clientMismatchErrorWithFamilyRT = e instanceof ServerError && e.errorCode === Errors.INVALID_GRANT_ERROR && e.subError === Errors.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) {
(_c = this.performanceClient) === null || _c === void 0 ? void 0 : _c.setPreQueueTime(PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken, request.correlationId);
return [2 /*return*/, this.acquireTokenWithCachedRefreshToken(request, false)];
// throw in all other cases
}
else {
throw e;
}
}
}
// fall back to application refresh token acquisition
(_d = this.performanceClient) === null || _d === void 0 ? void 0 : _d.setPreQueueTime(PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken, request.correlationId);
return [2 /*return*/, this.acquireTokenWithCachedRefreshToken(request, false)];
});
});
};
}
}
// fall back to application refresh token acquisition
this.performanceClient?.setPreQueueTime(PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken, request.correlationId);
return this.acquireTokenWithCachedRefreshToken(request, false);
}
/**

@@ -131,28 +120,28 @@ * makes a network call to acquire tokens by exchanging RefreshToken available in userCache; throws if refresh token is not cached

*/
RefreshTokenClient.prototype.acquireTokenWithCachedRefreshToken = function (request, foci) {
var _a, _b, _c;
return __awaiter(this, void 0, void 0, function () {
var atsMeasurement, refreshToken, refreshTokenRequest;
return __generator(this, function (_d) {
(_a = this.performanceClient) === null || _a === void 0 ? void 0 : _a.addQueueMeasurement(PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken, request.correlationId);
atsMeasurement = (_b = this.performanceClient) === null || _b === void 0 ? void 0 : _b.startMeasurement(PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken, request.correlationId);
this.logger.verbose("RefreshTokenClientAcquireTokenWithCachedRefreshToken called", request.correlationId);
refreshToken = this.cacheManager.getRefreshToken(request.account, foci);
if (!refreshToken) {
atsMeasurement === null || atsMeasurement === void 0 ? void 0 : atsMeasurement.discardMeasurement();
throw InteractionRequiredAuthError.createNoTokensFoundError();
}
// attach cached RT size to the current measurement
atsMeasurement === null || atsMeasurement === void 0 ? void 0 : atsMeasurement.endMeasurement({
success: true
});
refreshTokenRequest = __assign(__assign({}, request), { refreshToken: refreshToken.secret, authenticationScheme: request.authenticationScheme || AuthenticationScheme.BEARER, ccsCredential: {
credential: request.account.homeAccountId,
type: CcsCredentialType.HOME_ACCOUNT_ID
} });
(_c = this.performanceClient) === null || _c === void 0 ? void 0 : _c.setPreQueueTime(PerformanceEvents.RefreshTokenClientAcquireToken, request.correlationId);
return [2 /*return*/, this.acquireToken(refreshTokenRequest)];
});
async acquireTokenWithCachedRefreshToken(request, foci) {
this.performanceClient?.addQueueMeasurement(PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken, request.correlationId);
// fetches family RT or application RT based on FOCI value
const atsMeasurement = this.performanceClient?.startMeasurement(PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken, request.correlationId);
this.logger.verbose("RefreshTokenClientAcquireTokenWithCachedRefreshToken called", request.correlationId);
const refreshToken = this.cacheManager.getRefreshToken(request.account, foci);
if (!refreshToken) {
atsMeasurement?.discardMeasurement();
throw InteractionRequiredAuthError.createNoTokensFoundError();
}
// attach cached RT size to the current measurement
atsMeasurement?.endMeasurement({
success: true,
});
};
const refreshTokenRequest = {
...request,
refreshToken: refreshToken.secret,
authenticationScheme: request.authenticationScheme || AuthenticationScheme.BEARER,
ccsCredential: {
credential: request.account.homeAccountId,
type: CcsCredentialType.HOME_ACCOUNT_ID,
},
};
this.performanceClient?.setPreQueueTime(PerformanceEvents.RefreshTokenClientAcquireToken, request.correlationId);
return this.acquireToken(refreshTokenRequest);
}
/**

@@ -163,46 +152,35 @@ * Constructs the network message and makes a NW call to the underlying secure token service

*/
RefreshTokenClient.prototype.executeTokenRequest = function (request, authority) {
var _a, _b, _c;
return __awaiter(this, void 0, void 0, function () {
var acquireTokenMeasurement, queryParametersString, endpoint, requestBody, headers, thumbprint;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
(_a = this.performanceClient) === null || _a === void 0 ? void 0 : _a.addQueueMeasurement(PerformanceEvents.RefreshTokenClientExecuteTokenRequest, request.correlationId);
acquireTokenMeasurement = (_b = this.performanceClient) === null || _b === void 0 ? void 0 : _b.startMeasurement(PerformanceEvents.RefreshTokenClientExecuteTokenRequest, request.correlationId);
(_c = this.performanceClient) === null || _c === void 0 ? void 0 : _c.setPreQueueTime(PerformanceEvents.RefreshTokenClientCreateTokenRequestBody, request.correlationId);
queryParametersString = this.createTokenQueryParameters(request);
endpoint = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString);
return [4 /*yield*/, this.createTokenRequestBody(request)];
case 1:
requestBody = _d.sent();
headers = this.createTokenRequestHeaders(request.ccsCredential);
thumbprint = {
clientId: this.config.authOptions.clientId,
authority: authority.canonicalAuthority,
scopes: request.scopes,
claims: request.claims,
authenticationScheme: request.authenticationScheme,
resourceRequestMethod: request.resourceRequestMethod,
resourceRequestUri: request.resourceRequestUri,
shrClaims: request.shrClaims,
sshKid: request.sshKid
};
return [2 /*return*/, this.executePostToTokenEndpoint(endpoint, requestBody, headers, thumbprint)
.then(function (result) {
acquireTokenMeasurement === null || acquireTokenMeasurement === void 0 ? void 0 : acquireTokenMeasurement.endMeasurement({
success: true
});
return result;
})
.catch(function (error) {
acquireTokenMeasurement === null || acquireTokenMeasurement === void 0 ? void 0 : acquireTokenMeasurement.endMeasurement({
success: false
});
throw error;
})];
}
async executeTokenRequest(request, authority) {
this.performanceClient?.addQueueMeasurement(PerformanceEvents.RefreshTokenClientExecuteTokenRequest, request.correlationId);
const acquireTokenMeasurement = this.performanceClient?.startMeasurement(PerformanceEvents.RefreshTokenClientExecuteTokenRequest, request.correlationId);
this.performanceClient?.setPreQueueTime(PerformanceEvents.RefreshTokenClientCreateTokenRequestBody, request.correlationId);
const queryParametersString = this.createTokenQueryParameters(request);
const endpoint = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString);
const requestBody = await this.createTokenRequestBody(request);
const headers = this.createTokenRequestHeaders(request.ccsCredential);
const thumbprint = {
clientId: this.config.authOptions.clientId,
authority: authority.canonicalAuthority,
scopes: request.scopes,
claims: request.claims,
authenticationScheme: request.authenticationScheme,
resourceRequestMethod: request.resourceRequestMethod,
resourceRequestUri: request.resourceRequestUri,
shrClaims: request.shrClaims,
sshKid: request.sshKid,
};
return this.executePostToTokenEndpoint(endpoint, requestBody, headers, thumbprint)
.then((result) => {
acquireTokenMeasurement?.endMeasurement({
success: true,
});
return result;
})
.catch((error) => {
acquireTokenMeasurement?.endMeasurement({
success: false,
});
throw error;
});
};
}
/**

@@ -212,87 +190,76 @@ * Helper function to create the token request body

*/
RefreshTokenClient.prototype.createTokenRequestBody = function (request) {
var _a, _b, _c;
return __awaiter(this, void 0, void 0, function () {
var correlationId, acquireTokenMeasurement, parameterBuilder, clientAssertion, popTokenGenerator, reqCnfData, clientInfo;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
(_a = this.performanceClient) === null || _a === void 0 ? void 0 : _a.addQueueMeasurement(PerformanceEvents.RefreshTokenClientCreateTokenRequestBody, request.correlationId);
correlationId = request.correlationId;
acquireTokenMeasurement = (_b = this.performanceClient) === null || _b === void 0 ? void 0 : _b.startMeasurement(PerformanceEvents.BaseClientCreateTokenRequestHeaders, correlationId);
parameterBuilder = new RequestParameterBuilder();
parameterBuilder.addClientId(this.config.authOptions.clientId);
parameterBuilder.addScopes(request.scopes);
parameterBuilder.addGrantType(GrantType.REFRESH_TOKEN_GRANT);
parameterBuilder.addClientInfo();
parameterBuilder.addLibraryInfo(this.config.libraryInfo);
parameterBuilder.addApplicationTelemetry(this.config.telemetry.application);
parameterBuilder.addThrottling();
if (this.serverTelemetryManager) {
parameterBuilder.addServerTelemetry(this.serverTelemetryManager);
}
parameterBuilder.addCorrelationId(correlationId);
parameterBuilder.addRefreshToken(request.refreshToken);
if (this.config.clientCredentials.clientSecret) {
parameterBuilder.addClientSecret(this.config.clientCredentials.clientSecret);
}
if (this.config.clientCredentials.clientAssertion) {
clientAssertion = this.config.clientCredentials.clientAssertion;
parameterBuilder.addClientAssertion(clientAssertion.assertion);
parameterBuilder.addClientAssertionType(clientAssertion.assertionType);
}
if (!(request.authenticationScheme === AuthenticationScheme.POP)) return [3 /*break*/, 2];
popTokenGenerator = new PopTokenGenerator(this.cryptoUtils, this.performanceClient);
(_c = this.performanceClient) === null || _c === void 0 ? void 0 : _c.setPreQueueTime(PerformanceEvents.PopTokenGenerateCnf, request.correlationId);
return [4 /*yield*/, popTokenGenerator.generateCnf(request)];
case 1:
reqCnfData = _d.sent();
// SPA PoP requires full Base64Url encoded req_cnf string (unhashed)
parameterBuilder.addPopToken(reqCnfData.reqCnfString);
return [3 /*break*/, 3];
case 2:
if (request.authenticationScheme === AuthenticationScheme.SSH) {
if (request.sshJwk) {
parameterBuilder.addSshJwk(request.sshJwk);
}
else {
acquireTokenMeasurement === null || acquireTokenMeasurement === void 0 ? void 0 : acquireTokenMeasurement.endMeasurement({
success: false
});
throw ClientConfigurationError.createMissingSshJwkError();
}
}
_d.label = 3;
case 3:
if (!StringUtils.isEmptyObj(request.claims) || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) {
parameterBuilder.addClaims(request.claims, this.config.authOptions.clientCapabilities);
}
if (this.config.systemOptions.preventCorsPreflight && request.ccsCredential) {
switch (request.ccsCredential.type) {
case CcsCredentialType.HOME_ACCOUNT_ID:
try {
clientInfo = buildClientInfoFromHomeAccountId(request.ccsCredential.credential);
parameterBuilder.addCcsOid(clientInfo);
}
catch (e) {
this.logger.verbose("Could not parse home account ID for CCS Header: " + e);
}
break;
case CcsCredentialType.UPN:
parameterBuilder.addCcsUpn(request.ccsCredential.credential);
break;
}
}
acquireTokenMeasurement === null || acquireTokenMeasurement === void 0 ? void 0 : acquireTokenMeasurement.endMeasurement({
success: true
});
return [2 /*return*/, parameterBuilder.createQueryString()];
}
});
async createTokenRequestBody(request) {
this.performanceClient?.addQueueMeasurement(PerformanceEvents.RefreshTokenClientCreateTokenRequestBody, request.correlationId);
const correlationId = request.correlationId;
const acquireTokenMeasurement = this.performanceClient?.startMeasurement(PerformanceEvents.BaseClientCreateTokenRequestHeaders, correlationId);
const parameterBuilder = new RequestParameterBuilder();
parameterBuilder.addClientId(this.config.authOptions.clientId);
parameterBuilder.addScopes(request.scopes);
parameterBuilder.addGrantType(GrantType.REFRESH_TOKEN_GRANT);
parameterBuilder.addClientInfo();
parameterBuilder.addLibraryInfo(this.config.libraryInfo);
parameterBuilder.addApplicationTelemetry(this.config.telemetry.application);
parameterBuilder.addThrottling();
if (this.serverTelemetryManager) {
parameterBuilder.addServerTelemetry(this.serverTelemetryManager);
}
parameterBuilder.addCorrelationId(correlationId);
parameterBuilder.addRefreshToken(request.refreshToken);
if (this.config.clientCredentials.clientSecret) {
parameterBuilder.addClientSecret(this.config.clientCredentials.clientSecret);
}
if (this.config.clientCredentials.clientAssertion) {
const clientAssertion = this.config.clientCredentials.clientAssertion;
parameterBuilder.addClientAssertion(clientAssertion.assertion);
parameterBuilder.addClientAssertionType(clientAssertion.assertionType);
}
if (request.authenticationScheme === AuthenticationScheme.POP) {
const popTokenGenerator = new PopTokenGenerator(this.cryptoUtils, this.performanceClient);
this.performanceClient?.setPreQueueTime(PerformanceEvents.PopTokenGenerateCnf, request.correlationId);
const reqCnfData = await popTokenGenerator.generateCnf(request);
// SPA PoP requires full Base64Url encoded req_cnf string (unhashed)
parameterBuilder.addPopToken(reqCnfData.reqCnfString);
}
else if (request.authenticationScheme === AuthenticationScheme.SSH) {
if (request.sshJwk) {
parameterBuilder.addSshJwk(request.sshJwk);
}
else {
acquireTokenMeasurement?.endMeasurement({
success: false,
});
throw ClientConfigurationError.createMissingSshJwkError();
}
}
if (!StringUtils.isEmptyObj(request.claims) ||
(this.config.authOptions.clientCapabilities &&
this.config.authOptions.clientCapabilities.length > 0)) {
parameterBuilder.addClaims(request.claims, this.config.authOptions.clientCapabilities);
}
if (this.config.systemOptions.preventCorsPreflight &&
request.ccsCredential) {
switch (request.ccsCredential.type) {
case CcsCredentialType.HOME_ACCOUNT_ID:
try {
const clientInfo = buildClientInfoFromHomeAccountId(request.ccsCredential.credential);
parameterBuilder.addCcsOid(clientInfo);
}
catch (e) {
this.logger.verbose("Could not parse home account ID for CCS Header: " +
e);
}
break;
case CcsCredentialType.UPN:
parameterBuilder.addCcsUpn(request.ccsCredential.credential);
break;
}
}
acquireTokenMeasurement?.endMeasurement({
success: true,
});
};
return RefreshTokenClient;
}(BaseClient));
return parameterBuilder.createQueryString();
}
}
export { RefreshTokenClient };
//# sourceMappingURL=RefreshTokenClient.js.map

@@ -1,4 +0,3 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';
import { __extends, __awaiter, __generator } from '../_virtual/_tslib.js';
import { BaseClient } from './BaseClient.js';

@@ -17,6 +16,5 @@ import { AuthToken } from '../account/AuthToken.js';

*/
var SilentFlowClient = /** @class */ (function (_super) {
__extends(SilentFlowClient, _super);
function SilentFlowClient(configuration, performanceClient) {
return _super.call(this, configuration, performanceClient) || this;
class SilentFlowClient extends BaseClient {
constructor(configuration, performanceClient) {
super(configuration, performanceClient);
}

@@ -28,25 +26,17 @@ /**

*/
SilentFlowClient.prototype.acquireToken = function (request) {
return __awaiter(this, void 0, void 0, function () {
var e_1, refreshTokenClient;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, this.acquireCachedToken(request)];
case 1: return [2 /*return*/, _a.sent()];
case 2:
e_1 = _a.sent();
if (e_1 instanceof ClientAuthError && e_1.errorCode === ClientAuthErrorMessage.tokenRefreshRequired.code) {
refreshTokenClient = new RefreshTokenClient(this.config, this.performanceClient);
return [2 /*return*/, refreshTokenClient.acquireTokenByRefreshToken(request)];
}
else {
throw e_1;
}
case 3: return [2 /*return*/];
}
});
});
};
async acquireToken(request) {
try {
return await this.acquireCachedToken(request);
}
catch (e) {
if (e instanceof ClientAuthError &&
e.errorCode === ClientAuthErrorMessage.tokenRefreshRequired.code) {
const refreshTokenClient = new RefreshTokenClient(this.config, this.performanceClient);
return refreshTokenClient.acquireTokenByRefreshToken(request);
}
else {
throw e;
}
}
}
/**

@@ -56,53 +46,44 @@ * Retrieves token from cache or throws an error if it must be refreshed.

*/
SilentFlowClient.prototype.acquireCachedToken = function (request) {
var _a, _b, _c, _d;
return __awaiter(this, void 0, void 0, function () {
var environment, cacheRecord;
return __generator(this, function (_e) {
switch (_e.label) {
case 0:
// Cannot renew token if no request object is given.
if (!request) {
throw ClientConfigurationError.createEmptyTokenRequestError();
}
if (request.forceRefresh) {
// Must refresh due to present force_refresh flag.
(_a = this.serverTelemetryManager) === null || _a === void 0 ? void 0 : _a.setCacheOutcome(CacheOutcome.FORCE_REFRESH);
this.logger.info("SilentFlowClient:acquireCachedToken - Skipping cache because forceRefresh is true.");
throw ClientAuthError.createRefreshRequiredError();
}
// We currently do not support silent flow for account === null use cases; This will be revisited for confidential flow usecases
if (!request.account) {
throw ClientAuthError.createNoAccountInSilentRequestError();
}
environment = request.authority || this.authority.getPreferredCache();
cacheRecord = this.cacheManager.readCacheRecord(request.account, request, environment);
if (!cacheRecord.accessToken) {
// Must refresh due to non-existent access_token.
(_b = this.serverTelemetryManager) === null || _b === void 0 ? void 0 : _b.setCacheOutcome(CacheOutcome.NO_CACHED_ACCESS_TOKEN);
this.logger.info("SilentFlowClient:acquireCachedToken - No access token found in cache for the given properties.");
throw ClientAuthError.createRefreshRequiredError();
}
else if (TimeUtils.wasClockTurnedBack(cacheRecord.accessToken.cachedAt) ||
TimeUtils.isTokenExpired(cacheRecord.accessToken.expiresOn, this.config.systemOptions.tokenRenewalOffsetSeconds)) {
// Must refresh due to expired access_token.
(_c = this.serverTelemetryManager) === null || _c === void 0 ? void 0 : _c.setCacheOutcome(CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED);
this.logger.info("SilentFlowClient:acquireCachedToken - Cached access token is expired or will expire within " + this.config.systemOptions.tokenRenewalOffsetSeconds + " seconds.");
throw ClientAuthError.createRefreshRequiredError();
}
else if (cacheRecord.accessToken.refreshOn && TimeUtils.isTokenExpired(cacheRecord.accessToken.refreshOn, 0)) {
// Must refresh due to the refresh_in value.
(_d = this.serverTelemetryManager) === null || _d === void 0 ? void 0 : _d.setCacheOutcome(CacheOutcome.REFRESH_CACHED_ACCESS_TOKEN);
this.logger.info("SilentFlowClient:acquireCachedToken - Cached access token's refreshOn property has been exceeded'.");
throw ClientAuthError.createRefreshRequiredError();
}
if (this.config.serverTelemetryManager) {
this.config.serverTelemetryManager.incrementCacheHits();
}
return [4 /*yield*/, this.generateResultFromCacheRecord(cacheRecord, request)];
case 1: return [2 /*return*/, _e.sent()];
}
});
});
};
async acquireCachedToken(request) {
// Cannot renew token if no request object is given.
if (!request) {
throw ClientConfigurationError.createEmptyTokenRequestError();
}
if (request.forceRefresh) {
// Must refresh due to present force_refresh flag.
this.serverTelemetryManager?.setCacheOutcome(CacheOutcome.FORCE_REFRESH);
this.logger.info("SilentFlowClient:acquireCachedToken - Skipping cache because forceRefresh is true.");
throw ClientAuthError.createRefreshRequiredError();
}
// We currently do not support silent flow for account === null use cases; This will be revisited for confidential flow usecases
if (!request.account) {
throw ClientAuthError.createNoAccountInSilentRequestError();
}
const environment = request.authority || this.authority.getPreferredCache();
const cacheRecord = this.cacheManager.readCacheRecord(request.account, request, environment);
if (!cacheRecord.accessToken) {
// Must refresh due to non-existent access_token.
this.serverTelemetryManager?.setCacheOutcome(CacheOutcome.NO_CACHED_ACCESS_TOKEN);
this.logger.info("SilentFlowClient:acquireCachedToken - No access token found in cache for the given properties.");
throw ClientAuthError.createRefreshRequiredError();
}
else if (TimeUtils.wasClockTurnedBack(cacheRecord.accessToken.cachedAt) ||
TimeUtils.isTokenExpired(cacheRecord.accessToken.expiresOn, this.config.systemOptions.tokenRenewalOffsetSeconds)) {
// Must refresh due to expired access_token.
this.serverTelemetryManager?.setCacheOutcome(CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED);
this.logger.info(`SilentFlowClient:acquireCachedToken - Cached access token is expired or will expire within ${this.config.systemOptions.tokenRenewalOffsetSeconds} seconds.`);
throw ClientAuthError.createRefreshRequiredError();
}
else if (cacheRecord.accessToken.refreshOn &&
TimeUtils.isTokenExpired(cacheRecord.accessToken.refreshOn, 0)) {
// Must refresh due to the refresh_in value.
this.serverTelemetryManager?.setCacheOutcome(CacheOutcome.REFRESH_CACHED_ACCESS_TOKEN);
this.logger.info("SilentFlowClient:acquireCachedToken - Cached access token's refreshOn property has been exceeded'.");
throw ClientAuthError.createRefreshRequiredError();
}
if (this.config.serverTelemetryManager) {
this.config.serverTelemetryManager.incrementCacheHits();
}
return await this.generateResultFromCacheRecord(cacheRecord, request);
}
/**

@@ -112,29 +93,20 @@ * Helper function to build response object from the CacheRecord

*/
SilentFlowClient.prototype.generateResultFromCacheRecord = function (cacheRecord, request) {
return __awaiter(this, void 0, void 0, function () {
var idTokenObj, authTime;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (cacheRecord.idToken) {
idTokenObj = new AuthToken(cacheRecord.idToken.secret, this.config.cryptoInterface);
}
// token max_age check
if (request.maxAge || (request.maxAge === 0)) {
authTime = idTokenObj === null || idTokenObj === void 0 ? void 0 : idTokenObj.claims.auth_time;
if (!authTime) {
throw ClientAuthError.createAuthTimeNotFoundError();
}
AuthToken.checkMaxAge(authTime, request.maxAge);
}
return [4 /*yield*/, ResponseHandler.generateAuthenticationResult(this.cryptoUtils, this.authority, cacheRecord, true, request, idTokenObj)];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
return SilentFlowClient;
}(BaseClient));
async generateResultFromCacheRecord(cacheRecord, request) {
let idTokenObj;
if (cacheRecord.idToken) {
idTokenObj = new AuthToken(cacheRecord.idToken.secret, this.config.cryptoInterface);
}
// token max_age check
if (request.maxAge || request.maxAge === 0) {
const authTime = idTokenObj?.claims.auth_time;
if (!authTime) {
throw ClientAuthError.createAuthTimeNotFoundError();
}
AuthToken.checkMaxAge(authTime, request.maxAge);
}
return await ResponseHandler.generateAuthenticationResult(this.cryptoUtils, this.authority, cacheRecord, true, request, idTokenObj);
}
}
export { SilentFlowClient };
//# sourceMappingURL=SilentFlowClient.js.map

@@ -21,3 +21,3 @@ /**

*/
export declare type AppTokenProviderParameters = {
export type AppTokenProviderParameters = {
readonly correlationId?: string;

@@ -35,3 +35,3 @@ readonly tenantId: string;

*/
export declare type AppTokenProviderResult = {
export type AppTokenProviderResult = {
accessToken: string;

@@ -38,0 +38,0 @@ expiresInSeconds: number;

@@ -25,3 +25,3 @@ import { INetworkModule } from "../network/INetworkModule";

*/
export declare type ClientConfiguration = {
export type ClientConfiguration = {
authOptions: AuthOptions;

@@ -40,3 +40,3 @@ systemOptions?: SystemOptions;

};
export declare type CommonClientConfiguration = {
export type CommonClientConfiguration = {
authOptions: Required<AuthOptions>;

@@ -66,3 +66,3 @@ systemOptions: Required<SystemOptions>;

*/
export declare type AuthOptions = {
export type AuthOptions = {
clientId: string;

@@ -79,3 +79,3 @@ authority: Authority;

*/
export declare type SystemOptions = {
export type SystemOptions = {
tokenRenewalOffsetSeconds?: number;

@@ -92,3 +92,3 @@ preventCorsPreflight?: boolean;

*/
export declare type LoggerOptions = {
export type LoggerOptions = {
loggerCallback?: ILoggerCallback;

@@ -102,3 +102,3 @@ piiLoggingEnabled?: boolean;

*/
export declare type LibraryInfo = {
export type LibraryInfo = {
sku: string;

@@ -115,7 +115,7 @@ version: string;

*/
export declare type AzureCloudOptions = {
export type AzureCloudOptions = {
azureCloudInstance: AzureCloudInstance;
tenant?: string;
};
export declare type TelemetryOptions = {
export type TelemetryOptions = {
application: ApplicationTelemetry;

@@ -128,3 +128,3 @@ };

*/
export declare type ApplicationTelemetry = {
export type ApplicationTelemetry = {
appName: string;

@@ -131,0 +131,0 @@ appVersion: string;

@@ -1,4 +0,3 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';
import { __assign, __awaiter, __generator } from '../_virtual/_tslib.js';
import { DEFAULT_CRYPTO_IMPLEMENTATION } from '../crypto/ICrypto.js';

@@ -17,9 +16,9 @@ import { AuthError } from '../error/AuthError.js';

// Token renewal offset default in seconds
var DEFAULT_TOKEN_RENEWAL_OFFSET_SEC = 300;
var DEFAULT_SYSTEM_OPTIONS = {
const DEFAULT_TOKEN_RENEWAL_OFFSET_SEC = 300;
const DEFAULT_SYSTEM_OPTIONS = {
tokenRenewalOffsetSeconds: DEFAULT_TOKEN_RENEWAL_OFFSET_SEC,
preventCorsPreflight: false
preventCorsPreflight: false,
};
var DEFAULT_LOGGER_IMPLEMENTATION = {
loggerCallback: function () {
const DEFAULT_LOGGER_IMPLEMENTATION = {
loggerCallback: () => {
// allow users to not set loggerCallback

@@ -29,43 +28,33 @@ },

logLevel: LogLevel.Info,
correlationId: Constants.EMPTY_STRING
correlationId: Constants.EMPTY_STRING,
};
var DEFAULT_NETWORK_IMPLEMENTATION = {
sendGetRequestAsync: function () {
return __awaiter(this, void 0, void 0, function () {
var notImplErr;
return __generator(this, function (_a) {
notImplErr = "Network interface - sendGetRequestAsync() has not been implemented";
throw AuthError.createUnexpectedError(notImplErr);
});
});
const DEFAULT_NETWORK_IMPLEMENTATION = {
async sendGetRequestAsync() {
const notImplErr = "Network interface - sendGetRequestAsync() has not been implemented";
throw AuthError.createUnexpectedError(notImplErr);
},
sendPostRequestAsync: function () {
return __awaiter(this, void 0, void 0, function () {
var notImplErr;
return __generator(this, function (_a) {
notImplErr = "Network interface - sendPostRequestAsync() has not been implemented";
throw AuthError.createUnexpectedError(notImplErr);
});
});
}
async sendPostRequestAsync() {
const notImplErr = "Network interface - sendPostRequestAsync() has not been implemented";
throw AuthError.createUnexpectedError(notImplErr);
},
};
var DEFAULT_LIBRARY_INFO = {
const DEFAULT_LIBRARY_INFO = {
sku: Constants.SKU,
version: version,
cpu: Constants.EMPTY_STRING,
os: Constants.EMPTY_STRING
os: Constants.EMPTY_STRING,
};
var DEFAULT_CLIENT_CREDENTIALS = {
const DEFAULT_CLIENT_CREDENTIALS = {
clientSecret: Constants.EMPTY_STRING,
clientAssertion: undefined
clientAssertion: undefined,
};
var DEFAULT_AZURE_CLOUD_OPTIONS = {
const DEFAULT_AZURE_CLOUD_OPTIONS = {
azureCloudInstance: AzureCloudInstance.None,
tenant: "" + Constants.DEFAULT_COMMON_TENANT
tenant: `${Constants.DEFAULT_COMMON_TENANT}`,
};
var DEFAULT_TELEMETRY_OPTIONS = {
const DEFAULT_TELEMETRY_OPTIONS = {
application: {
appName: "",
appVersion: ""
}
appVersion: "",
},
};

@@ -79,15 +68,18 @@ /**

*/
function buildClientConfiguration(_a) {
var userAuthOptions = _a.authOptions, userSystemOptions = _a.systemOptions, userLoggerOption = _a.loggerOptions, storageImplementation = _a.storageInterface, networkImplementation = _a.networkInterface, cryptoImplementation = _a.cryptoInterface, clientCredentials = _a.clientCredentials, libraryInfo = _a.libraryInfo, telemetry = _a.telemetry, serverTelemetryManager = _a.serverTelemetryManager, persistencePlugin = _a.persistencePlugin, serializableCache = _a.serializableCache;
var loggerOptions = __assign(__assign({}, DEFAULT_LOGGER_IMPLEMENTATION), userLoggerOption);
function buildClientConfiguration({ authOptions: userAuthOptions, systemOptions: userSystemOptions, loggerOptions: userLoggerOption, storageInterface: storageImplementation, networkInterface: networkImplementation, cryptoInterface: cryptoImplementation, clientCredentials: clientCredentials, libraryInfo: libraryInfo, telemetry: telemetry, serverTelemetryManager: serverTelemetryManager, persistencePlugin: persistencePlugin, serializableCache: serializableCache, }) {
const loggerOptions = {
...DEFAULT_LOGGER_IMPLEMENTATION,
...userLoggerOption,
};
return {
authOptions: buildAuthOptions(userAuthOptions),
systemOptions: __assign(__assign({}, DEFAULT_SYSTEM_OPTIONS), userSystemOptions),
systemOptions: { ...DEFAULT_SYSTEM_OPTIONS, ...userSystemOptions },
loggerOptions: loggerOptions,
storageInterface: storageImplementation || new DefaultStorageClass(userAuthOptions.clientId, DEFAULT_CRYPTO_IMPLEMENTATION, new Logger(loggerOptions)),
storageInterface: storageImplementation ||
new DefaultStorageClass(userAuthOptions.clientId, DEFAULT_CRYPTO_IMPLEMENTATION, new Logger(loggerOptions)),
networkInterface: networkImplementation || DEFAULT_NETWORK_IMPLEMENTATION,
cryptoInterface: cryptoImplementation || DEFAULT_CRYPTO_IMPLEMENTATION,
clientCredentials: clientCredentials || DEFAULT_CLIENT_CREDENTIALS,
libraryInfo: __assign(__assign({}, DEFAULT_LIBRARY_INFO), libraryInfo),
telemetry: __assign(__assign({}, DEFAULT_TELEMETRY_OPTIONS), telemetry),
libraryInfo: { ...DEFAULT_LIBRARY_INFO, ...libraryInfo },
telemetry: { ...DEFAULT_TELEMETRY_OPTIONS, ...telemetry },
serverTelemetryManager: serverTelemetryManager || null,

@@ -103,3 +95,8 @@ persistencePlugin: persistencePlugin || null,

function buildAuthOptions(authOptions) {
return __assign({ clientCapabilities: [], azureCloudOptions: DEFAULT_AZURE_CLOUD_OPTIONS, skipAuthorityMetadataCache: false }, authOptions);
return {
clientCapabilities: [],
azureCloudOptions: DEFAULT_AZURE_CLOUD_OPTIONS,
skipAuthorityMetadataCache: false,
...authOptions,
};
}

@@ -106,0 +103,0 @@

@@ -8,7 +8,7 @@ import { BaseAuthRequest } from "../request/BaseAuthRequest";

*/
export declare type PkceCodes = {
export type PkceCodes = {
verifier: string;
challenge: string;
};
export declare type SignedHttpRequestParameters = Pick<BaseAuthRequest, "resourceRequestMethod" | "resourceRequestUri" | "shrClaims" | "shrNonce"> & {
export type SignedHttpRequestParameters = Pick<BaseAuthRequest, "resourceRequestMethod" | "resourceRequestUri" | "shrClaims" | "shrNonce"> & {
correlationId?: string;

@@ -15,0 +15,0 @@ };

@@ -1,4 +0,3 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';
import { __awaiter, __generator } from '../_virtual/_tslib.js';
import { AuthError } from '../error/AuthError.js';

@@ -10,69 +9,39 @@

*/
var DEFAULT_CRYPTO_IMPLEMENTATION = {
createNewGuid: function () {
var notImplErr = "Crypto interface - createNewGuid() has not been implemented";
const DEFAULT_CRYPTO_IMPLEMENTATION = {
createNewGuid: () => {
const notImplErr = "Crypto interface - createNewGuid() has not been implemented";
throw AuthError.createUnexpectedError(notImplErr);
},
base64Decode: function () {
var notImplErr = "Crypto interface - base64Decode() has not been implemented";
base64Decode: () => {
const notImplErr = "Crypto interface - base64Decode() has not been implemented";
throw AuthError.createUnexpectedError(notImplErr);
},
base64Encode: function () {
var notImplErr = "Crypto interface - base64Encode() has not been implemented";
base64Encode: () => {
const notImplErr = "Crypto interface - base64Encode() has not been implemented";
throw AuthError.createUnexpectedError(notImplErr);
},
generatePkceCodes: function () {
return __awaiter(this, void 0, void 0, function () {
var notImplErr;
return __generator(this, function (_a) {
notImplErr = "Crypto interface - generatePkceCodes() has not been implemented";
throw AuthError.createUnexpectedError(notImplErr);
});
});
async generatePkceCodes() {
const notImplErr = "Crypto interface - generatePkceCodes() has not been implemented";
throw AuthError.createUnexpectedError(notImplErr);
},
getPublicKeyThumbprint: function () {
return __awaiter(this, void 0, void 0, function () {
var notImplErr;
return __generator(this, function (_a) {
notImplErr = "Crypto interface - getPublicKeyThumbprint() has not been implemented";
throw AuthError.createUnexpectedError(notImplErr);
});
});
async getPublicKeyThumbprint() {
const notImplErr = "Crypto interface - getPublicKeyThumbprint() has not been implemented";
throw AuthError.createUnexpectedError(notImplErr);
},
removeTokenBindingKey: function () {
return __awaiter(this, void 0, void 0, function () {
var notImplErr;
return __generator(this, function (_a) {
notImplErr = "Crypto interface - removeTokenBindingKey() has not been implemented";
throw AuthError.createUnexpectedError(notImplErr);
});
});
async removeTokenBindingKey() {
const notImplErr = "Crypto interface - removeTokenBindingKey() has not been implemented";
throw AuthError.createUnexpectedError(notImplErr);
},
clearKeystore: function () {
return __awaiter(this, void 0, void 0, function () {
var notImplErr;
return __generator(this, function (_a) {
notImplErr = "Crypto interface - clearKeystore() has not been implemented";
throw AuthError.createUnexpectedError(notImplErr);
});
});
async clearKeystore() {
const notImplErr = "Crypto interface - clearKeystore() has not been implemented";
throw AuthError.createUnexpectedError(notImplErr);
},
signJwt: function () {
return __awaiter(this, void 0, void 0, function () {
var notImplErr;
return __generator(this, function (_a) {
notImplErr = "Crypto interface - signJwt() has not been implemented";
throw AuthError.createUnexpectedError(notImplErr);
});
});
async signJwt() {
const notImplErr = "Crypto interface - signJwt() has not been implemented";
throw AuthError.createUnexpectedError(notImplErr);
},
hashString: function () {
return __awaiter(this, void 0, void 0, function () {
var notImplErr;
return __generator(this, function (_a) {
notImplErr = "Crypto interface - hashString() has not been implemented";
throw AuthError.createUnexpectedError(notImplErr);
});
});
}
async hashString() {
const notImplErr = "Crypto interface - hashString() has not been implemented";
throw AuthError.createUnexpectedError(notImplErr);
},
};

@@ -79,0 +48,0 @@

import { JsonTypes } from "../utils/Constants";
export declare type JoseHeaderOptions = {
export type JoseHeaderOptions = {
typ?: JsonTypes;

@@ -4,0 +4,0 @@ alg?: string;

@@ -1,2 +0,2 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';

@@ -10,4 +10,4 @@ import { JoseHeaderError } from '../error/JoseHeaderError.js';

*/
var JoseHeader = /** @class */ (function () {
function JoseHeader(options) {
class JoseHeader {
constructor(options) {
this.typ = options.typ;

@@ -25,3 +25,3 @@ this.alg = options.alg;

*/
JoseHeader.getShrHeaderString = function (shrHeaderOptions) {
static getShrHeaderString(shrHeaderOptions) {
// KeyID is required on the SHR header

@@ -35,14 +35,13 @@ if (!shrHeaderOptions.kid) {

}
var shrHeader = new JoseHeader({
const shrHeader = new JoseHeader({
// Access Token PoP headers must have type pop, but the type header can be overriden for special cases
typ: shrHeaderOptions.typ || JsonTypes.Pop,
kid: shrHeaderOptions.kid,
alg: shrHeaderOptions.alg
alg: shrHeaderOptions.alg,
});
return JSON.stringify(shrHeader);
};
return JoseHeader;
}());
}
}
export { JoseHeader };
//# sourceMappingURL=JoseHeader.js.map

@@ -10,7 +10,7 @@ import { ICrypto, SignedHttpRequestParameters } from "./ICrypto";

*/
declare type ReqCnf = {
type ReqCnf = {
kid: string;
xms_ksl: KeyLocation;
};
export declare type ReqCnfData = {
export type ReqCnfData = {
kid: string;

@@ -17,0 +17,0 @@ reqCnfString: string;

@@ -1,4 +0,3 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';
import { __awaiter, __generator, __assign } from '../_virtual/_tslib.js';
import { TimeUtils } from '../utils/TimeUtils.js';

@@ -17,4 +16,4 @@ import { UrlString } from '../url/UrlString.js';

})(KeyLocation || (KeyLocation = {}));
var PopTokenGenerator = /** @class */ (function () {
function PopTokenGenerator(cryptoUtils, performanceClient) {
class PopTokenGenerator {
constructor(cryptoUtils, performanceClient) {
this.cryptoUtils = cryptoUtils;

@@ -29,26 +28,13 @@ this.performanceClient = performanceClient;

*/
PopTokenGenerator.prototype.generateCnf = function (request) {
var _a, _b;
return __awaiter(this, void 0, void 0, function () {
var reqCnf, reqCnfString, _c;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
(_a = this.performanceClient) === null || _a === void 0 ? void 0 : _a.addQueueMeasurement(PerformanceEvents.PopTokenGenerateCnf, request.correlationId);
(_b = this.performanceClient) === null || _b === void 0 ? void 0 : _b.setPreQueueTime(PerformanceEvents.PopTokenGenerateKid, request.correlationId);
return [4 /*yield*/, this.generateKid(request)];
case 1:
reqCnf = _d.sent();
reqCnfString = this.cryptoUtils.base64Encode(JSON.stringify(reqCnf));
_c = {
kid: reqCnf.kid,
reqCnfString: reqCnfString
};
return [4 /*yield*/, this.cryptoUtils.hashString(reqCnfString)];
case 2: return [2 /*return*/, (_c.reqCnfHash = _d.sent(),
_c)];
}
});
});
};
async generateCnf(request) {
this.performanceClient?.addQueueMeasurement(PerformanceEvents.PopTokenGenerateCnf, request.correlationId);
this.performanceClient?.setPreQueueTime(PerformanceEvents.PopTokenGenerateKid, request.correlationId);
const reqCnf = await this.generateKid(request);
const reqCnfString = this.cryptoUtils.base64Encode(JSON.stringify(reqCnf));
return {
kid: reqCnf.kid,
reqCnfString,
reqCnfHash: await this.cryptoUtils.hashString(reqCnfString),
};
}
/**

@@ -59,21 +45,10 @@ * Generates key_id for a SHR token request

*/
PopTokenGenerator.prototype.generateKid = function (request) {
var _a;
return __awaiter(this, void 0, void 0, function () {
var kidThumbprint;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
(_a = this.performanceClient) === null || _a === void 0 ? void 0 : _a.addQueueMeasurement(PerformanceEvents.PopTokenGenerateKid, request.correlationId);
return [4 /*yield*/, this.cryptoUtils.getPublicKeyThumbprint(request)];
case 1:
kidThumbprint = _b.sent();
return [2 /*return*/, {
kid: kidThumbprint,
xms_ksl: KeyLocation.SW
}];
}
});
});
};
async generateKid(request) {
this.performanceClient?.addQueueMeasurement(PerformanceEvents.PopTokenGenerateKid, request.correlationId);
const kidThumbprint = await this.cryptoUtils.getPublicKeyThumbprint(request);
return {
kid: kidThumbprint,
xms_ksl: KeyLocation.SW,
};
}
/**

@@ -85,9 +60,5 @@ * Signs the POP access_token with the local generated key-pair

*/
PopTokenGenerator.prototype.signPopToken = function (accessToken, keyId, request) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.signPayload(accessToken, keyId, request)];
});
});
};
async signPopToken(accessToken, keyId, request) {
return this.signPayload(accessToken, keyId, request);
}
/**

@@ -101,21 +72,26 @@ * Utility function to generate the signed JWT for an access_token

*/
PopTokenGenerator.prototype.signPayload = function (payload, keyId, request, claims) {
return __awaiter(this, void 0, void 0, function () {
var resourceRequestMethod, resourceRequestUri, shrClaims, shrNonce, resourceUrlString, resourceUrlComponents;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
resourceRequestMethod = request.resourceRequestMethod, resourceRequestUri = request.resourceRequestUri, shrClaims = request.shrClaims, shrNonce = request.shrNonce;
resourceUrlString = (resourceRequestUri) ? new UrlString(resourceRequestUri) : undefined;
resourceUrlComponents = resourceUrlString === null || resourceUrlString === void 0 ? void 0 : resourceUrlString.getUrlComponents();
return [4 /*yield*/, this.cryptoUtils.signJwt(__assign({ at: payload, ts: TimeUtils.nowSeconds(), m: resourceRequestMethod === null || resourceRequestMethod === void 0 ? void 0 : resourceRequestMethod.toUpperCase(), u: resourceUrlComponents === null || resourceUrlComponents === void 0 ? void 0 : resourceUrlComponents.HostNameAndPort, nonce: shrNonce || this.cryptoUtils.createNewGuid(), p: resourceUrlComponents === null || resourceUrlComponents === void 0 ? void 0 : resourceUrlComponents.AbsolutePath, q: (resourceUrlComponents === null || resourceUrlComponents === void 0 ? void 0 : resourceUrlComponents.QueryString) ? [[], resourceUrlComponents.QueryString] : undefined, client_claims: shrClaims || undefined }, claims), keyId, request.correlationId)];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
return PopTokenGenerator;
}());
async signPayload(payload, keyId, request, claims) {
// Deconstruct request to extract SHR parameters
const { resourceRequestMethod, resourceRequestUri, shrClaims, shrNonce, } = request;
const resourceUrlString = resourceRequestUri
? new UrlString(resourceRequestUri)
: undefined;
const resourceUrlComponents = resourceUrlString?.getUrlComponents();
return await this.cryptoUtils.signJwt({
at: payload,
ts: TimeUtils.nowSeconds(),
m: resourceRequestMethod?.toUpperCase(),
u: resourceUrlComponents?.HostNameAndPort,
nonce: shrNonce || this.cryptoUtils.createNewGuid(),
p: resourceUrlComponents?.AbsolutePath,
q: resourceUrlComponents?.QueryString
? [[], resourceUrlComponents.QueryString]
: undefined,
client_claims: shrClaims || undefined,
...claims,
}, keyId, request.correlationId);
}
}
export { PopTokenGenerator };
//# sourceMappingURL=PopTokenGenerator.js.map

@@ -1,2 +0,2 @@

export declare type SignedHttpRequest = {
export type SignedHttpRequest = {
at?: string;

@@ -3,0 +3,0 @@ cnf?: object;

@@ -1,4 +0,3 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';
import { __extends } from '../_virtual/_tslib.js';
import { Constants } from '../utils/Constants.js';

@@ -13,11 +12,11 @@

*/
var AuthErrorMessage = {
const AuthErrorMessage = {
unexpectedError: {
code: "unexpected_error",
desc: "Unexpected error in authentication."
desc: "Unexpected error in authentication.",
},
postRequestFailed: {
code: "post_request_failed",
desc: "Post request failed from the network, could be a 4xx/5xx or a network unavailability. Please check the exact error code for details."
}
desc: "Post request failed from the network, could be a 4xx/5xx or a network unavailability. Please check the exact error code for details.",
},
};

@@ -27,18 +26,17 @@ /**

*/
var AuthError = /** @class */ (function (_super) {
__extends(AuthError, _super);
function AuthError(errorCode, errorMessage, suberror) {
var _this = this;
var errorString = errorMessage ? errorCode + ": " + errorMessage : errorCode;
_this = _super.call(this, errorString) || this;
Object.setPrototypeOf(_this, AuthError.prototype);
_this.errorCode = errorCode || Constants.EMPTY_STRING;
_this.errorMessage = errorMessage || Constants.EMPTY_STRING;
_this.subError = suberror || Constants.EMPTY_STRING;
_this.name = "AuthError";
return _this;
class AuthError extends Error {
constructor(errorCode, errorMessage, suberror) {
const errorString = errorMessage
? `${errorCode}: ${errorMessage}`
: errorCode;
super(errorString);
Object.setPrototypeOf(this, AuthError.prototype);
this.errorCode = errorCode || Constants.EMPTY_STRING;
this.errorMessage = errorMessage || Constants.EMPTY_STRING;
this.subError = suberror || Constants.EMPTY_STRING;
this.name = "AuthError";
}
AuthError.prototype.setCorrelationId = function (correlationId) {
setCorrelationId(correlationId) {
this.correlationId = correlationId;
};
}
/**

@@ -48,5 +46,5 @@ * Creates an error that is thrown when something unexpected happens in the library.

*/
AuthError.createUnexpectedError = function (errDesc) {
return new AuthError(AuthErrorMessage.unexpectedError.code, AuthErrorMessage.unexpectedError.desc + ": " + errDesc);
};
static createUnexpectedError(errDesc) {
return new AuthError(AuthErrorMessage.unexpectedError.code, `${AuthErrorMessage.unexpectedError.desc}: ${errDesc}`);
}
/**

@@ -57,9 +55,8 @@ * Creates an error for post request failures.

*/
AuthError.createPostRequestFailed = function (errDesc) {
return new AuthError(AuthErrorMessage.postRequestFailed.code, AuthErrorMessage.postRequestFailed.desc + ": " + errDesc);
};
return AuthError;
}(Error));
static createPostRequestFailed(errDesc) {
return new AuthError(AuthErrorMessage.postRequestFailed.code, `${AuthErrorMessage.postRequestFailed.desc}: ${errDesc}`);
}
}
export { AuthError, AuthErrorMessage };
//# sourceMappingURL=AuthError.js.map

@@ -206,2 +206,6 @@ import { AuthError } from "./AuthError";

};
missingTenantIdError: {
code: string;
desc: string;
};
};

@@ -405,3 +409,7 @@ /**

static createUserCanceledError(): ClientAuthError;
/**
* Creates an error for during acquireTokenByClientCredential when TenantId is set to "common" or "organizations"
*/
static createMissingTenantIdError(): ClientAuthError;
}
//# sourceMappingURL=ClientAuthError.d.ts.map

@@ -1,4 +0,3 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';
import { __extends } from '../_virtual/_tslib.js';
import { AuthError } from './AuthError.js';

@@ -13,58 +12,58 @@

*/
var ClientAuthErrorMessage = {
const ClientAuthErrorMessage = {
clientInfoDecodingError: {
code: "client_info_decoding_error",
desc: "The client info could not be parsed/decoded correctly. Please review the trace to determine the root cause."
desc: "The client info could not be parsed/decoded correctly. Please review the trace to determine the root cause.",
},
clientInfoEmptyError: {
code: "client_info_empty_error",
desc: "The client info was empty. Please review the trace to determine the root cause."
desc: "The client info was empty. Please review the trace to determine the root cause.",
},
tokenParsingError: {
code: "token_parsing_error",
desc: "Token cannot be parsed. Please review stack trace to determine root cause."
desc: "Token cannot be parsed. Please review stack trace to determine root cause.",
},
nullOrEmptyToken: {
code: "null_or_empty_token",
desc: "The token is null or empty. Please review the trace to determine the root cause."
desc: "The token is null or empty. Please review the trace to determine the root cause.",
},
endpointResolutionError: {
code: "endpoints_resolution_error",
desc: "Error: could not resolve endpoints. Please check network and try again."
desc: "Error: could not resolve endpoints. Please check network and try again.",
},
networkError: {
code: "network_error",
desc: "Network request failed. Please check network trace to determine root cause."
desc: "Network request failed. Please check network trace to determine root cause.",
},
unableToGetOpenidConfigError: {
code: "openid_config_error",
desc: "Could not retrieve endpoints. Check your authority and verify the .well-known/openid-configuration endpoint returns the required endpoints."
desc: "Could not retrieve endpoints. Check your authority and verify the .well-known/openid-configuration endpoint returns the required endpoints.",
},
hashNotDeserialized: {
code: "hash_not_deserialized",
desc: "The hash parameters could not be deserialized. Please review the trace to determine the root cause."
desc: "The hash parameters could not be deserialized. Please review the trace to determine the root cause.",
},
blankGuidGenerated: {
code: "blank_guid_generated",
desc: "The guid generated was blank. Please review the trace to determine the root cause."
desc: "The guid generated was blank. Please review the trace to determine the root cause.",
},
invalidStateError: {
code: "invalid_state",
desc: "State was not the expected format. Please check the logs to determine whether the request was sent using ProtocolUtils.setRequestState()."
desc: "State was not the expected format. Please check the logs to determine whether the request was sent using ProtocolUtils.setRequestState().",
},
stateMismatchError: {
code: "state_mismatch",
desc: "State mismatch error. Please check your network. Continued requests may cause cache overflow."
desc: "State mismatch error. Please check your network. Continued requests may cause cache overflow.",
},
stateNotFoundError: {
code: "state_not_found",
desc: "State not found"
desc: "State not found",
},
nonceMismatchError: {
code: "nonce_mismatch",
desc: "Nonce mismatch error. This may be caused by a race condition in concurrent requests."
desc: "Nonce mismatch error. This may be caused by a race condition in concurrent requests.",
},
nonceNotFoundError: {
code: "nonce_not_found",
desc: "nonce not found"
desc: "nonce not found",
},

@@ -75,11 +74,11 @@ authTimeNotFoundError: {

" auth_time is an optional claim and is not enabled by default - it must be enabled." +
" See https://aka.ms/msaljs/optional-claims for more information."
" See https://aka.ms/msaljs/optional-claims for more information.",
},
maxAgeTranspiredError: {
code: "max_age_transpired",
desc: "Max Age is set to 0, or too much time has elapsed since the last end-user authentication."
desc: "Max Age is set to 0, or too much time has elapsed since the last end-user authentication.",
},
noTokensFoundError: {
code: "no_tokens_found",
desc: "No tokens were found for the given scopes, and no authorization code was passed to acquireToken. You must retrieve an authorization code before making a call to acquireToken()."
desc: "No tokens were found for the given scopes, and no authorization code was passed to acquireToken. You must retrieve an authorization code before making a call to acquireToken().",
},

@@ -89,91 +88,91 @@ multipleMatchingTokens: {

desc: "The cache contains multiple tokens satisfying the requirements. " +
"Call AcquireToken again providing more requirements such as authority or account."
"Call AcquireToken again providing more requirements such as authority or account.",
},
multipleMatchingAccounts: {
code: "multiple_matching_accounts",
desc: "The cache contains multiple accounts satisfying the given parameters. Please pass more info to obtain the correct account"
desc: "The cache contains multiple accounts satisfying the given parameters. Please pass more info to obtain the correct account",
},
multipleMatchingAppMetadata: {
code: "multiple_matching_appMetadata",
desc: "The cache contains multiple appMetadata satisfying the given parameters. Please pass more info to obtain the correct appMetadata"
desc: "The cache contains multiple appMetadata satisfying the given parameters. Please pass more info to obtain the correct appMetadata",
},
tokenRequestCannotBeMade: {
code: "request_cannot_be_made",
desc: "Token request cannot be made without authorization code or refresh token."
desc: "Token request cannot be made without authorization code or refresh token.",
},
appendEmptyScopeError: {
code: "cannot_append_empty_scope",
desc: "Cannot append null or empty scope to ScopeSet. Please check the stack trace for more info."
desc: "Cannot append null or empty scope to ScopeSet. Please check the stack trace for more info.",
},
removeEmptyScopeError: {
code: "cannot_remove_empty_scope",
desc: "Cannot remove null or empty scope from ScopeSet. Please check the stack trace for more info."
desc: "Cannot remove null or empty scope from ScopeSet. Please check the stack trace for more info.",
},
appendScopeSetError: {
code: "cannot_append_scopeset",
desc: "Cannot append ScopeSet due to error."
desc: "Cannot append ScopeSet due to error.",
},
emptyInputScopeSetError: {
code: "empty_input_scopeset",
desc: "Empty input ScopeSet cannot be processed."
desc: "Empty input ScopeSet cannot be processed.",
},
DeviceCodePollingCancelled: {
code: "device_code_polling_cancelled",
desc: "Caller has cancelled token endpoint polling during device code flow by setting DeviceCodeRequest.cancel = true."
desc: "Caller has cancelled token endpoint polling during device code flow by setting DeviceCodeRequest.cancel = true.",
},
DeviceCodeExpired: {
code: "device_code_expired",
desc: "Device code is expired."
desc: "Device code is expired.",
},
DeviceCodeUnknownError: {
code: "device_code_unknown_error",
desc: "Device code stopped polling for unknown reasons."
desc: "Device code stopped polling for unknown reasons.",
},
NoAccountInSilentRequest: {
code: "no_account_in_silent_request",
desc: "Please pass an account object, silent flow is not supported without account information"
desc: "Please pass an account object, silent flow is not supported without account information",
},
invalidCacheRecord: {
code: "invalid_cache_record",
desc: "Cache record object was null or undefined."
desc: "Cache record object was null or undefined.",
},
invalidCacheEnvironment: {
code: "invalid_cache_environment",
desc: "Invalid environment when attempting to create cache entry"
desc: "Invalid environment when attempting to create cache entry",
},
noAccountFound: {
code: "no_account_found",
desc: "No account found in cache for given key."
desc: "No account found in cache for given key.",
},
CachePluginError: {
code: "no cache plugin set on CacheManager",
desc: "ICachePlugin needs to be set before using readFromStorage or writeFromStorage"
desc: "ICachePlugin needs to be set before using readFromStorage or writeFromStorage",
},
noCryptoObj: {
code: "no_crypto_object",
desc: "No crypto object detected. This is required for the following operation: "
desc: "No crypto object detected. This is required for the following operation: ",
},
invalidCacheType: {
code: "invalid_cache_type",
desc: "Invalid cache type"
desc: "Invalid cache type",
},
unexpectedAccountType: {
code: "unexpected_account_type",
desc: "Unexpected account type."
desc: "Unexpected account type.",
},
unexpectedCredentialType: {
code: "unexpected_credential_type",
desc: "Unexpected credential type."
desc: "Unexpected credential type.",
},
invalidAssertion: {
code: "invalid_assertion",
desc: "Client assertion must meet requirements described in https://tools.ietf.org/html/rfc7515"
desc: "Client assertion must meet requirements described in https://tools.ietf.org/html/rfc7515",
},
invalidClientCredential: {
code: "invalid_client_credential",
desc: "Client credential (secret, certificate, or assertion) must not be empty when creating a confidential client. An application should at most have one credential"
desc: "Client credential (secret, certificate, or assertion) must not be empty when creating a confidential client. An application should at most have one credential",
},
tokenRefreshRequired: {
code: "token_refresh_required",
desc: "Cannot return token from cache because it must be refreshed. This may be due to one of the following reasons: forceRefresh parameter is set to true, claims have been requested, there is no cached access token or it is expired."
desc: "Cannot return token from cache because it must be refreshed. This may be due to one of the following reasons: forceRefresh parameter is set to true, claims have been requested, there is no cached access token or it is expired.",
},

@@ -186,36 +185,40 @@ userTimeoutReached: {

code: "token_claims_cnf_required_for_signedjwt",
desc: "Cannot generate a POP jwt if the token_claims are not populated"
desc: "Cannot generate a POP jwt if the token_claims are not populated",
},
noAuthorizationCodeFromServer: {
code: "authorization_code_missing_from_server_response",
desc: "Server response does not contain an authorization code to proceed"
desc: "Server response does not contain an authorization code to proceed",
},
noAzureRegionDetected: {
code: "no_azure_region_detected",
desc: "No azure region was detected and no fallback was made available"
desc: "No azure region was detected and no fallback was made available",
},
accessTokenEntityNullError: {
code: "access_token_entity_null",
desc: "Access token entity is null, please check logs and cache to ensure a valid access token is present."
desc: "Access token entity is null, please check logs and cache to ensure a valid access token is present.",
},
bindingKeyNotRemovedError: {
code: "binding_key_not_removed",
desc: "Could not remove the credential's binding key from storage."
desc: "Could not remove the credential's binding key from storage.",
},
logoutNotSupported: {
code: "end_session_endpoint_not_supported",
desc: "Provided authority does not support logout."
desc: "Provided authority does not support logout.",
},
keyIdMissing: {
code: "key_id_missing",
desc: "A keyId value is missing from the requested bound token's cache record and is required to match the token to it's stored binding key."
desc: "A keyId value is missing from the requested bound token's cache record and is required to match the token to it's stored binding key.",
},
noNetworkConnectivity: {
code: "no_network_connectivity",
desc: "No network connectivity. Check your internet connection."
desc: "No network connectivity. Check your internet connection.",
},
userCanceledError: {
code: "user_canceled",
desc: "User canceled the flow."
}
desc: "User canceled the flow.",
},
missingTenantIdError: {
code: "missing_tenant_id_error",
desc: "A tenant id - not common, organizations, or consumers - must be specified when using the client_credentials flow.",
},
};

@@ -225,9 +228,7 @@ /**

*/
var ClientAuthError = /** @class */ (function (_super) {
__extends(ClientAuthError, _super);
function ClientAuthError(errorCode, errorMessage) {
var _this = _super.call(this, errorCode, errorMessage) || this;
_this.name = "ClientAuthError";
Object.setPrototypeOf(_this, ClientAuthError.prototype);
return _this;
class ClientAuthError extends AuthError {
constructor(errorCode, errorMessage) {
super(errorCode, errorMessage);
this.name = "ClientAuthError";
Object.setPrototypeOf(this, ClientAuthError.prototype);
}

@@ -238,5 +239,5 @@ /**

*/
ClientAuthError.createClientInfoDecodingError = function (caughtError) {
return new ClientAuthError(ClientAuthErrorMessage.clientInfoDecodingError.code, ClientAuthErrorMessage.clientInfoDecodingError.desc + " Failed with error: " + caughtError);
};
static createClientInfoDecodingError(caughtError) {
return new ClientAuthError(ClientAuthErrorMessage.clientInfoDecodingError.code, `${ClientAuthErrorMessage.clientInfoDecodingError.desc} Failed with error: ${caughtError}`);
}
/**

@@ -246,5 +247,5 @@ * Creates an error thrown if the client info is empty.

*/
ClientAuthError.createClientInfoEmptyError = function () {
return new ClientAuthError(ClientAuthErrorMessage.clientInfoEmptyError.code, "" + ClientAuthErrorMessage.clientInfoEmptyError.desc);
};
static createClientInfoEmptyError() {
return new ClientAuthError(ClientAuthErrorMessage.clientInfoEmptyError.code, `${ClientAuthErrorMessage.clientInfoEmptyError.desc}`);
}
/**

@@ -254,5 +255,5 @@ * Creates an error thrown when the id token extraction errors out.

*/
ClientAuthError.createTokenParsingError = function (caughtExtractionError) {
return new ClientAuthError(ClientAuthErrorMessage.tokenParsingError.code, ClientAuthErrorMessage.tokenParsingError.desc + " Failed with error: " + caughtExtractionError);
};
static createTokenParsingError(caughtExtractionError) {
return new ClientAuthError(ClientAuthErrorMessage.tokenParsingError.code, `${ClientAuthErrorMessage.tokenParsingError.desc} Failed with error: ${caughtExtractionError}`);
}
/**

@@ -262,23 +263,23 @@ * Creates an error thrown when the id token string is null or empty.

*/
ClientAuthError.createTokenNullOrEmptyError = function (invalidRawTokenString) {
return new ClientAuthError(ClientAuthErrorMessage.nullOrEmptyToken.code, ClientAuthErrorMessage.nullOrEmptyToken.desc + " Raw Token Value: " + invalidRawTokenString);
};
static createTokenNullOrEmptyError(invalidRawTokenString) {
return new ClientAuthError(ClientAuthErrorMessage.nullOrEmptyToken.code, `${ClientAuthErrorMessage.nullOrEmptyToken.desc} Raw Token Value: ${invalidRawTokenString}`);
}
/**
* Creates an error thrown when the endpoint discovery doesn't complete correctly.
*/
ClientAuthError.createEndpointDiscoveryIncompleteError = function (errDetail) {
return new ClientAuthError(ClientAuthErrorMessage.endpointResolutionError.code, ClientAuthErrorMessage.endpointResolutionError.desc + " Detail: " + errDetail);
};
static createEndpointDiscoveryIncompleteError(errDetail) {
return new ClientAuthError(ClientAuthErrorMessage.endpointResolutionError.code, `${ClientAuthErrorMessage.endpointResolutionError.desc} Detail: ${errDetail}`);
}
/**
* Creates an error thrown when the fetch client throws
*/
ClientAuthError.createNetworkError = function (endpoint, errDetail) {
return new ClientAuthError(ClientAuthErrorMessage.networkError.code, ClientAuthErrorMessage.networkError.desc + " | Fetch client threw: " + errDetail + " | Attempted to reach: " + endpoint.split("?")[0]);
};
static createNetworkError(endpoint, errDetail) {
return new ClientAuthError(ClientAuthErrorMessage.networkError.code, `${ClientAuthErrorMessage.networkError.desc} | Fetch client threw: ${errDetail} | Attempted to reach: ${endpoint.split("?")[0]}`);
}
/**
* Creates an error thrown when the openid-configuration endpoint cannot be reached or does not contain the required data
*/
ClientAuthError.createUnableToGetOpenidConfigError = function (errDetail) {
return new ClientAuthError(ClientAuthErrorMessage.unableToGetOpenidConfigError.code, ClientAuthErrorMessage.unableToGetOpenidConfigError.desc + " Attempted to retrieve endpoints from: " + errDetail);
};
static createUnableToGetOpenidConfigError(errDetail) {
return new ClientAuthError(ClientAuthErrorMessage.unableToGetOpenidConfigError.code, `${ClientAuthErrorMessage.unableToGetOpenidConfigError.desc} Attempted to retrieve endpoints from: ${errDetail}`);
}
/**

@@ -288,5 +289,5 @@ * Creates an error thrown when the hash cannot be deserialized.

*/
ClientAuthError.createHashNotDeserializedError = function (hashParamObj) {
return new ClientAuthError(ClientAuthErrorMessage.hashNotDeserialized.code, ClientAuthErrorMessage.hashNotDeserialized.desc + " Given Object: " + hashParamObj);
};
static createHashNotDeserializedError(hashParamObj) {
return new ClientAuthError(ClientAuthErrorMessage.hashNotDeserialized.code, `${ClientAuthErrorMessage.hashNotDeserialized.desc} Given Object: ${hashParamObj}`);
}
/**

@@ -296,11 +297,11 @@ * Creates an error thrown when the state cannot be parsed.

*/
ClientAuthError.createInvalidStateError = function (invalidState, errorString) {
return new ClientAuthError(ClientAuthErrorMessage.invalidStateError.code, ClientAuthErrorMessage.invalidStateError.desc + " Invalid State: " + invalidState + ", Root Err: " + errorString);
};
static createInvalidStateError(invalidState, errorString) {
return new ClientAuthError(ClientAuthErrorMessage.invalidStateError.code, `${ClientAuthErrorMessage.invalidStateError.desc} Invalid State: ${invalidState}, Root Err: ${errorString}`);
}
/**
* Creates an error thrown when two states do not match.
*/
ClientAuthError.createStateMismatchError = function () {
static createStateMismatchError() {
return new ClientAuthError(ClientAuthErrorMessage.stateMismatchError.code, ClientAuthErrorMessage.stateMismatchError.desc);
};
}
/**

@@ -310,11 +311,11 @@ * Creates an error thrown when the state is not present

*/
ClientAuthError.createStateNotFoundError = function (missingState) {
return new ClientAuthError(ClientAuthErrorMessage.stateNotFoundError.code, ClientAuthErrorMessage.stateNotFoundError.desc + ": " + missingState);
};
static createStateNotFoundError(missingState) {
return new ClientAuthError(ClientAuthErrorMessage.stateNotFoundError.code, `${ClientAuthErrorMessage.stateNotFoundError.desc}: ${missingState}`);
}
/**
* Creates an error thrown when the nonce does not match.
*/
ClientAuthError.createNonceMismatchError = function () {
static createNonceMismatchError() {
return new ClientAuthError(ClientAuthErrorMessage.nonceMismatchError.code, ClientAuthErrorMessage.nonceMismatchError.desc);
};
}
/**

@@ -324,11 +325,11 @@ * Creates an error thrown when max_age was provided in the request, but auth_time is not in the token claims

*/
ClientAuthError.createAuthTimeNotFoundError = function () {
static createAuthTimeNotFoundError() {
return new ClientAuthError(ClientAuthErrorMessage.authTimeNotFoundError.code, ClientAuthErrorMessage.authTimeNotFoundError.desc);
};
}
/**
* Creates an error thrown when too much time has elapsed since the last end-user authentication
*/
ClientAuthError.createMaxAgeTranspiredError = function () {
static createMaxAgeTranspiredError() {
return new ClientAuthError(ClientAuthErrorMessage.maxAgeTranspiredError.code, ClientAuthErrorMessage.maxAgeTranspiredError.desc);
};
}
/**

@@ -338,29 +339,29 @@ * Creates an error thrown when the mnonce is not present

*/
ClientAuthError.createNonceNotFoundError = function (missingNonce) {
return new ClientAuthError(ClientAuthErrorMessage.nonceNotFoundError.code, ClientAuthErrorMessage.nonceNotFoundError.desc + ": " + missingNonce);
};
static createNonceNotFoundError(missingNonce) {
return new ClientAuthError(ClientAuthErrorMessage.nonceNotFoundError.code, `${ClientAuthErrorMessage.nonceNotFoundError.desc}: ${missingNonce}`);
}
/**
* Throws error when multiple tokens are in cache.
*/
ClientAuthError.createMultipleMatchingTokensInCacheError = function () {
return new ClientAuthError(ClientAuthErrorMessage.multipleMatchingTokens.code, ClientAuthErrorMessage.multipleMatchingTokens.desc + ".");
};
static createMultipleMatchingTokensInCacheError() {
return new ClientAuthError(ClientAuthErrorMessage.multipleMatchingTokens.code, `${ClientAuthErrorMessage.multipleMatchingTokens.desc}.`);
}
/**
* Throws error when multiple accounts are in cache for the given params
*/
ClientAuthError.createMultipleMatchingAccountsInCacheError = function () {
static createMultipleMatchingAccountsInCacheError() {
return new ClientAuthError(ClientAuthErrorMessage.multipleMatchingAccounts.code, ClientAuthErrorMessage.multipleMatchingAccounts.desc);
};
}
/**
* Throws error when multiple appMetada are in cache for the given clientId.
*/
ClientAuthError.createMultipleMatchingAppMetadataInCacheError = function () {
static createMultipleMatchingAppMetadataInCacheError() {
return new ClientAuthError(ClientAuthErrorMessage.multipleMatchingAppMetadata.code, ClientAuthErrorMessage.multipleMatchingAppMetadata.desc);
};
}
/**
* Throws error when no auth code or refresh token is given to ServerTokenRequestParameters.
*/
ClientAuthError.createTokenRequestCannotBeMadeError = function () {
static createTokenRequestCannotBeMadeError() {
return new ClientAuthError(ClientAuthErrorMessage.tokenRequestCannotBeMade.code, ClientAuthErrorMessage.tokenRequestCannotBeMade.desc);
};
}
/**

@@ -370,5 +371,5 @@ * Throws error when attempting to append a null, undefined or empty scope to a set

*/
ClientAuthError.createAppendEmptyScopeToSetError = function (givenScope) {
return new ClientAuthError(ClientAuthErrorMessage.appendEmptyScopeError.code, ClientAuthErrorMessage.appendEmptyScopeError.desc + " Given Scope: " + givenScope);
};
static createAppendEmptyScopeToSetError(givenScope) {
return new ClientAuthError(ClientAuthErrorMessage.appendEmptyScopeError.code, `${ClientAuthErrorMessage.appendEmptyScopeError.desc} Given Scope: ${givenScope}`);
}
/**

@@ -378,5 +379,5 @@ * Throws error when attempting to append a null, undefined or empty scope to a set

*/
ClientAuthError.createRemoveEmptyScopeFromSetError = function (givenScope) {
return new ClientAuthError(ClientAuthErrorMessage.removeEmptyScopeError.code, ClientAuthErrorMessage.removeEmptyScopeError.desc + " Given Scope: " + givenScope);
};
static createRemoveEmptyScopeFromSetError(givenScope) {
return new ClientAuthError(ClientAuthErrorMessage.removeEmptyScopeError.code, `${ClientAuthErrorMessage.removeEmptyScopeError.desc} Given Scope: ${givenScope}`);
}
/**

@@ -386,5 +387,5 @@ * Throws error when attempting to append null or empty ScopeSet.

*/
ClientAuthError.createAppendScopeSetError = function (appendError) {
return new ClientAuthError(ClientAuthErrorMessage.appendScopeSetError.code, ClientAuthErrorMessage.appendScopeSetError.desc + " Detail Error: " + appendError);
};
static createAppendScopeSetError(appendError) {
return new ClientAuthError(ClientAuthErrorMessage.appendScopeSetError.code, `${ClientAuthErrorMessage.appendScopeSetError.desc} Detail Error: ${appendError}`);
}
/**

@@ -394,53 +395,53 @@ * Throws error if ScopeSet is null or undefined.

*/
ClientAuthError.createEmptyInputScopeSetError = function () {
return new ClientAuthError(ClientAuthErrorMessage.emptyInputScopeSetError.code, "" + ClientAuthErrorMessage.emptyInputScopeSetError.desc);
};
static createEmptyInputScopeSetError() {
return new ClientAuthError(ClientAuthErrorMessage.emptyInputScopeSetError.code, `${ClientAuthErrorMessage.emptyInputScopeSetError.desc}`);
}
/**
* Throws error if user sets CancellationToken.cancel = true during polling of token endpoint during device code flow
*/
ClientAuthError.createDeviceCodeCancelledError = function () {
return new ClientAuthError(ClientAuthErrorMessage.DeviceCodePollingCancelled.code, "" + ClientAuthErrorMessage.DeviceCodePollingCancelled.desc);
};
static createDeviceCodeCancelledError() {
return new ClientAuthError(ClientAuthErrorMessage.DeviceCodePollingCancelled.code, `${ClientAuthErrorMessage.DeviceCodePollingCancelled.desc}`);
}
/**
* Throws error if device code is expired
*/
ClientAuthError.createDeviceCodeExpiredError = function () {
return new ClientAuthError(ClientAuthErrorMessage.DeviceCodeExpired.code, "" + ClientAuthErrorMessage.DeviceCodeExpired.desc);
};
static createDeviceCodeExpiredError() {
return new ClientAuthError(ClientAuthErrorMessage.DeviceCodeExpired.code, `${ClientAuthErrorMessage.DeviceCodeExpired.desc}`);
}
/**
* Throws error if device code is expired
*/
ClientAuthError.createDeviceCodeUnknownError = function () {
return new ClientAuthError(ClientAuthErrorMessage.DeviceCodeUnknownError.code, "" + ClientAuthErrorMessage.DeviceCodeUnknownError.desc);
};
static createDeviceCodeUnknownError() {
return new ClientAuthError(ClientAuthErrorMessage.DeviceCodeUnknownError.code, `${ClientAuthErrorMessage.DeviceCodeUnknownError.desc}`);
}
/**
* Throws error when silent requests are made without an account object
*/
ClientAuthError.createNoAccountInSilentRequestError = function () {
return new ClientAuthError(ClientAuthErrorMessage.NoAccountInSilentRequest.code, "" + ClientAuthErrorMessage.NoAccountInSilentRequest.desc);
};
static createNoAccountInSilentRequestError() {
return new ClientAuthError(ClientAuthErrorMessage.NoAccountInSilentRequest.code, `${ClientAuthErrorMessage.NoAccountInSilentRequest.desc}`);
}
/**
* Throws error when cache record is null or undefined.
*/
ClientAuthError.createNullOrUndefinedCacheRecord = function () {
static createNullOrUndefinedCacheRecord() {
return new ClientAuthError(ClientAuthErrorMessage.invalidCacheRecord.code, ClientAuthErrorMessage.invalidCacheRecord.desc);
};
}
/**
* Throws error when provided environment is not part of the CloudDiscoveryMetadata object
*/
ClientAuthError.createInvalidCacheEnvironmentError = function () {
static createInvalidCacheEnvironmentError() {
return new ClientAuthError(ClientAuthErrorMessage.invalidCacheEnvironment.code, ClientAuthErrorMessage.invalidCacheEnvironment.desc);
};
}
/**
* Throws error when account is not found in cache.
*/
ClientAuthError.createNoAccountFoundError = function () {
static createNoAccountFoundError() {
return new ClientAuthError(ClientAuthErrorMessage.noAccountFound.code, ClientAuthErrorMessage.noAccountFound.desc);
};
}
/**
* Throws error if ICachePlugin not set on CacheManager.
*/
ClientAuthError.createCachePluginError = function () {
return new ClientAuthError(ClientAuthErrorMessage.CachePluginError.code, "" + ClientAuthErrorMessage.CachePluginError.desc);
};
static createCachePluginError() {
return new ClientAuthError(ClientAuthErrorMessage.CachePluginError.code, `${ClientAuthErrorMessage.CachePluginError.desc}`);
}
/**

@@ -450,90 +451,95 @@ * Throws error if crypto object not found.

*/
ClientAuthError.createNoCryptoObjectError = function (operationName) {
return new ClientAuthError(ClientAuthErrorMessage.noCryptoObj.code, "" + ClientAuthErrorMessage.noCryptoObj.desc + operationName);
};
static createNoCryptoObjectError(operationName) {
return new ClientAuthError(ClientAuthErrorMessage.noCryptoObj.code, `${ClientAuthErrorMessage.noCryptoObj.desc}${operationName}`);
}
/**
* Throws error if cache type is invalid.
*/
ClientAuthError.createInvalidCacheTypeError = function () {
return new ClientAuthError(ClientAuthErrorMessage.invalidCacheType.code, "" + ClientAuthErrorMessage.invalidCacheType.desc);
};
static createInvalidCacheTypeError() {
return new ClientAuthError(ClientAuthErrorMessage.invalidCacheType.code, `${ClientAuthErrorMessage.invalidCacheType.desc}`);
}
/**
* Throws error if unexpected account type.
*/
ClientAuthError.createUnexpectedAccountTypeError = function () {
return new ClientAuthError(ClientAuthErrorMessage.unexpectedAccountType.code, "" + ClientAuthErrorMessage.unexpectedAccountType.desc);
};
static createUnexpectedAccountTypeError() {
return new ClientAuthError(ClientAuthErrorMessage.unexpectedAccountType.code, `${ClientAuthErrorMessage.unexpectedAccountType.desc}`);
}
/**
* Throws error if unexpected credential type.
*/
ClientAuthError.createUnexpectedCredentialTypeError = function () {
return new ClientAuthError(ClientAuthErrorMessage.unexpectedCredentialType.code, "" + ClientAuthErrorMessage.unexpectedCredentialType.desc);
};
static createUnexpectedCredentialTypeError() {
return new ClientAuthError(ClientAuthErrorMessage.unexpectedCredentialType.code, `${ClientAuthErrorMessage.unexpectedCredentialType.desc}`);
}
/**
* Throws error if client assertion is not valid.
*/
ClientAuthError.createInvalidAssertionError = function () {
return new ClientAuthError(ClientAuthErrorMessage.invalidAssertion.code, "" + ClientAuthErrorMessage.invalidAssertion.desc);
};
static createInvalidAssertionError() {
return new ClientAuthError(ClientAuthErrorMessage.invalidAssertion.code, `${ClientAuthErrorMessage.invalidAssertion.desc}`);
}
/**
* Throws error if client assertion is not valid.
*/
ClientAuthError.createInvalidCredentialError = function () {
return new ClientAuthError(ClientAuthErrorMessage.invalidClientCredential.code, "" + ClientAuthErrorMessage.invalidClientCredential.desc);
};
static createInvalidCredentialError() {
return new ClientAuthError(ClientAuthErrorMessage.invalidClientCredential.code, `${ClientAuthErrorMessage.invalidClientCredential.desc}`);
}
/**
* Throws error if token cannot be retrieved from cache due to refresh being required.
*/
ClientAuthError.createRefreshRequiredError = function () {
static createRefreshRequiredError() {
return new ClientAuthError(ClientAuthErrorMessage.tokenRefreshRequired.code, ClientAuthErrorMessage.tokenRefreshRequired.desc);
};
}
/**
* Throws error if the user defined timeout is reached.
*/
ClientAuthError.createUserTimeoutReachedError = function () {
static createUserTimeoutReachedError() {
return new ClientAuthError(ClientAuthErrorMessage.userTimeoutReached.code, ClientAuthErrorMessage.userTimeoutReached.desc);
};
}
/*
* Throws error if token claims are not populated for a signed jwt generation
*/
ClientAuthError.createTokenClaimsRequiredError = function () {
static createTokenClaimsRequiredError() {
return new ClientAuthError(ClientAuthErrorMessage.tokenClaimsRequired.code, ClientAuthErrorMessage.tokenClaimsRequired.desc);
};
}
/**
* Throws error when the authorization code is missing from the server response
*/
ClientAuthError.createNoAuthCodeInServerResponseError = function () {
static createNoAuthCodeInServerResponseError() {
return new ClientAuthError(ClientAuthErrorMessage.noAuthorizationCodeFromServer.code, ClientAuthErrorMessage.noAuthorizationCodeFromServer.desc);
};
ClientAuthError.createBindingKeyNotRemovedError = function () {
}
static createBindingKeyNotRemovedError() {
return new ClientAuthError(ClientAuthErrorMessage.bindingKeyNotRemovedError.code, ClientAuthErrorMessage.bindingKeyNotRemovedError.desc);
};
}
/**
* Thrown when logout is attempted for an authority that doesnt have an end_session_endpoint
*/
ClientAuthError.createLogoutNotSupportedError = function () {
static createLogoutNotSupportedError() {
return new ClientAuthError(ClientAuthErrorMessage.logoutNotSupported.code, ClientAuthErrorMessage.logoutNotSupported.desc);
};
}
/**
* Create an error when kid attribute is missing from a PoP token's cache record
*/
ClientAuthError.createKeyIdMissingError = function () {
static createKeyIdMissingError() {
return new ClientAuthError(ClientAuthErrorMessage.keyIdMissing.code, ClientAuthErrorMessage.keyIdMissing.desc);
};
}
/**
* Create an error when the client does not have network connectivity
*/
ClientAuthError.createNoNetworkConnectivityError = function () {
static createNoNetworkConnectivityError() {
return new ClientAuthError(ClientAuthErrorMessage.noNetworkConnectivity.code, ClientAuthErrorMessage.noNetworkConnectivity.desc);
};
}
/**
* Create an error when the user cancels the flow
*/
ClientAuthError.createUserCanceledError = function () {
static createUserCanceledError() {
return new ClientAuthError(ClientAuthErrorMessage.userCanceledError.code, ClientAuthErrorMessage.userCanceledError.desc);
};
return ClientAuthError;
}(AuthError));
}
/**
* Creates an error for during acquireTokenByClientCredential when TenantId is set to "common" or "organizations"
*/
static createMissingTenantIdError() {
return new AuthError(ClientAuthErrorMessage.missingTenantIdError.code, ClientAuthErrorMessage.missingTenantIdError.desc);
}
}
export { ClientAuthError, ClientAuthErrorMessage };
//# sourceMappingURL=ClientAuthError.js.map

@@ -1,4 +0,3 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';
import { __extends } from '../_virtual/_tslib.js';
import { ClientAuthError } from './ClientAuthError.js';

@@ -13,38 +12,38 @@

*/
var ClientConfigurationErrorMessage = {
const ClientConfigurationErrorMessage = {
redirectUriNotSet: {
code: "redirect_uri_empty",
desc: "A redirect URI is required for all calls, and none has been set."
desc: "A redirect URI is required for all calls, and none has been set.",
},
postLogoutUriNotSet: {
code: "post_logout_uri_empty",
desc: "A post logout redirect has not been set."
desc: "A post logout redirect has not been set.",
},
claimsRequestParsingError: {
code: "claims_request_parsing_error",
desc: "Could not parse the given claims request object."
desc: "Could not parse the given claims request object.",
},
authorityUriInsecure: {
code: "authority_uri_insecure",
desc: "Authority URIs must use https. Please see here for valid authority configuration options: https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-js-initializing-client-applications#configuration-options"
desc: "Authority URIs must use https. Please see here for valid authority configuration options: https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-js-initializing-client-applications#configuration-options",
},
urlParseError: {
code: "url_parse_error",
desc: "URL could not be parsed into appropriate segments."
desc: "URL could not be parsed into appropriate segments.",
},
urlEmptyError: {
code: "empty_url_error",
desc: "URL was empty or null."
desc: "URL was empty or null.",
},
emptyScopesError: {
code: "empty_input_scopes_error",
desc: "Scopes cannot be passed as null, undefined or empty array because they are required to obtain an access token."
desc: "Scopes cannot be passed as null, undefined or empty array because they are required to obtain an access token.",
},
nonArrayScopesError: {
code: "nonarray_input_scopes_error",
desc: "Scopes cannot be passed as non-array."
desc: "Scopes cannot be passed as non-array.",
},
clientIdSingleScopeError: {
code: "clientid_input_scopes_error",
desc: "Client ID can only be provided as a single scope."
desc: "Client ID can only be provided as a single scope.",
},

@@ -57,52 +56,52 @@ invalidPrompt: {

code: "invalid_claims",
desc: "Given claims parameter must be a stringified JSON object."
desc: "Given claims parameter must be a stringified JSON object.",
},
tokenRequestEmptyError: {
code: "token_request_empty",
desc: "Token request was empty and not found in cache."
desc: "Token request was empty and not found in cache.",
},
logoutRequestEmptyError: {
code: "logout_request_empty",
desc: "The logout request was null or undefined."
desc: "The logout request was null or undefined.",
},
invalidCodeChallengeMethod: {
code: "invalid_code_challenge_method",
desc: "code_challenge_method passed is invalid. Valid values are \"plain\" and \"S256\"."
desc: 'code_challenge_method passed is invalid. Valid values are "plain" and "S256".',
},
invalidCodeChallengeParams: {
code: "pkce_params_missing",
desc: "Both params: code_challenge and code_challenge_method are to be passed if to be sent in the request"
desc: "Both params: code_challenge and code_challenge_method are to be passed if to be sent in the request",
},
invalidCloudDiscoveryMetadata: {
code: "invalid_cloud_discovery_metadata",
desc: "Invalid cloudDiscoveryMetadata provided. Must be a stringified JSON object containing tenant_discovery_endpoint and metadata fields"
desc: "Invalid cloudDiscoveryMetadata provided. Must be a stringified JSON object containing tenant_discovery_endpoint and metadata fields",
},
invalidAuthorityMetadata: {
code: "invalid_authority_metadata",
desc: "Invalid authorityMetadata provided. Must by a stringified JSON object containing authorization_endpoint, token_endpoint, issuer fields."
desc: "Invalid authorityMetadata provided. Must by a stringified JSON object containing authorization_endpoint, token_endpoint, issuer fields.",
},
untrustedAuthority: {
code: "untrusted_authority",
desc: "The provided authority is not a trusted authority. Please include this authority in the knownAuthorities config parameter."
desc: "The provided authority is not a trusted authority. Please include this authority in the knownAuthorities config parameter.",
},
invalidAzureCloudInstance: {
code: "invalid_azure_cloud_instance",
desc: "Invalid AzureCloudInstance provided. Please refer MSAL JS docs: aks.ms/msaljs/azure_cloud_instance for valid values"
desc: "Invalid AzureCloudInstance provided. Please refer MSAL JS docs: aks.ms/msaljs/azure_cloud_instance for valid values",
},
missingSshJwk: {
code: "missing_ssh_jwk",
desc: "Missing sshJwk in SSH certificate request. A stringified JSON Web Key is required when using the SSH authentication scheme."
desc: "Missing sshJwk in SSH certificate request. A stringified JSON Web Key is required when using the SSH authentication scheme.",
},
missingSshKid: {
code: "missing_ssh_kid",
desc: "Missing sshKid in SSH certificate request. A string that uniquely identifies the public SSH key is required when using the SSH authentication scheme."
desc: "Missing sshKid in SSH certificate request. A string that uniquely identifies the public SSH key is required when using the SSH authentication scheme.",
},
missingNonceAuthenticationHeader: {
code: "missing_nonce_authentication_header",
desc: "Unable to find an authentication header containing server nonce. Either the Authentication-Info or WWW-Authenticate headers must be present in order to obtain a server nonce."
desc: "Unable to find an authentication header containing server nonce. Either the Authentication-Info or WWW-Authenticate headers must be present in order to obtain a server nonce.",
},
invalidAuthenticationHeader: {
code: "invalid_authentication_header",
desc: "Invalid authentication header provided"
}
desc: "Invalid authentication header provided",
},
};

@@ -112,9 +111,7 @@ /**

*/
var ClientConfigurationError = /** @class */ (function (_super) {
__extends(ClientConfigurationError, _super);
function ClientConfigurationError(errorCode, errorMessage) {
var _this = _super.call(this, errorCode, errorMessage) || this;
_this.name = "ClientConfigurationError";
Object.setPrototypeOf(_this, ClientConfigurationError.prototype);
return _this;
class ClientConfigurationError extends ClientAuthError {
constructor(errorCode, errorMessage) {
super(errorCode, errorMessage);
this.name = "ClientConfigurationError";
Object.setPrototypeOf(this, ClientConfigurationError.prototype);
}

@@ -124,17 +121,17 @@ /**

*/
ClientConfigurationError.createRedirectUriEmptyError = function () {
static createRedirectUriEmptyError() {
return new ClientConfigurationError(ClientConfigurationErrorMessage.redirectUriNotSet.code, ClientConfigurationErrorMessage.redirectUriNotSet.desc);
};
}
/**
* Creates an error thrown when the post-logout redirect uri is empty (not set by caller)
*/
ClientConfigurationError.createPostLogoutRedirectUriEmptyError = function () {
static createPostLogoutRedirectUriEmptyError() {
return new ClientConfigurationError(ClientConfigurationErrorMessage.postLogoutUriNotSet.code, ClientConfigurationErrorMessage.postLogoutUriNotSet.desc);
};
}
/**
* Creates an error thrown when the claims request could not be successfully parsed
*/
ClientConfigurationError.createClaimsRequestParsingError = function (claimsRequestParseError) {
return new ClientConfigurationError(ClientConfigurationErrorMessage.claimsRequestParsingError.code, ClientConfigurationErrorMessage.claimsRequestParsingError.desc + " Given value: " + claimsRequestParseError);
};
static createClaimsRequestParsingError(claimsRequestParseError) {
return new ClientConfigurationError(ClientConfigurationErrorMessage.claimsRequestParsingError.code, `${ClientConfigurationErrorMessage.claimsRequestParsingError.desc} Given value: ${claimsRequestParseError}`);
}
/**

@@ -144,5 +141,5 @@ * Creates an error thrown if authority uri is given an insecure protocol.

*/
ClientConfigurationError.createInsecureAuthorityUriError = function (urlString) {
return new ClientConfigurationError(ClientConfigurationErrorMessage.authorityUriInsecure.code, ClientConfigurationErrorMessage.authorityUriInsecure.desc + " Given URI: " + urlString);
};
static createInsecureAuthorityUriError(urlString) {
return new ClientConfigurationError(ClientConfigurationErrorMessage.authorityUriInsecure.code, `${ClientConfigurationErrorMessage.authorityUriInsecure.desc} Given URI: ${urlString}`);
}
/**

@@ -152,5 +149,5 @@ * Creates an error thrown if URL string does not parse into separate segments.

*/
ClientConfigurationError.createUrlParseError = function (urlParseError) {
return new ClientConfigurationError(ClientConfigurationErrorMessage.urlParseError.code, ClientConfigurationErrorMessage.urlParseError.desc + " Given Error: " + urlParseError);
};
static createUrlParseError(urlParseError) {
return new ClientConfigurationError(ClientConfigurationErrorMessage.urlParseError.code, `${ClientConfigurationErrorMessage.urlParseError.desc} Given Error: ${urlParseError}`);
}
/**

@@ -160,5 +157,5 @@ * Creates an error thrown if URL string is empty or null.

*/
ClientConfigurationError.createUrlEmptyError = function () {
static createUrlEmptyError() {
return new ClientConfigurationError(ClientConfigurationErrorMessage.urlEmptyError.code, ClientConfigurationErrorMessage.urlEmptyError.desc);
};
}
/**

@@ -168,5 +165,5 @@ * Error thrown when scopes are empty.

*/
ClientConfigurationError.createEmptyScopesArrayError = function () {
return new ClientConfigurationError(ClientConfigurationErrorMessage.emptyScopesError.code, "" + ClientConfigurationErrorMessage.emptyScopesError.desc);
};
static createEmptyScopesArrayError() {
return new ClientConfigurationError(ClientConfigurationErrorMessage.emptyScopesError.code, `${ClientConfigurationErrorMessage.emptyScopesError.desc}`);
}
/**

@@ -176,5 +173,5 @@ * Error thrown when client id scope is not provided as single scope.

*/
ClientConfigurationError.createClientIdSingleScopeError = function (inputScopes) {
return new ClientConfigurationError(ClientConfigurationErrorMessage.clientIdSingleScopeError.code, ClientConfigurationErrorMessage.clientIdSingleScopeError.desc + " Given Scopes: " + inputScopes);
};
static createClientIdSingleScopeError(inputScopes) {
return new ClientConfigurationError(ClientConfigurationErrorMessage.clientIdSingleScopeError.code, `${ClientConfigurationErrorMessage.clientIdSingleScopeError.desc} Given Scopes: ${inputScopes}`);
}
/**

@@ -184,87 +181,86 @@ * Error thrown when prompt is not an allowed type.

*/
ClientConfigurationError.createInvalidPromptError = function (promptValue) {
return new ClientConfigurationError(ClientConfigurationErrorMessage.invalidPrompt.code, ClientConfigurationErrorMessage.invalidPrompt.desc + " Given value: " + promptValue);
};
static createInvalidPromptError(promptValue) {
return new ClientConfigurationError(ClientConfigurationErrorMessage.invalidPrompt.code, `${ClientConfigurationErrorMessage.invalidPrompt.desc} Given value: ${promptValue}`);
}
/**
* Creates error thrown when claims parameter is not a stringified JSON object
*/
ClientConfigurationError.createInvalidClaimsRequestError = function () {
static createInvalidClaimsRequestError() {
return new ClientConfigurationError(ClientConfigurationErrorMessage.invalidClaimsRequest.code, ClientConfigurationErrorMessage.invalidClaimsRequest.desc);
};
}
/**
* Throws error when token request is empty and nothing cached in storage.
*/
ClientConfigurationError.createEmptyLogoutRequestError = function () {
static createEmptyLogoutRequestError() {
return new ClientConfigurationError(ClientConfigurationErrorMessage.logoutRequestEmptyError.code, ClientConfigurationErrorMessage.logoutRequestEmptyError.desc);
};
}
/**
* Throws error when token request is empty and nothing cached in storage.
*/
ClientConfigurationError.createEmptyTokenRequestError = function () {
static createEmptyTokenRequestError() {
return new ClientConfigurationError(ClientConfigurationErrorMessage.tokenRequestEmptyError.code, ClientConfigurationErrorMessage.tokenRequestEmptyError.desc);
};
}
/**
* Throws error when an invalid code_challenge_method is passed by the user
*/
ClientConfigurationError.createInvalidCodeChallengeMethodError = function () {
static createInvalidCodeChallengeMethodError() {
return new ClientConfigurationError(ClientConfigurationErrorMessage.invalidCodeChallengeMethod.code, ClientConfigurationErrorMessage.invalidCodeChallengeMethod.desc);
};
}
/**
* Throws error when both params: code_challenge and code_challenge_method are not passed together
*/
ClientConfigurationError.createInvalidCodeChallengeParamsError = function () {
static createInvalidCodeChallengeParamsError() {
return new ClientConfigurationError(ClientConfigurationErrorMessage.invalidCodeChallengeParams.code, ClientConfigurationErrorMessage.invalidCodeChallengeParams.desc);
};
}
/**
* Throws an error when the user passes invalid cloudDiscoveryMetadata
*/
ClientConfigurationError.createInvalidCloudDiscoveryMetadataError = function () {
static createInvalidCloudDiscoveryMetadataError() {
return new ClientConfigurationError(ClientConfigurationErrorMessage.invalidCloudDiscoveryMetadata.code, ClientConfigurationErrorMessage.invalidCloudDiscoveryMetadata.desc);
};
}
/**
* Throws an error when the user passes invalid cloudDiscoveryMetadata
*/
ClientConfigurationError.createInvalidAuthorityMetadataError = function () {
static createInvalidAuthorityMetadataError() {
return new ClientConfigurationError(ClientConfigurationErrorMessage.invalidAuthorityMetadata.code, ClientConfigurationErrorMessage.invalidAuthorityMetadata.desc);
};
}
/**
* Throws error when provided authority is not a member of the trusted host list
*/
ClientConfigurationError.createUntrustedAuthorityError = function () {
static createUntrustedAuthorityError() {
return new ClientConfigurationError(ClientConfigurationErrorMessage.untrustedAuthority.code, ClientConfigurationErrorMessage.untrustedAuthority.desc);
};
}
/**
* Throws error when the AzureCloudInstance is set to an invalid value
*/
ClientConfigurationError.createInvalidAzureCloudInstanceError = function () {
static createInvalidAzureCloudInstanceError() {
return new ClientConfigurationError(ClientConfigurationErrorMessage.invalidAzureCloudInstance.code, ClientConfigurationErrorMessage.invalidAzureCloudInstance.desc);
};
}
/**
* Throws an error when the authentication scheme is set to SSH but the SSH public key is omitted from the request
*/
ClientConfigurationError.createMissingSshJwkError = function () {
static createMissingSshJwkError() {
return new ClientConfigurationError(ClientConfigurationErrorMessage.missingSshJwk.code, ClientConfigurationErrorMessage.missingSshJwk.desc);
};
}
/**
* Throws an error when the authentication scheme is set to SSH but the SSH public key ID is omitted from the request
*/
ClientConfigurationError.createMissingSshKidError = function () {
static createMissingSshKidError() {
return new ClientConfigurationError(ClientConfigurationErrorMessage.missingSshKid.code, ClientConfigurationErrorMessage.missingSshKid.desc);
};
}
/**
* Throws error when provided headers don't contain a header that a server nonce can be extracted from
*/
ClientConfigurationError.createMissingNonceAuthenticationHeadersError = function () {
static createMissingNonceAuthenticationHeadersError() {
return new ClientConfigurationError(ClientConfigurationErrorMessage.missingNonceAuthenticationHeader.code, ClientConfigurationErrorMessage.missingNonceAuthenticationHeader.desc);
};
}
/**
* Throws error when a provided header is invalid in any way
*/
ClientConfigurationError.createInvalidAuthenticationHeaderError = function (invalidHeaderName, details) {
return new ClientConfigurationError(ClientConfigurationErrorMessage.invalidAuthenticationHeader.code, ClientConfigurationErrorMessage.invalidAuthenticationHeader.desc + ". Invalid header: " + invalidHeaderName + ". Details: " + details);
};
return ClientConfigurationError;
}(ClientAuthError));
static createInvalidAuthenticationHeaderError(invalidHeaderName, details) {
return new ClientConfigurationError(ClientConfigurationErrorMessage.invalidAuthenticationHeader.code, `${ClientConfigurationErrorMessage.invalidAuthenticationHeader.desc}. Invalid header: ${invalidHeaderName}. Details: ${details}`);
}
}
export { ClientConfigurationError, ClientConfigurationErrorMessage };
//# sourceMappingURL=ClientConfigurationError.js.map

@@ -1,4 +0,3 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';
import { __extends } from '../_virtual/_tslib.js';
import { Constants } from '../utils/Constants.js';

@@ -14,8 +13,8 @@ import { AuthError } from './AuthError.js';

*/
var InteractionRequiredServerErrorMessage = [
const InteractionRequiredServerErrorMessage = [
"interaction_required",
"consent_required",
"login_required"
"login_required",
];
var InteractionRequiredAuthSubErrorMessage = [
const InteractionRequiredAuthSubErrorMessage = [
"message_only",

@@ -25,3 +24,3 @@ "additional_action",

"user_password_expired",
"consent_required"
"consent_required",
];

@@ -31,11 +30,11 @@ /**

*/
var InteractionRequiredAuthErrorMessage = {
const InteractionRequiredAuthErrorMessage = {
noTokensFoundError: {
code: "no_tokens_found",
desc: "No refresh token found in the cache. Please sign-in."
desc: "No refresh token found in the cache. Please sign-in.",
},
native_account_unavailable: {
code: "native_account_unavailable",
desc: "The requested account is not available in the native broker. It may have been deleted or logged out. Please sign-in again using an interactive API."
}
desc: "The requested account is not available in the native broker. It may have been deleted or logged out. Please sign-in again using an interactive API.",
},
};

@@ -45,13 +44,11 @@ /**

*/
var InteractionRequiredAuthError = /** @class */ (function (_super) {
__extends(InteractionRequiredAuthError, _super);
function InteractionRequiredAuthError(errorCode, errorMessage, subError, timestamp, traceId, correlationId, claims) {
var _this = _super.call(this, errorCode, errorMessage, subError) || this;
Object.setPrototypeOf(_this, InteractionRequiredAuthError.prototype);
_this.timestamp = timestamp || Constants.EMPTY_STRING;
_this.traceId = traceId || Constants.EMPTY_STRING;
_this.correlationId = correlationId || Constants.EMPTY_STRING;
_this.claims = claims || Constants.EMPTY_STRING;
_this.name = "InteractionRequiredAuthError";
return _this;
class InteractionRequiredAuthError extends AuthError {
constructor(errorCode, errorMessage, subError, timestamp, traceId, correlationId, claims) {
super(errorCode, errorMessage, subError);
Object.setPrototypeOf(this, InteractionRequiredAuthError.prototype);
this.timestamp = timestamp || Constants.EMPTY_STRING;
this.traceId = traceId || Constants.EMPTY_STRING;
this.correlationId = correlationId || Constants.EMPTY_STRING;
this.claims = claims || Constants.EMPTY_STRING;
this.name = "InteractionRequiredAuthError";
}

@@ -64,16 +61,21 @@ /**

*/
InteractionRequiredAuthError.isInteractionRequiredError = function (errorCode, errorString, subError) {
var isInteractionRequiredErrorCode = !!errorCode && InteractionRequiredServerErrorMessage.indexOf(errorCode) > -1;
var isInteractionRequiredSubError = !!subError && InteractionRequiredAuthSubErrorMessage.indexOf(subError) > -1;
var isInteractionRequiredErrorDesc = !!errorString && InteractionRequiredServerErrorMessage.some(function (irErrorCode) {
return errorString.indexOf(irErrorCode) > -1;
});
return isInteractionRequiredErrorCode || isInteractionRequiredErrorDesc || isInteractionRequiredSubError;
};
static isInteractionRequiredError(errorCode, errorString, subError) {
const isInteractionRequiredErrorCode = !!errorCode &&
InteractionRequiredServerErrorMessage.indexOf(errorCode) > -1;
const isInteractionRequiredSubError = !!subError &&
InteractionRequiredAuthSubErrorMessage.indexOf(subError) > -1;
const isInteractionRequiredErrorDesc = !!errorString &&
InteractionRequiredServerErrorMessage.some((irErrorCode) => {
return errorString.indexOf(irErrorCode) > -1;
});
return (isInteractionRequiredErrorCode ||
isInteractionRequiredErrorDesc ||
isInteractionRequiredSubError);
}
/**
* Creates an error thrown when the authorization code required for a token request is null or empty.
*/
InteractionRequiredAuthError.createNoTokensFoundError = function () {
static createNoTokensFoundError() {
return new InteractionRequiredAuthError(InteractionRequiredAuthErrorMessage.noTokensFoundError.code, InteractionRequiredAuthErrorMessage.noTokensFoundError.desc);
};
}
/**

@@ -83,9 +85,8 @@ * Creates an error thrown when the native broker returns ACCOUNT_UNAVAILABLE status, indicating that the account was removed and interactive sign-in is required

*/
InteractionRequiredAuthError.createNativeAccountUnavailableError = function () {
static createNativeAccountUnavailableError() {
return new InteractionRequiredAuthError(InteractionRequiredAuthErrorMessage.native_account_unavailable.code, InteractionRequiredAuthErrorMessage.native_account_unavailable.desc);
};
return InteractionRequiredAuthError;
}(AuthError));
}
}
export { InteractionRequiredAuthError, InteractionRequiredAuthErrorMessage, InteractionRequiredAuthSubErrorMessage, InteractionRequiredServerErrorMessage };
//# sourceMappingURL=InteractionRequiredAuthError.js.map

@@ -1,4 +0,3 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';
import { __extends } from '../_virtual/_tslib.js';
import { AuthError } from './AuthError.js';

@@ -13,10 +12,10 @@

*/
var JoseHeaderErrorMessage = {
const JoseHeaderErrorMessage = {
missingKidError: {
code: "missing_kid_error",
desc: "The JOSE Header for the requested JWT, JWS or JWK object requires a keyId to be configured as the 'kid' header claim. No 'kid' value was provided."
desc: "The JOSE Header for the requested JWT, JWS or JWK object requires a keyId to be configured as the 'kid' header claim. No 'kid' value was provided.",
},
missingAlgError: {
code: "missing_alg_error",
desc: "The JOSE Header for the requested JWT, JWS or JWK object requires an algorithm to be specified as the 'alg' header claim. No 'alg' value was provided."
desc: "The JOSE Header for the requested JWT, JWS or JWK object requires an algorithm to be specified as the 'alg' header claim. No 'alg' value was provided.",
},

@@ -27,9 +26,7 @@ };

*/
var JoseHeaderError = /** @class */ (function (_super) {
__extends(JoseHeaderError, _super);
function JoseHeaderError(errorCode, errorMessage) {
var _this = _super.call(this, errorCode, errorMessage) || this;
_this.name = "JoseHeaderError";
Object.setPrototypeOf(_this, JoseHeaderError.prototype);
return _this;
class JoseHeaderError extends AuthError {
constructor(errorCode, errorMessage) {
super(errorCode, errorMessage);
this.name = "JoseHeaderError";
Object.setPrototypeOf(this, JoseHeaderError.prototype);
}

@@ -39,15 +36,14 @@ /**

*/
JoseHeaderError.createMissingKidError = function () {
static createMissingKidError() {
return new JoseHeaderError(JoseHeaderErrorMessage.missingKidError.code, JoseHeaderErrorMessage.missingKidError.desc);
};
}
/**
* Creates an error thrown when algorithm isn't set on JOSE header.
*/
JoseHeaderError.createMissingAlgError = function () {
static createMissingAlgError() {
return new JoseHeaderError(JoseHeaderErrorMessage.missingAlgError.code, JoseHeaderErrorMessage.missingAlgError.desc);
};
return JoseHeaderError;
}(AuthError));
}
}
export { JoseHeaderError, JoseHeaderErrorMessage };
//# sourceMappingURL=JoseHeaderError.js.map

@@ -1,4 +0,3 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';
import { __extends } from '../_virtual/_tslib.js';
import { AuthError } from './AuthError.js';

@@ -13,14 +12,11 @@

*/
var ServerError = /** @class */ (function (_super) {
__extends(ServerError, _super);
function ServerError(errorCode, errorMessage, subError) {
var _this = _super.call(this, errorCode, errorMessage, subError) || this;
_this.name = "ServerError";
Object.setPrototypeOf(_this, ServerError.prototype);
return _this;
class ServerError extends AuthError {
constructor(errorCode, errorMessage, subError) {
super(errorCode, errorMessage, subError);
this.name = "ServerError";
Object.setPrototypeOf(this, ServerError.prototype);
}
return ServerError;
}(AuthError));
}
export { ServerError };
//# sourceMappingURL=ServerError.js.map

@@ -6,10 +6,7 @@ /**

export { AuthorizationCodeClient } from "./client/AuthorizationCodeClient";
export { DeviceCodeClient } from "./client/DeviceCodeClient";
export { RefreshTokenClient } from "./client/RefreshTokenClient";
export { ClientCredentialClient } from "./client/ClientCredentialClient";
export { OnBehalfOfClient } from "./client/OnBehalfOfClient";
export { SilentFlowClient } from "./client/SilentFlowClient";
export { UsernamePasswordClient } from "./client/UsernamePasswordClient";
export { AuthOptions, SystemOptions, LoggerOptions, DEFAULT_SYSTEM_OPTIONS, AzureCloudOptions, ApplicationTelemetry } from "./config/ClientConfiguration";
export { IAppTokenProvider, AppTokenProviderParameters, AppTokenProviderResult } from "./config/AppTokenProvider";
export { BaseClient } from "./client/BaseClient";
export { AuthOptions, SystemOptions, LoggerOptions, DEFAULT_SYSTEM_OPTIONS, AzureCloudOptions, ApplicationTelemetry, } from "./config/ClientConfiguration";
export { IAppTokenProvider, AppTokenProviderParameters, AppTokenProviderResult, } from "./config/AppTokenProvider";
export { ClientConfiguration } from "./config/ClientConfiguration";

@@ -22,5 +19,5 @@ export { AccountInfo, ActiveAccountFilters } from "./account/AccountInfo";

export { CcsCredential, CcsCredentialType } from "./account/CcsCredential";
export { ClientInfo, buildClientInfo, buildClientInfoFromHomeAccountId } from "./account/ClientInfo";
export { ClientInfo, buildClientInfo, buildClientInfoFromHomeAccountId, } from "./account/ClientInfo";
export { Authority } from "./authority/Authority";
export { AuthorityOptions, AzureCloudInstance } from "./authority/AuthorityOptions";
export { AuthorityOptions, AzureCloudInstance, } from "./authority/AuthorityOptions";
export { AuthorityFactory } from "./authority/AuthorityFactory";

@@ -31,3 +28,3 @@ export { AuthorityType } from "./authority/AuthorityType";

export { CacheManager, DefaultStorageClass } from "./cache/CacheManager";
export { AccountCache, AccessTokenCache, IdTokenCache, RefreshTokenCache, AppMetadataCache, ValidCacheType, ValidCredentialType, TokenKeys } from "./cache/utils/CacheTypes";
export { AccountCache, AccessTokenCache, IdTokenCache, RefreshTokenCache, AppMetadataCache, CredentialFilter, ValidCacheType, ValidCredentialType, TokenKeys, } from "./cache/utils/CacheTypes";
export { CacheRecord } from "./cache/entities/CacheRecord";

@@ -46,4 +43,4 @@ export { CredentialEntity } from "./cache/entities/CredentialEntity";

export { ISerializableTokenCache } from "./cache/interface/ISerializableTokenCache";
export { INetworkModule, NetworkRequestOptions, StubbedNetworkModule } from "./network/INetworkModule";
export { NetworkManager, NetworkResponse, UrlToHttpRequestOptions } from "./network/NetworkManager";
export { INetworkModule, NetworkRequestOptions, StubbedNetworkModule, } from "./network/INetworkModule";
export { NetworkManager, NetworkResponse, UrlToHttpRequestOptions, } from "./network/NetworkManager";
export { ThrottlingUtils } from "./network/ThrottlingUtils";

@@ -53,3 +50,3 @@ export { RequestThumbprint } from "./network/RequestThumbprint";

export { UrlString } from "./url/UrlString";
export { ICrypto, PkceCodes, DEFAULT_CRYPTO_IMPLEMENTATION, SignedHttpRequestParameters } from "./crypto/ICrypto";
export { ICrypto, PkceCodes, DEFAULT_CRYPTO_IMPLEMENTATION, SignedHttpRequestParameters, } from "./crypto/ICrypto";
export { SignedHttpRequest } from "./crypto/SignedHttpRequest";

@@ -70,2 +67,3 @@ export { IGuidGenerator } from "./crypto/IGuidGenerator";

export { NativeSignOutRequest } from "./request/NativeSignOutRequest";
export { RequestParameterBuilder } from "./request/RequestParameterBuilder";
export { AzureRegion } from "./authority/AzureRegion";

@@ -78,22 +76,23 @@ export { AzureRegionConfiguration } from "./authority/AzureRegionConfiguration";

export { ExternalTokenResponse } from "./response/ExternalTokenResponse";
export { DeviceCodeResponse } from "./response/DeviceCodeResponse";
export { DeviceCodeResponse, ServerDeviceCodeResponse, } from "./response/DeviceCodeResponse";
export { ResponseHandler } from "./response/ResponseHandler";
export { ScopeSet } from "./request/ScopeSet";
export { AuthenticationHeaderParser } from "./request/AuthenticationHeaderParser";
export { ILoggerCallback, LogLevel, Logger } from "./logger/Logger";
export { InteractionRequiredAuthError, InteractionRequiredAuthErrorMessage } from "./error/InteractionRequiredAuthError";
export { InteractionRequiredAuthError, InteractionRequiredAuthErrorMessage, } from "./error/InteractionRequiredAuthError";
export { AuthError, AuthErrorMessage } from "./error/AuthError";
export { ServerError } from "./error/ServerError";
export { ClientAuthError, ClientAuthErrorMessage } from "./error/ClientAuthError";
export { ClientConfigurationError, ClientConfigurationErrorMessage } from "./error/ClientConfigurationError";
export { Constants, OIDC_DEFAULT_SCOPES, PromptValue, PersistentCacheKeys, ResponseMode, CredentialType, CacheType, CacheAccountType, AuthenticationScheme, CodeChallengeMethodValues, SSOTypes, PasswordGrantConstants, ThrottlingConstants, ClaimsRequestKeys, HeaderNames, AADServerParamKeys, Errors, THE_FAMILY_ID, ONE_DAY_IN_MS } from "./utils/Constants";
export { ClientAuthError, ClientAuthErrorMessage, } from "./error/ClientAuthError";
export { ClientConfigurationError, ClientConfigurationErrorMessage, } from "./error/ClientConfigurationError";
export { Constants, OIDC_DEFAULT_SCOPES, PromptValue, PersistentCacheKeys, ResponseMode, CacheOutcome, CredentialType, CacheType, CacheAccountType, AuthenticationScheme, CodeChallengeMethodValues, SSOTypes, PasswordGrantConstants, ThrottlingConstants, ClaimsRequestKeys, HeaderNames, AADServerParamKeys, Errors, THE_FAMILY_ID, ONE_DAY_IN_MS, GrantType, AADAuthorityConstants, } from "./utils/Constants";
export { StringUtils } from "./utils/StringUtils";
export { StringDict } from "./utils/MsalTypes";
export { ProtocolUtils, RequestStateObject, LibraryStateObject } from "./utils/ProtocolUtils";
export { ProtocolUtils, RequestStateObject, LibraryStateObject, } from "./utils/ProtocolUtils";
export { TimeUtils } from "./utils/TimeUtils";
export { ServerTelemetryManager } from "./telemetry/server/ServerTelemetryManager";
export { ServerTelemetryRequest } from "./telemetry/server/ServerTelemetryRequest";
export { IPerformanceClient, PerformanceCallbackFunction, InProgressPerformanceEvent, QueueMeasurement } from "./telemetry/performance/IPerformanceClient";
export { Counters, IntFields, PerformanceEvent, PerformanceEvents, PerformanceEventStatus, StaticFields, SubMeasurement } from "./telemetry/performance/PerformanceEvent";
export { IPerformanceClient, PerformanceCallbackFunction, InProgressPerformanceEvent, QueueMeasurement, } from "./telemetry/performance/IPerformanceClient";
export { Counters, IntFields, PerformanceEvent, PerformanceEvents, PerformanceEventStatus, StaticFields, SubMeasurement, } from "./telemetry/performance/PerformanceEvent";
export { IPerformanceMeasurement } from "./telemetry/performance/IPerformanceMeasurement";
export { PerformanceClient, PreQueueEvent } from "./telemetry/performance/PerformanceClient";
export { PerformanceClient, PreQueueEvent, } from "./telemetry/performance/PerformanceClient";
export { StubPerformanceClient } from "./telemetry/performance/StubPerformanceClient";

@@ -100,0 +99,0 @@ export { PopTokenGenerator } from "./crypto/PopTokenGenerator";

@@ -1,10 +0,7 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';
export { AuthorizationCodeClient } from './client/AuthorizationCodeClient.js';
export { DeviceCodeClient } from './client/DeviceCodeClient.js';
export { RefreshTokenClient } from './client/RefreshTokenClient.js';
export { ClientCredentialClient } from './client/ClientCredentialClient.js';
export { OnBehalfOfClient } from './client/OnBehalfOfClient.js';
export { SilentFlowClient } from './client/SilentFlowClient.js';
export { UsernamePasswordClient } from './client/UsernamePasswordClient.js';
export { BaseClient } from './client/BaseClient.js';
export { DEFAULT_SYSTEM_OPTIONS } from './config/ClientConfiguration.js';

@@ -37,2 +34,4 @@ export { AuthToken, AuthToken as IdToken } from './account/AuthToken.js';

export { JoseHeader } from './crypto/JoseHeader.js';
export { RequestParameterBuilder } from './request/RequestParameterBuilder.js';
export { ResponseHandler } from './response/ResponseHandler.js';
export { ScopeSet } from './request/ScopeSet.js';

@@ -46,3 +45,3 @@ export { AuthenticationHeaderParser } from './request/AuthenticationHeaderParser.js';

export { ClientConfigurationError, ClientConfigurationErrorMessage } from './error/ClientConfigurationError.js';
export { AADServerParamKeys, AuthenticationScheme, CacheAccountType, CacheType, ClaimsRequestKeys, CodeChallengeMethodValues, Constants, CredentialType, Errors, HeaderNames, OIDC_DEFAULT_SCOPES, ONE_DAY_IN_MS, PasswordGrantConstants, PersistentCacheKeys, PromptValue, ResponseMode, SSOTypes, THE_FAMILY_ID, ThrottlingConstants } from './utils/Constants.js';
export { AADAuthorityConstants, AADServerParamKeys, AuthenticationScheme, CacheAccountType, CacheOutcome, CacheType, ClaimsRequestKeys, CodeChallengeMethodValues, Constants, CredentialType, Errors, GrantType, HeaderNames, OIDC_DEFAULT_SCOPES, ONE_DAY_IN_MS, PasswordGrantConstants, PersistentCacheKeys, PromptValue, ResponseMode, SSOTypes, THE_FAMILY_ID, ThrottlingConstants } from './utils/Constants.js';
export { StringUtils } from './utils/StringUtils.js';

@@ -49,0 +48,0 @@ export { ProtocolUtils } from './utils/ProtocolUtils.js';

@@ -5,3 +5,3 @@ import { LoggerOptions } from "../config/ClientConfiguration";

*/
export declare type LoggerMessageOptions = {
export type LoggerMessageOptions = {
logLevel: LogLevel;

@@ -8,0 +8,0 @@ containsPii?: boolean;

@@ -1,2 +0,2 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';

@@ -24,173 +24,183 @@ import { StringUtils } from '../utils/StringUtils.js';

*/
var Logger = /** @class */ (function () {
function Logger(loggerOptions, packageName, packageVersion) {
class Logger {
constructor(loggerOptions, packageName, packageVersion) {
// Current log level, defaults to info.
this.level = LogLevel.Info;
var defaultLoggerCallback = function () {
const defaultLoggerCallback = () => {
return;
};
var setLoggerOptions = loggerOptions || Logger.createDefaultLoggerOptions();
this.localCallback = setLoggerOptions.loggerCallback || defaultLoggerCallback;
const setLoggerOptions = loggerOptions || Logger.createDefaultLoggerOptions();
this.localCallback =
setLoggerOptions.loggerCallback || defaultLoggerCallback;
this.piiLoggingEnabled = setLoggerOptions.piiLoggingEnabled || false;
this.level = typeof (setLoggerOptions.logLevel) === "number" ? setLoggerOptions.logLevel : LogLevel.Info;
this.correlationId = setLoggerOptions.correlationId || Constants.EMPTY_STRING;
this.level =
typeof setLoggerOptions.logLevel === "number"
? setLoggerOptions.logLevel
: LogLevel.Info;
this.correlationId =
setLoggerOptions.correlationId || Constants.EMPTY_STRING;
this.packageName = packageName || Constants.EMPTY_STRING;
this.packageVersion = packageVersion || Constants.EMPTY_STRING;
}
Logger.createDefaultLoggerOptions = function () {
static createDefaultLoggerOptions() {
return {
loggerCallback: function () {
loggerCallback: () => {
// allow users to not set loggerCallback
},
piiLoggingEnabled: false,
logLevel: LogLevel.Info
logLevel: LogLevel.Info,
};
};
}
/**
* Create new Logger with existing configurations.
*/
Logger.prototype.clone = function (packageName, packageVersion, correlationId) {
return new Logger({ loggerCallback: this.localCallback, piiLoggingEnabled: this.piiLoggingEnabled, logLevel: this.level, correlationId: correlationId || this.correlationId }, packageName, packageVersion);
};
clone(packageName, packageVersion, correlationId) {
return new Logger({
loggerCallback: this.localCallback,
piiLoggingEnabled: this.piiLoggingEnabled,
logLevel: this.level,
correlationId: correlationId || this.correlationId,
}, packageName, packageVersion);
}
/**
* Log message with required options.
*/
Logger.prototype.logMessage = function (logMessage, options) {
if ((options.logLevel > this.level) || (!this.piiLoggingEnabled && options.containsPii)) {
logMessage(logMessage, options) {
if (options.logLevel > this.level ||
(!this.piiLoggingEnabled && options.containsPii)) {
return;
}
var timestamp = new Date().toUTCString();
const timestamp = new Date().toUTCString();
// Add correlationId to logs if set, correlationId provided on log messages take precedence
var logHeader;
let logHeader;
if (!StringUtils.isEmpty(options.correlationId)) {
logHeader = "[" + timestamp + "] : [" + options.correlationId + "]";
logHeader = `[${timestamp}] : [${options.correlationId}]`;
}
else if (!StringUtils.isEmpty(this.correlationId)) {
logHeader = "[" + timestamp + "] : [" + this.correlationId + "]";
logHeader = `[${timestamp}] : [${this.correlationId}]`;
}
else {
logHeader = "[" + timestamp + "]";
logHeader = `[${timestamp}]`;
}
var log = logHeader + " : " + this.packageName + "@" + this.packageVersion + " : " + LogLevel[options.logLevel] + " - " + logMessage;
const log = `${logHeader} : ${this.packageName}@${this.packageVersion} : ${LogLevel[options.logLevel]} - ${logMessage}`;
// debug(`msal:${LogLevel[options.logLevel]}${options.containsPii ? "-Pii": Constants.EMPTY_STRING}${options.context ? `:${options.context}` : Constants.EMPTY_STRING}`)(logMessage);
this.executeCallback(options.logLevel, log, options.containsPii || false);
};
}
/**
* Execute callback with message.
*/
Logger.prototype.executeCallback = function (level, message, containsPii) {
executeCallback(level, message, containsPii) {
if (this.localCallback) {
this.localCallback(level, message, containsPii);
}
};
}
/**
* Logs error messages.
*/
Logger.prototype.error = function (message, correlationId) {
error(message, correlationId) {
this.logMessage(message, {
logLevel: LogLevel.Error,
containsPii: false,
correlationId: correlationId || Constants.EMPTY_STRING
correlationId: correlationId || Constants.EMPTY_STRING,
});
};
}
/**
* Logs error messages with PII.
*/
Logger.prototype.errorPii = function (message, correlationId) {
errorPii(message, correlationId) {
this.logMessage(message, {
logLevel: LogLevel.Error,
containsPii: true,
correlationId: correlationId || Constants.EMPTY_STRING
correlationId: correlationId || Constants.EMPTY_STRING,
});
};
}
/**
* Logs warning messages.
*/
Logger.prototype.warning = function (message, correlationId) {
warning(message, correlationId) {
this.logMessage(message, {
logLevel: LogLevel.Warning,
containsPii: false,
correlationId: correlationId || Constants.EMPTY_STRING
correlationId: correlationId || Constants.EMPTY_STRING,
});
};
}
/**
* Logs warning messages with PII.
*/
Logger.prototype.warningPii = function (message, correlationId) {
warningPii(message, correlationId) {
this.logMessage(message, {
logLevel: LogLevel.Warning,
containsPii: true,
correlationId: correlationId || Constants.EMPTY_STRING
correlationId: correlationId || Constants.EMPTY_STRING,
});
};
}
/**
* Logs info messages.
*/
Logger.prototype.info = function (message, correlationId) {
info(message, correlationId) {
this.logMessage(message, {
logLevel: LogLevel.Info,
containsPii: false,
correlationId: correlationId || Constants.EMPTY_STRING
correlationId: correlationId || Constants.EMPTY_STRING,
});
};
}
/**
* Logs info messages with PII.
*/
Logger.prototype.infoPii = function (message, correlationId) {
infoPii(message, correlationId) {
this.logMessage(message, {
logLevel: LogLevel.Info,
containsPii: true,
correlationId: correlationId || Constants.EMPTY_STRING
correlationId: correlationId || Constants.EMPTY_STRING,
});
};
}
/**
* Logs verbose messages.
*/
Logger.prototype.verbose = function (message, correlationId) {
verbose(message, correlationId) {
this.logMessage(message, {
logLevel: LogLevel.Verbose,
containsPii: false,
correlationId: correlationId || Constants.EMPTY_STRING
correlationId: correlationId || Constants.EMPTY_STRING,
});
};
}
/**
* Logs verbose messages with PII.
*/
Logger.prototype.verbosePii = function (message, correlationId) {
verbosePii(message, correlationId) {
this.logMessage(message, {
logLevel: LogLevel.Verbose,
containsPii: true,
correlationId: correlationId || Constants.EMPTY_STRING
correlationId: correlationId || Constants.EMPTY_STRING,
});
};
}
/**
* Logs trace messages.
*/
Logger.prototype.trace = function (message, correlationId) {
trace(message, correlationId) {
this.logMessage(message, {
logLevel: LogLevel.Trace,
containsPii: false,
correlationId: correlationId || Constants.EMPTY_STRING
correlationId: correlationId || Constants.EMPTY_STRING,
});
};
}
/**
* Logs trace messages with PII.
*/
Logger.prototype.tracePii = function (message, correlationId) {
tracePii(message, correlationId) {
this.logMessage(message, {
logLevel: LogLevel.Trace,
containsPii: true,
correlationId: correlationId || Constants.EMPTY_STRING
correlationId: correlationId || Constants.EMPTY_STRING,
});
};
}
/**
* Returns whether PII Logging is enabled or not.
*/
Logger.prototype.isPiiLoggingEnabled = function () {
isPiiLoggingEnabled() {
return this.piiLoggingEnabled || false;
};
return Logger;
}());
}
}
export { LogLevel, Logger };
//# sourceMappingURL=Logger.js.map

@@ -5,3 +5,3 @@ import { NetworkResponse } from "./NetworkManager";

*/
export declare type NetworkRequestOptions = {
export type NetworkRequestOptions = {
headers?: Record<string, string>;

@@ -8,0 +8,0 @@ body?: string;

@@ -1,2 +0,2 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';

@@ -9,11 +9,11 @@ import { AuthError } from '../error/AuthError.js';

*/
var StubbedNetworkModule = {
sendGetRequestAsync: function () {
var notImplErr = "Network interface - sendGetRequestAsync() has not been implemented for the Network interface.";
const StubbedNetworkModule = {
sendGetRequestAsync: () => {
const notImplErr = "Network interface - sendGetRequestAsync() has not been implemented for the Network interface.";
return Promise.reject(AuthError.createUnexpectedError(notImplErr));
},
sendPostRequestAsync: function () {
var notImplErr = "Network interface - sendPostRequestAsync() has not been implemented for the Network interface.";
sendPostRequestAsync: () => {
const notImplErr = "Network interface - sendPostRequestAsync() has not been implemented for the Network interface.";
return Promise.reject(AuthError.createUnexpectedError(notImplErr));
}
},
};

@@ -20,0 +20,0 @@

import { INetworkModule, NetworkRequestOptions } from "./INetworkModule";
import { RequestThumbprint } from "./RequestThumbprint";
import { CacheManager } from "../cache/CacheManager";
export declare type NetworkResponse<T> = {
import { ServerAuthorizationTokenResponse } from "../response/ServerAuthorizationTokenResponse";
export type NetworkResponse<T> = {
headers: Record<string, string>;

@@ -9,3 +10,3 @@ body: T;

};
export declare type UrlToHttpRequestOptions = {
export type UrlToHttpRequestOptions = {
protocol: string;

@@ -31,4 +32,4 @@ hostname: string;

*/
sendPostRequest<T>(thumbprint: RequestThumbprint, tokenEndpoint: string, options: NetworkRequestOptions): Promise<NetworkResponse<T>>;
sendPostRequest<T extends ServerAuthorizationTokenResponse>(thumbprint: RequestThumbprint, tokenEndpoint: string, options: NetworkRequestOptions): Promise<NetworkResponse<T>>;
}
//# sourceMappingURL=NetworkManager.d.ts.map

@@ -1,4 +0,3 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';
import { __awaiter, __generator } from '../_virtual/_tslib.js';
import { ThrottlingUtils } from './ThrottlingUtils.js';

@@ -12,4 +11,4 @@ import { AuthError } from '../error/AuthError.js';

*/
var NetworkManager = /** @class */ (function () {
function NetworkManager(networkClient, cacheManager) {
class NetworkManager {
constructor(networkClient, cacheManager) {
this.networkClient = networkClient;

@@ -24,35 +23,22 @@ this.cacheManager = cacheManager;

*/
NetworkManager.prototype.sendPostRequest = function (thumbprint, tokenEndpoint, options) {
return __awaiter(this, void 0, void 0, function () {
var response, e_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
ThrottlingUtils.preProcess(this.cacheManager, thumbprint);
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.networkClient.sendPostRequestAsync(tokenEndpoint, options)];
case 2:
response = _a.sent();
return [3 /*break*/, 4];
case 3:
e_1 = _a.sent();
if (e_1 instanceof AuthError) {
throw e_1;
}
else {
throw ClientAuthError.createNetworkError(tokenEndpoint, e_1);
}
case 4:
ThrottlingUtils.postProcess(this.cacheManager, thumbprint, response);
return [2 /*return*/, response];
}
});
});
};
return NetworkManager;
}());
async sendPostRequest(thumbprint, tokenEndpoint, options) {
ThrottlingUtils.preProcess(this.cacheManager, thumbprint);
let response;
try {
response = await this.networkClient.sendPostRequestAsync(tokenEndpoint, options);
}
catch (e) {
if (e instanceof AuthError) {
throw e;
}
else {
throw ClientAuthError.createNetworkError(tokenEndpoint, e);
}
}
ThrottlingUtils.postProcess(this.cacheManager, thumbprint, response);
return response;
}
}
export { NetworkManager };
//# sourceMappingURL=NetworkManager.js.map

@@ -5,3 +5,3 @@ import { AuthenticationScheme } from "../utils/Constants";

*/
export declare type RequestThumbprint = {
export type RequestThumbprint = {
clientId: string;

@@ -8,0 +8,0 @@ authority: string;

@@ -1,2 +0,2 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';

@@ -10,5 +10,3 @@ import { ThrottlingConstants, Constants, HeaderNames } from '../utils/Constants.js';

*/
var ThrottlingUtils = /** @class */ (function () {
function ThrottlingUtils() {
}
class ThrottlingUtils {
/**

@@ -18,5 +16,5 @@ * Prepares a RequestThumbprint to be stored as a key.

*/
ThrottlingUtils.generateThrottlingStorageKey = function (thumbprint) {
return ThrottlingConstants.THROTTLING_PREFIX + "." + JSON.stringify(thumbprint);
};
static generateThrottlingStorageKey(thumbprint) {
return `${ThrottlingConstants.THROTTLING_PREFIX}.${JSON.stringify(thumbprint)}`;
}
/**

@@ -27,6 +25,5 @@ * Performs necessary throttling checks before a network request.

*/
ThrottlingUtils.preProcess = function (cacheManager, thumbprint) {
var _a;
var key = ThrottlingUtils.generateThrottlingStorageKey(thumbprint);
var value = cacheManager.getThrottlingCache(key);
static preProcess(cacheManager, thumbprint) {
const key = ThrottlingUtils.generateThrottlingStorageKey(thumbprint);
const value = cacheManager.getThrottlingCache(key);
if (value) {

@@ -37,5 +34,5 @@ if (value.throttleTime < Date.now()) {

}
throw new ServerError(((_a = value.errorCodes) === null || _a === void 0 ? void 0 : _a.join(" ")) || Constants.EMPTY_STRING, value.errorMessage, value.subError);
throw new ServerError(value.errorCodes?.join(" ") || Constants.EMPTY_STRING, value.errorMessage, value.subError);
}
};
}
/**

@@ -47,5 +44,6 @@ * Performs necessary throttling checks after a network request.

*/
ThrottlingUtils.postProcess = function (cacheManager, thumbprint, response) {
if (ThrottlingUtils.checkResponseStatus(response) || ThrottlingUtils.checkResponseForRetryAfter(response)) {
var thumbprintValue = {
static postProcess(cacheManager, thumbprint, response) {
if (ThrottlingUtils.checkResponseStatus(response) ||
ThrottlingUtils.checkResponseForRetryAfter(response)) {
const thumbprintValue = {
throttleTime: ThrottlingUtils.calculateThrottleTime(parseInt(response.headers[HeaderNames.RETRY_AFTER])),

@@ -55,7 +53,7 @@ error: response.body.error,

errorMessage: response.body.error_description,
subError: response.body.suberror
subError: response.body.suberror,
};
cacheManager.setThrottlingCache(ThrottlingUtils.generateThrottlingStorageKey(thumbprint), thumbprintValue);
}
};
}
/**

@@ -65,5 +63,6 @@ * Checks a NetworkResponse object's status codes against 429 or 5xx

*/
ThrottlingUtils.checkResponseStatus = function (response) {
return response.status === 429 || response.status >= 500 && response.status < 600;
};
static checkResponseStatus(response) {
return (response.status === 429 ||
(response.status >= 500 && response.status < 600));
}
/**

@@ -73,8 +72,9 @@ * Checks a NetworkResponse object's RetryAfter header

*/
ThrottlingUtils.checkResponseForRetryAfter = function (response) {
static checkResponseForRetryAfter(response) {
if (response.headers) {
return response.headers.hasOwnProperty(HeaderNames.RETRY_AFTER) && (response.status < 200 || response.status >= 300);
return (response.headers.hasOwnProperty(HeaderNames.RETRY_AFTER) &&
(response.status < 200 || response.status >= 300));
}
return false;
};
}
/**

@@ -84,9 +84,11 @@ * Calculates the Unix-time value for a throttle to expire given throttleTime in seconds.

*/
ThrottlingUtils.calculateThrottleTime = function (throttleTime) {
var time = throttleTime <= 0 ? 0 : throttleTime;
var currentSeconds = Date.now() / 1000;
return Math.floor(Math.min(currentSeconds + (time || ThrottlingConstants.DEFAULT_THROTTLE_TIME_SECONDS), currentSeconds + ThrottlingConstants.DEFAULT_MAX_THROTTLE_TIME_SECONDS) * 1000);
};
ThrottlingUtils.removeThrottle = function (cacheManager, clientId, request, homeAccountIdentifier) {
var thumbprint = {
static calculateThrottleTime(throttleTime) {
const time = throttleTime <= 0 ? 0 : throttleTime;
const currentSeconds = Date.now() / 1000;
return Math.floor(Math.min(currentSeconds +
(time || ThrottlingConstants.DEFAULT_THROTTLE_TIME_SECONDS), currentSeconds +
ThrottlingConstants.DEFAULT_MAX_THROTTLE_TIME_SECONDS) * 1000);
}
static removeThrottle(cacheManager, clientId, request, homeAccountIdentifier) {
const thumbprint = {
clientId: clientId,

@@ -101,11 +103,10 @@ authority: request.authority,

shrClaims: request.shrClaims,
sshKid: request.sshKid
sshKid: request.sshKid,
};
var key = this.generateThrottlingStorageKey(thumbprint);
const key = this.generateThrottlingStorageKey(thumbprint);
cacheManager.removeItem(key);
};
return ThrottlingUtils;
}());
}
}
export { ThrottlingUtils };
//# sourceMappingURL=ThrottlingUtils.js.map
export declare const name = "@azure/msal-common";
export declare const version = "13.0.0";
export declare const version = "14.0.0-alpha.1";
//# sourceMappingURL=packageMetadata.d.ts.map

@@ -1,8 +0,8 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';
/* eslint-disable header/header */
var name = "@azure/msal-common";
var version = "13.0.0";
const name = "@azure/msal-common";
const version = "14.0.0-alpha.1";
export { name, version };
//# sourceMappingURL=packageMetadata.js.map

@@ -1,2 +0,2 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';

@@ -14,4 +14,4 @@ import { ClientConfigurationError } from '../error/ClientConfigurationError.js';

*/
var AuthenticationHeaderParser = /** @class */ (function () {
function AuthenticationHeaderParser(headers) {
class AuthenticationHeaderParser {
constructor(headers) {
this.headers = headers;

@@ -23,7 +23,7 @@ }

*/
AuthenticationHeaderParser.prototype.getShrNonce = function () {
getShrNonce() {
// Attempt to parse nonce from Authentiacation-Info
var authenticationInfo = this.headers[HeaderNames.AuthenticationInfo];
const authenticationInfo = this.headers[HeaderNames.AuthenticationInfo];
if (authenticationInfo) {
var authenticationInfoChallenges = this.parseChallenges(authenticationInfo);
const authenticationInfoChallenges = this.parseChallenges(authenticationInfo);
if (authenticationInfoChallenges.nextnonce) {

@@ -35,5 +35,5 @@ return authenticationInfoChallenges.nextnonce;

// Attempt to parse nonce from WWW-Authenticate
var wwwAuthenticate = this.headers[HeaderNames.WWWAuthenticate];
const wwwAuthenticate = this.headers[HeaderNames.WWWAuthenticate];
if (wwwAuthenticate) {
var wwwAuthenticateChallenges = this.parseChallenges(wwwAuthenticate);
const wwwAuthenticateChallenges = this.parseChallenges(wwwAuthenticate);
if (wwwAuthenticateChallenges.nonce) {

@@ -46,3 +46,3 @@ return wwwAuthenticateChallenges.nonce;

throw ClientConfigurationError.createMissingNonceAuthenticationHeadersError();
};
}
/**

@@ -53,8 +53,8 @@ * Parses an HTTP header's challenge set into a key/value map.

*/
AuthenticationHeaderParser.prototype.parseChallenges = function (header) {
var schemeSeparator = header.indexOf(" ");
var challenges = header.substr(schemeSeparator + 1).split(",");
var challengeMap = {};
challenges.forEach(function (challenge) {
var _a = challenge.split("="), key = _a[0], value = _a[1];
parseChallenges(header) {
const schemeSeparator = header.indexOf(" ");
const challenges = header.substr(schemeSeparator + 1).split(",");
const challengeMap = {};
challenges.forEach((challenge) => {
const [key, value] = challenge.split("=");
// Remove escaped quotation marks (', ") from challenge string to keep only the challenge value

@@ -64,7 +64,6 @@ challengeMap[key] = unescape(value.replace(/['"]+/g, Constants.EMPTY_STRING));

return challengeMap;
};
return AuthenticationHeaderParser;
}());
}
}
export { AuthenticationHeaderParser };
//# sourceMappingURL=AuthenticationHeaderParser.js.map

@@ -21,3 +21,3 @@ import { AuthenticationScheme } from "../utils/Constants";

*/
export declare type BaseAuthRequest = {
export type BaseAuthRequest = {
authority: string;

@@ -24,0 +24,0 @@ correlationId: string;

@@ -19,3 +19,3 @@ import { BaseAuthRequest } from "./BaseAuthRequest";

*/
export declare type CommonAuthorizationCodeRequest = BaseAuthRequest & {
export type CommonAuthorizationCodeRequest = BaseAuthRequest & {
code: string;

@@ -22,0 +22,0 @@ redirectUri: string;

@@ -35,3 +35,3 @@ import { ResponseMode } from "../utils/Constants";

*/
export declare type CommonAuthorizationUrlRequest = BaseAuthRequest & {
export type CommonAuthorizationUrlRequest = BaseAuthRequest & {
redirectUri: string;

@@ -38,0 +38,0 @@ responseMode: ResponseMode;

@@ -13,3 +13,3 @@ import { BaseAuthRequest } from "./BaseAuthRequest";

*/
export declare type CommonClientCredentialRequest = BaseAuthRequest & {
export type CommonClientCredentialRequest = BaseAuthRequest & {
skipCache?: boolean;

@@ -16,0 +16,0 @@ azureRegion?: AzureRegion;

@@ -16,3 +16,3 @@ import { DeviceCodeResponse } from "../response/DeviceCodeResponse";

*/
export declare type CommonDeviceCodeRequest = Omit<BaseAuthRequest, "tokenQueryParameters"> & {
export type CommonDeviceCodeRequest = Omit<BaseAuthRequest, "tokenQueryParameters"> & {
deviceCodeCallback: (response: DeviceCodeResponse) => void;

@@ -19,0 +19,0 @@ cancel?: boolean;

@@ -13,3 +13,3 @@ import { AccountInfo } from "../account/AccountInfo";

*/
export declare type CommonEndSessionRequest = {
export type CommonEndSessionRequest = {
correlationId: string;

@@ -16,0 +16,0 @@ account?: AccountInfo | null;

@@ -10,3 +10,3 @@ import { BaseAuthRequest } from "./BaseAuthRequest";

*/
export declare type CommonOnBehalfOfRequest = BaseAuthRequest & {
export type CommonOnBehalfOfRequest = BaseAuthRequest & {
oboAssertion: string;

@@ -13,0 +13,0 @@ skipCache?: boolean;

@@ -15,3 +15,3 @@ import { BaseAuthRequest } from "./BaseAuthRequest";

*/
export declare type CommonRefreshTokenRequest = BaseAuthRequest & {
export type CommonRefreshTokenRequest = BaseAuthRequest & {
refreshToken: string;

@@ -18,0 +18,0 @@ ccsCredential?: CcsCredential;

@@ -15,3 +15,3 @@ import { AccountInfo } from "../account/AccountInfo";

*/
export declare type CommonSilentFlowRequest = BaseAuthRequest & {
export type CommonSilentFlowRequest = BaseAuthRequest & {
account: AccountInfo;

@@ -18,0 +18,0 @@ forceRefresh: boolean;

@@ -14,3 +14,3 @@ import { BaseAuthRequest } from "./BaseAuthRequest";

*/
export declare type CommonUsernamePasswordRequest = BaseAuthRequest & {
export type CommonUsernamePasswordRequest = BaseAuthRequest & {
username: string;

@@ -17,0 +17,0 @@ password: string;

import { StringDict } from "../utils/MsalTypes";
export declare type NativeRequest = {
export type NativeRequest = {
clientId: string;

@@ -4,0 +4,0 @@ authority: string;

@@ -1,2 +0,2 @@

export declare type NativeSignOutRequest = {
export type NativeSignOutRequest = {
clientId: string;

@@ -3,0 +3,0 @@ accountId: string;

@@ -1,5 +0,4 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';
import { __spreadArrays } from '../_virtual/_tslib.js';
import { AADServerParamKeys, Constants, ResponseMode, OIDC_DEFAULT_SCOPES, SSOTypes, HeaderNames, CLIENT_INFO, ClaimsRequestKeys, PasswordGrantConstants, AuthenticationScheme, ThrottlingConstants } from '../utils/Constants.js';
import { AADServerParamKeys, Constants, ResponseMode, SSOTypes, HeaderNames, CLIENT_INFO, ClaimsRequestKeys, PasswordGrantConstants, AuthenticationScheme, ThrottlingConstants, OIDC_DEFAULT_SCOPES } from '../utils/Constants.js';
import { ScopeSet } from './ScopeSet.js';

@@ -14,4 +13,4 @@ import { ClientConfigurationError } from '../error/ClientConfigurationError.js';

*/
var RequestParameterBuilder = /** @class */ (function () {
function RequestParameterBuilder() {
class RequestParameterBuilder {
constructor() {
this.parameters = new Map();

@@ -22,11 +21,11 @@ }

*/
RequestParameterBuilder.prototype.addResponseTypeCode = function () {
addResponseTypeCode() {
this.parameters.set(AADServerParamKeys.RESPONSE_TYPE, encodeURIComponent(Constants.CODE_RESPONSE_TYPE));
};
}
/**
* add response_type = token id_token
*/
RequestParameterBuilder.prototype.addResponseTypeForTokenAndIdToken = function () {
this.parameters.set(AADServerParamKeys.RESPONSE_TYPE, encodeURIComponent(Constants.TOKEN_RESPONSE_TYPE + " " + Constants.ID_TOKEN_RESPONSE_TYPE));
};
addResponseTypeForTokenAndIdToken() {
this.parameters.set(AADServerParamKeys.RESPONSE_TYPE, encodeURIComponent(`${Constants.TOKEN_RESPONSE_TYPE} ${Constants.ID_TOKEN_RESPONSE_TYPE}`));
}
/**

@@ -36,11 +35,11 @@ * add response_mode. defaults to query.

*/
RequestParameterBuilder.prototype.addResponseMode = function (responseMode) {
this.parameters.set(AADServerParamKeys.RESPONSE_MODE, encodeURIComponent((responseMode) ? responseMode : ResponseMode.QUERY));
};
addResponseMode(responseMode) {
this.parameters.set(AADServerParamKeys.RESPONSE_MODE, encodeURIComponent(responseMode ? responseMode : ResponseMode.QUERY));
}
/**
* Add flag to indicate STS should attempt to use WAM if available
*/
RequestParameterBuilder.prototype.addNativeBroker = function () {
addNativeBroker() {
this.parameters.set(AADServerParamKeys.NATIVE_BROKER, encodeURIComponent("1"));
};
}
/**

@@ -51,8 +50,9 @@ * add scopes. set addOidcScopes to false to prevent default scopes in non-user scenarios

*/
RequestParameterBuilder.prototype.addScopes = function (scopes, addOidcScopes) {
if (addOidcScopes === void 0) { addOidcScopes = true; }
var requestScopes = addOidcScopes ? __spreadArrays(scopes || [], OIDC_DEFAULT_SCOPES) : scopes || [];
var scopeSet = new ScopeSet(requestScopes);
addScopes(scopes, addOidcScopes = true) {
const requestScopes = addOidcScopes
? [...(scopes || []), ...OIDC_DEFAULT_SCOPES]
: scopes || [];
const scopeSet = new ScopeSet(requestScopes);
this.parameters.set(AADServerParamKeys.SCOPE, encodeURIComponent(scopeSet.printScopes()));
};
}
/**

@@ -62,5 +62,5 @@ * add clientId

*/
RequestParameterBuilder.prototype.addClientId = function (clientId) {
addClientId(clientId) {
this.parameters.set(AADServerParamKeys.CLIENT_ID, encodeURIComponent(clientId));
};
}
/**

@@ -70,6 +70,6 @@ * add redirect_uri

*/
RequestParameterBuilder.prototype.addRedirectUri = function (redirectUri) {
addRedirectUri(redirectUri) {
RequestValidator.validateRedirectUri(redirectUri);
this.parameters.set(AADServerParamKeys.REDIRECT_URI, encodeURIComponent(redirectUri));
};
}
/**

@@ -79,6 +79,6 @@ * add post logout redirectUri

*/
RequestParameterBuilder.prototype.addPostLogoutRedirectUri = function (redirectUri) {
addPostLogoutRedirectUri(redirectUri) {
RequestValidator.validateRedirectUri(redirectUri);
this.parameters.set(AADServerParamKeys.POST_LOGOUT_URI, encodeURIComponent(redirectUri));
};
}
/**

@@ -88,5 +88,5 @@ * add id_token_hint to logout request

*/
RequestParameterBuilder.prototype.addIdTokenHint = function (idTokenHint) {
addIdTokenHint(idTokenHint) {
this.parameters.set(AADServerParamKeys.ID_TOKEN_HINT, encodeURIComponent(idTokenHint));
};
}
/**

@@ -96,5 +96,5 @@ * add domain_hint

*/
RequestParameterBuilder.prototype.addDomainHint = function (domainHint) {
addDomainHint(domainHint) {
this.parameters.set(SSOTypes.DOMAIN_HINT, encodeURIComponent(domainHint));
};
}
/**

@@ -104,5 +104,5 @@ * add login_hint

*/
RequestParameterBuilder.prototype.addLoginHint = function (loginHint) {
addLoginHint(loginHint) {
this.parameters.set(SSOTypes.LOGIN_HINT, encodeURIComponent(loginHint));
};
}
/**

@@ -112,5 +112,5 @@ * Adds the CCS (Cache Credential Service) query parameter for login_hint

*/
RequestParameterBuilder.prototype.addCcsUpn = function (loginHint) {
this.parameters.set(HeaderNames.CCS_HEADER, encodeURIComponent("UPN:" + loginHint));
};
addCcsUpn(loginHint) {
this.parameters.set(HeaderNames.CCS_HEADER, encodeURIComponent(`UPN:${loginHint}`));
}
/**

@@ -120,5 +120,5 @@ * Adds the CCS (Cache Credential Service) query parameter for account object

*/
RequestParameterBuilder.prototype.addCcsOid = function (clientInfo) {
this.parameters.set(HeaderNames.CCS_HEADER, encodeURIComponent("Oid:" + clientInfo.uid + "@" + clientInfo.utid));
};
addCcsOid(clientInfo) {
this.parameters.set(HeaderNames.CCS_HEADER, encodeURIComponent(`Oid:${clientInfo.uid}@${clientInfo.utid}`));
}
/**

@@ -128,5 +128,5 @@ * add sid

*/
RequestParameterBuilder.prototype.addSid = function (sid) {
addSid(sid) {
this.parameters.set(SSOTypes.SID, encodeURIComponent(sid));
};
}
/**

@@ -136,7 +136,7 @@ * add claims

*/
RequestParameterBuilder.prototype.addClaims = function (claims, clientCapabilities) {
var mergedClaims = this.addClientCapabilitiesToClaims(claims, clientCapabilities);
addClaims(claims, clientCapabilities) {
const mergedClaims = this.addClientCapabilitiesToClaims(claims, clientCapabilities);
RequestValidator.validateClaims(mergedClaims);
this.parameters.set(AADServerParamKeys.CLAIMS, encodeURIComponent(mergedClaims));
};
}
/**

@@ -146,5 +146,5 @@ * add correlationId

*/
RequestParameterBuilder.prototype.addCorrelationId = function (correlationId) {
addCorrelationId(correlationId) {
this.parameters.set(AADServerParamKeys.CLIENT_REQUEST_ID, encodeURIComponent(correlationId));
};
}
/**

@@ -154,3 +154,3 @@ * add library info query params

*/
RequestParameterBuilder.prototype.addLibraryInfo = function (libraryInfo) {
addLibraryInfo(libraryInfo) {
// Telemetry Info

@@ -165,3 +165,3 @@ this.parameters.set(AADServerParamKeys.X_CLIENT_SKU, libraryInfo.sku);

}
};
}
/**

@@ -171,10 +171,10 @@ * Add client telemetry parameters

*/
RequestParameterBuilder.prototype.addApplicationTelemetry = function (appTelemetry) {
if (appTelemetry === null || appTelemetry === void 0 ? void 0 : appTelemetry.appName) {
addApplicationTelemetry(appTelemetry) {
if (appTelemetry?.appName) {
this.parameters.set(AADServerParamKeys.X_APP_NAME, appTelemetry.appName);
}
if (appTelemetry === null || appTelemetry === void 0 ? void 0 : appTelemetry.appVersion) {
if (appTelemetry?.appVersion) {
this.parameters.set(AADServerParamKeys.X_APP_VER, appTelemetry.appVersion);
}
};
}
/**

@@ -184,6 +184,6 @@ * add prompt

*/
RequestParameterBuilder.prototype.addPrompt = function (prompt) {
addPrompt(prompt) {
RequestValidator.validatePrompt(prompt);
this.parameters.set("" + AADServerParamKeys.PROMPT, encodeURIComponent(prompt));
};
this.parameters.set(`${AADServerParamKeys.PROMPT}`, encodeURIComponent(prompt));
}
/**

@@ -193,7 +193,7 @@ * add state

*/
RequestParameterBuilder.prototype.addState = function (state) {
addState(state) {
if (!StringUtils.isEmpty(state)) {
this.parameters.set(AADServerParamKeys.STATE, encodeURIComponent(state));
}
};
}
/**

@@ -203,5 +203,5 @@ * add nonce

*/
RequestParameterBuilder.prototype.addNonce = function (nonce) {
addNonce(nonce) {
this.parameters.set(AADServerParamKeys.NONCE, encodeURIComponent(nonce));
};
}
/**

@@ -213,3 +213,3 @@ * add code_challenge and code_challenge_method

*/
RequestParameterBuilder.prototype.addCodeChallengeParams = function (codeChallenge, codeChallengeMethod) {
addCodeChallengeParams(codeChallenge, codeChallengeMethod) {
RequestValidator.validateCodeChallengeParams(codeChallenge, codeChallengeMethod);

@@ -223,3 +223,3 @@ if (codeChallenge && codeChallengeMethod) {

}
};
}
/**

@@ -229,5 +229,5 @@ * add the `authorization_code` passed by the user to exchange for a token

*/
RequestParameterBuilder.prototype.addAuthorizationCode = function (code) {
addAuthorizationCode(code) {
this.parameters.set(AADServerParamKeys.CODE, encodeURIComponent(code));
};
}
/**

@@ -237,5 +237,5 @@ * add the `authorization_code` passed by the user to exchange for a token

*/
RequestParameterBuilder.prototype.addDeviceCode = function (code) {
addDeviceCode(code) {
this.parameters.set(AADServerParamKeys.DEVICE_CODE, encodeURIComponent(code));
};
}
/**

@@ -245,5 +245,5 @@ * add the `refreshToken` passed by the user

*/
RequestParameterBuilder.prototype.addRefreshToken = function (refreshToken) {
addRefreshToken(refreshToken) {
this.parameters.set(AADServerParamKeys.REFRESH_TOKEN, encodeURIComponent(refreshToken));
};
}
/**

@@ -253,5 +253,5 @@ * add the `code_verifier` passed by the user to exchange for a token

*/
RequestParameterBuilder.prototype.addCodeVerifier = function (codeVerifier) {
addCodeVerifier(codeVerifier) {
this.parameters.set(AADServerParamKeys.CODE_VERIFIER, encodeURIComponent(codeVerifier));
};
}
/**

@@ -261,5 +261,5 @@ * add client_secret

*/
RequestParameterBuilder.prototype.addClientSecret = function (clientSecret) {
addClientSecret(clientSecret) {
this.parameters.set(AADServerParamKeys.CLIENT_SECRET, encodeURIComponent(clientSecret));
};
}
/**

@@ -269,7 +269,7 @@ * add clientAssertion for confidential client flows

*/
RequestParameterBuilder.prototype.addClientAssertion = function (clientAssertion) {
addClientAssertion(clientAssertion) {
if (!StringUtils.isEmpty(clientAssertion)) {
this.parameters.set(AADServerParamKeys.CLIENT_ASSERTION, encodeURIComponent(clientAssertion));
}
};
}
/**

@@ -279,7 +279,7 @@ * add clientAssertionType for confidential client flows

*/
RequestParameterBuilder.prototype.addClientAssertionType = function (clientAssertionType) {
addClientAssertionType(clientAssertionType) {
if (!StringUtils.isEmpty(clientAssertionType)) {
this.parameters.set(AADServerParamKeys.CLIENT_ASSERTION_TYPE, encodeURIComponent(clientAssertionType));
}
};
}
/**

@@ -289,5 +289,5 @@ * add OBO assertion for confidential client flows

*/
RequestParameterBuilder.prototype.addOboAssertion = function (oboAssertion) {
addOboAssertion(oboAssertion) {
this.parameters.set(AADServerParamKeys.OBO_ASSERTION, encodeURIComponent(oboAssertion));
};
}
/**

@@ -297,5 +297,5 @@ * add grant type

*/
RequestParameterBuilder.prototype.addRequestTokenUse = function (tokenUse) {
addRequestTokenUse(tokenUse) {
this.parameters.set(AADServerParamKeys.REQUESTED_TOKEN_USE, encodeURIComponent(tokenUse));
};
}
/**

@@ -305,5 +305,5 @@ * add grant type

*/
RequestParameterBuilder.prototype.addGrantType = function (grantType) {
addGrantType(grantType) {
this.parameters.set(AADServerParamKeys.GRANT_TYPE, encodeURIComponent(grantType));
};
}
/**

@@ -313,5 +313,5 @@ * add client info

*/
RequestParameterBuilder.prototype.addClientInfo = function () {
addClientInfo() {
this.parameters.set(CLIENT_INFO, "1");
};
}
/**

@@ -321,11 +321,10 @@ * add extraQueryParams

*/
RequestParameterBuilder.prototype.addExtraQueryParameters = function (eQParams) {
var _this = this;
var sanitizedEQParams = RequestValidator.sanitizeEQParams(eQParams, this.parameters);
Object.keys(sanitizedEQParams).forEach(function (key) {
_this.parameters.set(key, eQParams[key]);
addExtraQueryParameters(eQParams) {
const sanitizedEQParams = RequestValidator.sanitizeEQParams(eQParams, this.parameters);
Object.keys(sanitizedEQParams).forEach((key) => {
this.parameters.set(key, eQParams[key]);
});
};
RequestParameterBuilder.prototype.addClientCapabilitiesToClaims = function (claims, clientCapabilities) {
var mergedClaims;
}
addClientCapabilitiesToClaims(claims, clientCapabilities) {
let mergedClaims;
// Parse provided claims into JSON object or initialize empty object

@@ -350,7 +349,7 @@ if (!claims) {

mergedClaims[ClaimsRequestKeys.ACCESS_TOKEN][ClaimsRequestKeys.XMS_CC] = {
values: clientCapabilities
values: clientCapabilities,
};
}
return JSON.stringify(mergedClaims);
};
}
/**

@@ -360,5 +359,5 @@ * adds `username` for Password Grant flow

*/
RequestParameterBuilder.prototype.addUsername = function (username) {
addUsername(username) {
this.parameters.set(PasswordGrantConstants.username, encodeURIComponent(username));
};
}
/**

@@ -368,5 +367,5 @@ * adds `password` for Password Grant flow

*/
RequestParameterBuilder.prototype.addPassword = function (password) {
addPassword(password) {
this.parameters.set(PasswordGrantConstants.password, encodeURIComponent(password));
};
}
/**

@@ -376,3 +375,3 @@ * add pop_jwk to query params

*/
RequestParameterBuilder.prototype.addPopToken = function (cnfString) {
addPopToken(cnfString) {
if (!StringUtils.isEmpty(cnfString)) {

@@ -382,7 +381,7 @@ this.parameters.set(AADServerParamKeys.TOKEN_TYPE, AuthenticationScheme.POP);

}
};
}
/**
* add SSH JWK and key ID to query params
*/
RequestParameterBuilder.prototype.addSshJwk = function (sshJwkString) {
addSshJwk(sshJwkString) {
if (!StringUtils.isEmpty(sshJwkString)) {

@@ -392,3 +391,3 @@ this.parameters.set(AADServerParamKeys.TOKEN_TYPE, AuthenticationScheme.SSH);

}
};
}
/**

@@ -398,32 +397,31 @@ * add server telemetry fields

*/
RequestParameterBuilder.prototype.addServerTelemetry = function (serverTelemetryManager) {
addServerTelemetry(serverTelemetryManager) {
this.parameters.set(AADServerParamKeys.X_CLIENT_CURR_TELEM, serverTelemetryManager.generateCurrentRequestHeaderValue());
this.parameters.set(AADServerParamKeys.X_CLIENT_LAST_TELEM, serverTelemetryManager.generateLastRequestHeaderValue());
};
}
/**
* Adds parameter that indicates to the server that throttling is supported
*/
RequestParameterBuilder.prototype.addThrottling = function () {
addThrottling() {
this.parameters.set(AADServerParamKeys.X_MS_LIB_CAPABILITY, ThrottlingConstants.X_MS_LIB_CAPABILITY_VALUE);
};
}
/**
* Adds logout_hint parameter for "silent" logout which prevent server account picker
*/
RequestParameterBuilder.prototype.addLogoutHint = function (logoutHint) {
addLogoutHint(logoutHint) {
this.parameters.set(AADServerParamKeys.LOGOUT_HINT, encodeURIComponent(logoutHint));
};
}
/**
* Utility to create a URL from the params map
*/
RequestParameterBuilder.prototype.createQueryString = function () {
var queryParameterArray = new Array();
this.parameters.forEach(function (value, key) {
queryParameterArray.push(key + "=" + value);
createQueryString() {
const queryParameterArray = new Array();
this.parameters.forEach((value, key) => {
queryParameterArray.push(`${key}=${value}`);
});
return queryParameterArray.join("&");
};
return RequestParameterBuilder;
}());
}
}
export { RequestParameterBuilder };
//# sourceMappingURL=RequestParameterBuilder.js.map

@@ -1,2 +0,2 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';

@@ -14,5 +14,3 @@ import { StringUtils } from '../utils/StringUtils.js';

*/
var RequestValidator = /** @class */ (function () {
function RequestValidator() {
}
class RequestValidator {
/**

@@ -22,7 +20,7 @@ * Utility to check if the `redirectUri` in the request is a non-null value

*/
RequestValidator.validateRedirectUri = function (redirectUri) {
static validateRedirectUri(redirectUri) {
if (StringUtils.isEmpty(redirectUri)) {
throw ClientConfigurationError.createRedirectUriEmptyError();
}
};
}
/**

@@ -32,5 +30,5 @@ * Utility to validate prompt sent by the user in the request

*/
RequestValidator.validatePrompt = function (prompt) {
var promptValues = [];
for (var value in PromptValue) {
static validatePrompt(prompt) {
const promptValues = [];
for (const value in PromptValue) {
promptValues.push(PromptValue[value]);

@@ -41,4 +39,4 @@ }

}
};
RequestValidator.validateClaims = function (claims) {
}
static validateClaims(claims) {
try {

@@ -50,3 +48,3 @@ JSON.parse(claims);

}
};
}
/**

@@ -57,4 +55,5 @@ * Utility to validate code_challenge and code_challenge_method

*/
RequestValidator.validateCodeChallengeParams = function (codeChallenge, codeChallengeMethod) {
if (StringUtils.isEmpty(codeChallenge) || StringUtils.isEmpty(codeChallengeMethod)) {
static validateCodeChallengeParams(codeChallenge, codeChallengeMethod) {
if (StringUtils.isEmpty(codeChallenge) ||
StringUtils.isEmpty(codeChallengeMethod)) {
throw ClientConfigurationError.createInvalidCodeChallengeParamsError();

@@ -65,3 +64,3 @@ }

}
};
}
/**

@@ -71,10 +70,10 @@ * Utility to validate code_challenge_method

*/
RequestValidator.validateCodeChallengeMethod = function (codeChallengeMethod) {
static validateCodeChallengeMethod(codeChallengeMethod) {
if ([
CodeChallengeMethodValues.PLAIN,
CodeChallengeMethodValues.S256
CodeChallengeMethodValues.S256,
].indexOf(codeChallengeMethod) < 0) {
throw ClientConfigurationError.createInvalidCodeChallengeMethodError();
}
};
}
/**

@@ -84,3 +83,3 @@ * Removes unnecessary, duplicate, and empty string query parameters from extraQueryParameters

*/
RequestValidator.sanitizeEQParams = function (eQParams, queryParams) {
static sanitizeEQParams(eQParams, queryParams) {
if (!eQParams) {

@@ -90,3 +89,3 @@ return {};

// Remove any query parameters already included in SSO params
queryParams.forEach(function (value, key) {
queryParams.forEach((value, key) => {
if (eQParams[key]) {

@@ -97,12 +96,8 @@ delete eQParams[key];

// remove empty string parameters
// eslint-disable-next-line @typescript-eslint/no-unused-vars
return Object.fromEntries(Object.entries(eQParams).filter(function (_a) {
var value = _a[1];
return value !== "";
}));
};
return RequestValidator;
}());
return Object.fromEntries(Object.entries(eQParams).filter(([key, value]) => value !== "") // eslint-disable-line @typescript-eslint/no-unused-vars
);
}
}
export { RequestValidator };
//# sourceMappingURL=RequestValidator.js.map

@@ -1,4 +0,3 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';
import { __spreadArrays } from '../_virtual/_tslib.js';
import { ClientConfigurationError } from '../error/ClientConfigurationError.js';

@@ -18,12 +17,15 @@ import { StringUtils } from '../utils/StringUtils.js';

*/
var ScopeSet = /** @class */ (function () {
function ScopeSet(inputScopes) {
var _this = this;
class ScopeSet {
constructor(inputScopes) {
// Filter empty string and null/undefined array items
var scopeArr = inputScopes ? StringUtils.trimArrayEntries(__spreadArrays(inputScopes)) : [];
var filteredInput = scopeArr ? StringUtils.removeEmptyStringsFromArray(scopeArr) : [];
const scopeArr = inputScopes
? StringUtils.trimArrayEntries([...inputScopes])
: [];
const filteredInput = scopeArr
? StringUtils.removeEmptyStringsFromArray(scopeArr)
: [];
// Validate and filter scopes (validate function throws if validation fails)
this.validateInputScopes(filteredInput);
this.scopes = new Set(); // Iterator in constructor not supported by IE11
filteredInput.forEach(function (scope) { return _this.scopes.add(scope); });
filteredInput.forEach((scope) => this.scopes.add(scope));
}

@@ -36,7 +38,7 @@ /**

*/
ScopeSet.fromString = function (inputScopeString) {
var scopeString = inputScopeString || Constants.EMPTY_STRING;
var inputScopes = scopeString.split(" ");
static fromString(inputScopeString) {
const scopeString = inputScopeString || Constants.EMPTY_STRING;
const inputScopes = scopeString.split(" ");
return new ScopeSet(inputScopes);
};
}
/**

@@ -47,4 +49,4 @@ * Creates the set of scopes to search for in cache lookups

*/
ScopeSet.createSearchScopes = function (inputScopeString) {
var scopeSet = new ScopeSet(inputScopeString);
static createSearchScopes(inputScopeString) {
const scopeSet = new ScopeSet(inputScopeString);
if (!scopeSet.containsOnlyOIDCScopes()) {

@@ -57,3 +59,3 @@ scopeSet.removeOIDCScopes();

return scopeSet;
};
}
/**

@@ -64,3 +66,3 @@ * Used to validate the scopes input parameter requested by the developer.

*/
ScopeSet.prototype.validateInputScopes = function (inputScopes) {
validateInputScopes(inputScopes) {
// Check if scopes are required but not given or is an empty array

@@ -70,3 +72,3 @@ if (!inputScopes || inputScopes.length < 1) {

}
};
}
/**

@@ -76,8 +78,10 @@ * Check if a given scope is present in this set of scopes.

*/
ScopeSet.prototype.containsScope = function (scope) {
var lowerCaseScopes = this.printScopesLowerCase().split(" ");
var lowerCaseScopesSet = new ScopeSet(lowerCaseScopes);
containsScope(scope) {
const lowerCaseScopes = this.printScopesLowerCase().split(" ");
const lowerCaseScopesSet = new ScopeSet(lowerCaseScopes);
// compare lowercase scopes
return !StringUtils.isEmpty(scope) ? lowerCaseScopesSet.scopes.has(scope.toLowerCase()) : false;
};
return !StringUtils.isEmpty(scope)
? lowerCaseScopesSet.scopes.has(scope.toLowerCase())
: false;
}
/**

@@ -87,17 +91,16 @@ * Check if a set of scopes is present in this set of scopes.

*/
ScopeSet.prototype.containsScopeSet = function (scopeSet) {
var _this = this;
containsScopeSet(scopeSet) {
if (!scopeSet || scopeSet.scopes.size <= 0) {
return false;
}
return (this.scopes.size >= scopeSet.scopes.size && scopeSet.asArray().every(function (scope) { return _this.containsScope(scope); }));
};
return (this.scopes.size >= scopeSet.scopes.size &&
scopeSet.asArray().every((scope) => this.containsScope(scope)));
}
/**
* Check if set of scopes contains only the defaults
*/
ScopeSet.prototype.containsOnlyOIDCScopes = function () {
var _this = this;
var defaultScopeCount = 0;
OIDC_SCOPES.forEach(function (defaultScope) {
if (_this.containsScope(defaultScope)) {
containsOnlyOIDCScopes() {
let defaultScopeCount = 0;
OIDC_SCOPES.forEach((defaultScope) => {
if (this.containsScope(defaultScope)) {
defaultScopeCount += 1;

@@ -107,3 +110,3 @@ }

return this.scopes.size === defaultScopeCount;
};
}
/**

@@ -113,7 +116,7 @@ * Appends single scope if passed

*/
ScopeSet.prototype.appendScope = function (newScope) {
appendScope(newScope) {
if (!StringUtils.isEmpty(newScope)) {
this.scopes.add(newScope.trim());
}
};
}
/**

@@ -123,6 +126,5 @@ * Appends multiple scopes if passed

*/
ScopeSet.prototype.appendScopes = function (newScopes) {
var _this = this;
appendScopes(newScopes) {
try {
newScopes.forEach(function (newScope) { return _this.appendScope(newScope); });
newScopes.forEach((newScope) => this.appendScope(newScope));
}

@@ -132,3 +134,3 @@ catch (e) {

}
};
}
/**

@@ -138,3 +140,3 @@ * Removes element from set of scopes.

*/
ScopeSet.prototype.removeScope = function (scope) {
removeScope(scope) {
if (StringUtils.isEmpty(scope)) {

@@ -144,3 +146,3 @@ throw ClientAuthError.createRemoveEmptyScopeFromSetError(scope);

this.scopes.delete(scope.trim());
};
}
/**

@@ -150,8 +152,7 @@ * Removes default scopes from set of scopes

*/
ScopeSet.prototype.removeOIDCScopes = function () {
var _this = this;
OIDC_SCOPES.forEach(function (defaultScope) {
_this.scopes.delete(defaultScope);
removeOIDCScopes() {
OIDC_SCOPES.forEach((defaultScope) => {
this.scopes.delete(defaultScope);
});
};
}
/**

@@ -161,11 +162,11 @@ * Combines an array of scopes with the current set of scopes.

*/
ScopeSet.prototype.unionScopeSets = function (otherScopes) {
unionScopeSets(otherScopes) {
if (!otherScopes) {
throw ClientAuthError.createEmptyInputScopeSetError();
}
var unionScopes = new Set(); // Iterator in constructor not supported in IE11
otherScopes.scopes.forEach(function (scope) { return unionScopes.add(scope.toLowerCase()); });
this.scopes.forEach(function (scope) { return unionScopes.add(scope.toLowerCase()); });
const unionScopes = new Set(); // Iterator in constructor not supported in IE11
otherScopes.scopes.forEach((scope) => unionScopes.add(scope.toLowerCase()));
this.scopes.forEach((scope) => unionScopes.add(scope.toLowerCase()));
return unionScopes;
};
}
/**

@@ -175,3 +176,3 @@ * Check if scopes intersect between this set and another.

*/
ScopeSet.prototype.intersectingScopeSets = function (otherScopes) {
intersectingScopeSets(otherScopes) {
if (!otherScopes) {

@@ -184,42 +185,41 @@ throw ClientAuthError.createEmptyInputScopeSetError();

}
var unionScopes = this.unionScopeSets(otherScopes);
var sizeOtherScopes = otherScopes.getScopeCount();
var sizeThisScopes = this.getScopeCount();
var sizeUnionScopes = unionScopes.size;
return sizeUnionScopes < (sizeThisScopes + sizeOtherScopes);
};
const unionScopes = this.unionScopeSets(otherScopes);
const sizeOtherScopes = otherScopes.getScopeCount();
const sizeThisScopes = this.getScopeCount();
const sizeUnionScopes = unionScopes.size;
return sizeUnionScopes < sizeThisScopes + sizeOtherScopes;
}
/**
* Returns size of set of scopes.
*/
ScopeSet.prototype.getScopeCount = function () {
getScopeCount() {
return this.scopes.size;
};
}
/**
* Returns the scopes as an array of string values
*/
ScopeSet.prototype.asArray = function () {
var array = [];
this.scopes.forEach(function (val) { return array.push(val); });
asArray() {
const array = [];
this.scopes.forEach((val) => array.push(val));
return array;
};
}
/**
* Prints scopes into a space-delimited string
*/
ScopeSet.prototype.printScopes = function () {
printScopes() {
if (this.scopes) {
var scopeArr = this.asArray();
const scopeArr = this.asArray();
return scopeArr.join(" ");
}
return Constants.EMPTY_STRING;
};
}
/**
* Prints scopes into a space-delimited lower-case string (used for caching)
*/
ScopeSet.prototype.printScopesLowerCase = function () {
printScopesLowerCase() {
return this.printScopes().toLowerCase();
};
return ScopeSet;
}());
}
}
export { ScopeSet };
//# sourceMappingURL=ScopeSet.js.map

@@ -18,3 +18,3 @@ import { AccountInfo } from "../account/AccountInfo";

*/
export declare type AuthenticationResult = {
export type AuthenticationResult = {
authority: string;

@@ -21,0 +21,0 @@ uniqueId: string;

/**
* Response returned after processing the code response query string or fragment.
*/
export declare type AuthorizationCodePayload = {
export type AuthorizationCodePayload = {
code: string;

@@ -6,0 +6,0 @@ cloud_instance_name?: string;

@@ -10,3 +10,3 @@ /**

*/
export declare type DeviceCodeResponse = {
export type DeviceCodeResponse = {
userCode: string;

@@ -19,3 +19,3 @@ deviceCode: string;

};
export declare type ServerDeviceCodeResponse = {
export type ServerDeviceCodeResponse = {
user_code: string;

@@ -22,0 +22,0 @@ device_code: string;

@@ -12,3 +12,3 @@ import { ServerAuthorizationTokenResponse } from "./ServerAuthorizationTokenResponse";

*/
export declare type ExternalTokenResponse = Pick<ServerAuthorizationTokenResponse, "token_type" | "scope" | "expires_in" | "id_token" | "refresh_token"> & {
export type ExternalTokenResponse = Pick<ServerAuthorizationTokenResponse, "token_type" | "scope" | "expires_in" | "id_token" | "refresh_token"> & {
access_token?: string;

@@ -15,0 +15,0 @@ client_info?: string;

@@ -1,2 +0,2 @@

export declare type IMDSBadResponse = {
export type IMDSBadResponse = {
error: string;

@@ -3,0 +3,0 @@ "newest-versions": Array<string>;

@@ -1,4 +0,3 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';
import { __awaiter, __generator } from '../_virtual/_tslib.js';
import { buildClientInfo } from '../account/ClientInfo.js';

@@ -31,4 +30,4 @@ import { ClientAuthError } from '../error/ClientAuthError.js';

*/
var ResponseHandler = /** @class */ (function () {
function ResponseHandler(clientId, cacheStorage, cryptoObj, logger, serializableCache, persistencePlugin, performanceClient) {
class ResponseHandler {
constructor(clientId, cacheStorage, cryptoObj, logger, serializableCache, persistencePlugin, performanceClient) {
this.clientId = clientId;

@@ -48,11 +47,16 @@ this.cacheStorage = cacheStorage;

*/
ResponseHandler.prototype.validateServerAuthorizationCodeResponse = function (serverResponseHash, cachedState, cryptoObj) {
validateServerAuthorizationCodeResponse(serverResponseHash, cachedState, cryptoObj) {
if (!serverResponseHash.state || !cachedState) {
throw !serverResponseHash.state ? ClientAuthError.createStateNotFoundError("Server State") : ClientAuthError.createStateNotFoundError("Cached State");
throw !serverResponseHash.state
? ClientAuthError.createStateNotFoundError("Server State")
: ClientAuthError.createStateNotFoundError("Cached State");
}
if (decodeURIComponent(serverResponseHash.state) !== decodeURIComponent(cachedState)) {
if (decodeURIComponent(serverResponseHash.state) !==
decodeURIComponent(cachedState)) {
throw ClientAuthError.createStateMismatchError();
}
// Check for error
if (serverResponseHash.error || serverResponseHash.error_description || serverResponseHash.suberror) {
if (serverResponseHash.error ||
serverResponseHash.error_description ||
serverResponseHash.suberror) {
if (InteractionRequiredAuthError.isInteractionRequiredError(serverResponseHash.error, serverResponseHash.error_description, serverResponseHash.suberror)) {

@@ -66,3 +70,3 @@ throw new InteractionRequiredAuthError(serverResponseHash.error || Constants.EMPTY_STRING, serverResponseHash.error_description, serverResponseHash.suberror, serverResponseHash.timestamp || Constants.EMPTY_STRING, serverResponseHash.trace_id || Constants.EMPTY_STRING, serverResponseHash.correlation_id || Constants.EMPTY_STRING, serverResponseHash.claims || Constants.EMPTY_STRING);

}
};
}
/**

@@ -72,12 +76,14 @@ * Function which validates server authorization token response.

*/
ResponseHandler.prototype.validateTokenResponse = function (serverResponse) {
validateTokenResponse(serverResponse) {
// Check for error
if (serverResponse.error || serverResponse.error_description || serverResponse.suberror) {
if (serverResponse.error ||
serverResponse.error_description ||
serverResponse.suberror) {
if (InteractionRequiredAuthError.isInteractionRequiredError(serverResponse.error, serverResponse.error_description, serverResponse.suberror)) {
throw new InteractionRequiredAuthError(serverResponse.error, serverResponse.error_description, serverResponse.suberror, serverResponse.timestamp || Constants.EMPTY_STRING, serverResponse.trace_id || Constants.EMPTY_STRING, serverResponse.correlation_id || Constants.EMPTY_STRING, serverResponse.claims || Constants.EMPTY_STRING);
}
var errString = serverResponse.error_codes + " - [" + serverResponse.timestamp + "]: " + serverResponse.error_description + " - Correlation ID: " + serverResponse.correlation_id + " - Trace ID: " + serverResponse.trace_id;
const errString = `${serverResponse.error_codes} - [${serverResponse.timestamp}]: ${serverResponse.error_description} - Correlation ID: ${serverResponse.correlation_id} - Trace ID: ${serverResponse.trace_id}`;
throw new ServerError(serverResponse.error, errString, serverResponse.suberror);
}
};
}
/**

@@ -88,77 +94,70 @@ * Returns a constructed token response based on given string. Also manages the cache updates and cleanups.

*/
ResponseHandler.prototype.handleServerTokenResponse = function (serverTokenResponse, authority, reqTimestamp, request, authCodePayload, userAssertionHash, handlingRefreshTokenResponse, forceCacheRefreshTokenResponse, serverRequestId) {
var _a;
return __awaiter(this, void 0, void 0, function () {
var idTokenObj, authTime, requestStateObj, cacheRecord, cacheContext, key, account;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
(_a = this.performanceClient) === null || _a === void 0 ? void 0 : _a.addQueueMeasurement(PerformanceEvents.HandleServerTokenResponse, serverTokenResponse.correlation_id);
if (serverTokenResponse.id_token) {
idTokenObj = new AuthToken(serverTokenResponse.id_token || Constants.EMPTY_STRING, this.cryptoObj);
// token nonce check (TODO: Add a warning if no nonce is given?)
if (authCodePayload && !StringUtils.isEmpty(authCodePayload.nonce)) {
if (idTokenObj.claims.nonce !== authCodePayload.nonce) {
throw ClientAuthError.createNonceMismatchError();
}
}
// token max_age check
if (request.maxAge || (request.maxAge === 0)) {
authTime = idTokenObj.claims.auth_time;
if (!authTime) {
throw ClientAuthError.createAuthTimeNotFoundError();
}
AuthToken.checkMaxAge(authTime, request.maxAge);
}
}
// generate homeAccountId
this.homeAccountIdentifier = AccountEntity.generateHomeAccountId(serverTokenResponse.client_info || Constants.EMPTY_STRING, authority.authorityType, this.logger, this.cryptoObj, idTokenObj);
if (!!authCodePayload && !!authCodePayload.state) {
requestStateObj = ProtocolUtils.parseRequestState(this.cryptoObj, authCodePayload.state);
}
// Add keyId from request to serverTokenResponse if defined
serverTokenResponse.key_id = serverTokenResponse.key_id || request.sshKid || undefined;
cacheRecord = this.generateCacheRecord(serverTokenResponse, authority, reqTimestamp, request, idTokenObj, userAssertionHash, authCodePayload);
_b.label = 1;
case 1:
_b.trys.push([1, , 5, 8]);
if (!(this.persistencePlugin && this.serializableCache)) return [3 /*break*/, 3];
this.logger.verbose("Persistence enabled, calling beforeCacheAccess");
cacheContext = new TokenCacheContext(this.serializableCache, true);
return [4 /*yield*/, this.persistencePlugin.beforeCacheAccess(cacheContext)];
case 2:
_b.sent();
_b.label = 3;
case 3:
/*
* When saving a refreshed tokens to the cache, it is expected that the account that was used is present in the cache.
* If not present, we should return null, as it's the case that another application called removeAccount in between
* the calls to getAllAccounts and acquireTokenSilent. We should not overwrite that removal, unless explicitly flagged by
* the developer, as in the case of refresh token flow used in ADAL Node to MSAL Node migration.
*/
if (handlingRefreshTokenResponse && !forceCacheRefreshTokenResponse && cacheRecord.account) {
key = cacheRecord.account.generateAccountKey();
account = this.cacheStorage.getAccount(key);
if (!account) {
this.logger.warning("Account used to refresh tokens not in persistence, refreshed tokens will not be stored in the cache");
return [2 /*return*/, ResponseHandler.generateAuthenticationResult(this.cryptoObj, authority, cacheRecord, false, request, idTokenObj, requestStateObj, undefined, serverRequestId)];
}
}
return [4 /*yield*/, this.cacheStorage.saveCacheRecord(cacheRecord)];
case 4:
_b.sent();
return [3 /*break*/, 8];
case 5:
if (!(this.persistencePlugin && this.serializableCache && cacheContext)) return [3 /*break*/, 7];
this.logger.verbose("Persistence enabled, calling afterCacheAccess");
return [4 /*yield*/, this.persistencePlugin.afterCacheAccess(cacheContext)];
case 6:
_b.sent();
_b.label = 7;
case 7: return [7 /*endfinally*/];
case 8: return [2 /*return*/, ResponseHandler.generateAuthenticationResult(this.cryptoObj, authority, cacheRecord, false, request, idTokenObj, requestStateObj, serverTokenResponse, serverRequestId)];
async handleServerTokenResponse(serverTokenResponse, authority, reqTimestamp, request, authCodePayload, userAssertionHash, handlingRefreshTokenResponse, forceCacheRefreshTokenResponse, serverRequestId) {
this.performanceClient?.addQueueMeasurement(PerformanceEvents.HandleServerTokenResponse, serverTokenResponse.correlation_id);
// create an idToken object (not entity)
let idTokenObj;
if (serverTokenResponse.id_token) {
idTokenObj = new AuthToken(serverTokenResponse.id_token || Constants.EMPTY_STRING, this.cryptoObj);
// token nonce check (TODO: Add a warning if no nonce is given?)
if (authCodePayload &&
!StringUtils.isEmpty(authCodePayload.nonce)) {
if (idTokenObj.claims.nonce !== authCodePayload.nonce) {
throw ClientAuthError.createNonceMismatchError();
}
});
});
};
}
// token max_age check
if (request.maxAge || request.maxAge === 0) {
const authTime = idTokenObj.claims.auth_time;
if (!authTime) {
throw ClientAuthError.createAuthTimeNotFoundError();
}
AuthToken.checkMaxAge(authTime, request.maxAge);
}
}
// generate homeAccountId
this.homeAccountIdentifier = AccountEntity.generateHomeAccountId(serverTokenResponse.client_info || Constants.EMPTY_STRING, authority.authorityType, this.logger, this.cryptoObj, idTokenObj);
// save the response tokens
let requestStateObj;
if (!!authCodePayload && !!authCodePayload.state) {
requestStateObj = ProtocolUtils.parseRequestState(this.cryptoObj, authCodePayload.state);
}
// Add keyId from request to serverTokenResponse if defined
serverTokenResponse.key_id =
serverTokenResponse.key_id || request.sshKid || undefined;
const cacheRecord = this.generateCacheRecord(serverTokenResponse, authority, reqTimestamp, request, idTokenObj, userAssertionHash, authCodePayload);
let cacheContext;
try {
if (this.persistencePlugin && this.serializableCache) {
this.logger.verbose("Persistence enabled, calling beforeCacheAccess");
cacheContext = new TokenCacheContext(this.serializableCache, true);
await this.persistencePlugin.beforeCacheAccess(cacheContext);
}
/*
* When saving a refreshed tokens to the cache, it is expected that the account that was used is present in the cache.
* If not present, we should return null, as it's the case that another application called removeAccount in between
* the calls to getAllAccounts and acquireTokenSilent. We should not overwrite that removal, unless explicitly flagged by
* the developer, as in the case of refresh token flow used in ADAL Node to MSAL Node migration.
*/
if (handlingRefreshTokenResponse &&
!forceCacheRefreshTokenResponse &&
cacheRecord.account) {
const key = cacheRecord.account.generateAccountKey();
const account = this.cacheStorage.getAccount(key);
if (!account) {
this.logger.warning("Account used to refresh tokens not in persistence, refreshed tokens will not be stored in the cache");
return ResponseHandler.generateAuthenticationResult(this.cryptoObj, authority, cacheRecord, false, request, idTokenObj, requestStateObj, undefined, serverRequestId);
}
}
await this.cacheStorage.saveCacheRecord(cacheRecord);
}
finally {
if (this.persistencePlugin &&
this.serializableCache &&
cacheContext) {
this.logger.verbose("Persistence enabled, calling afterCacheAccess");
await this.persistencePlugin.afterCacheAccess(cacheContext);
}
}
return ResponseHandler.generateAuthenticationResult(this.cryptoObj, authority, cacheRecord, false, request, idTokenObj, requestStateObj, serverTokenResponse, serverRequestId);
}
/**

@@ -170,4 +169,4 @@ * Generates CacheRecord

*/
ResponseHandler.prototype.generateCacheRecord = function (serverTokenResponse, authority, reqTimestamp, request, idTokenObj, userAssertionHash, authCodePayload) {
var env = authority.getPreferredCache();
generateCacheRecord(serverTokenResponse, authority, reqTimestamp, request, idTokenObj, userAssertionHash, authCodePayload) {
const env = authority.getPreferredCache();
if (StringUtils.isEmpty(env)) {

@@ -177,5 +176,6 @@ throw ClientAuthError.createInvalidCacheEnvironmentError();

// IdToken: non AAD scenarios can have empty realm
var cachedIdToken;
var cachedAccount;
if (!StringUtils.isEmpty(serverTokenResponse.id_token) && !!idTokenObj) {
let cachedIdToken;
let cachedAccount;
if (!StringUtils.isEmpty(serverTokenResponse.id_token) &&
!!idTokenObj) {
cachedIdToken = IdTokenEntity.createIdTokenEntity(this.homeAccountIdentifier, env, serverTokenResponse.id_token || Constants.EMPTY_STRING, this.clientId, idTokenObj.claims.tid || Constants.EMPTY_STRING);

@@ -185,6 +185,8 @@ cachedAccount = this.generateAccountEntity(serverTokenResponse, idTokenObj, authority, authCodePayload);

// AccessToken
var cachedAccessToken = null;
let cachedAccessToken = null;
if (!StringUtils.isEmpty(serverTokenResponse.access_token)) {
// If scopes not returned in server response, use request scopes
var responseScopes = serverTokenResponse.scope ? ScopeSet.fromString(serverTokenResponse.scope) : new ScopeSet(request.scopes || []);
const responseScopes = serverTokenResponse.scope
? ScopeSet.fromString(serverTokenResponse.scope)
: new ScopeSet(request.scopes || []);
/*

@@ -194,13 +196,23 @@ * Use timestamp calculated before request

*/
var expiresIn = (typeof serverTokenResponse.expires_in === "string" ? parseInt(serverTokenResponse.expires_in, 10) : serverTokenResponse.expires_in) || 0;
var extExpiresIn = (typeof serverTokenResponse.ext_expires_in === "string" ? parseInt(serverTokenResponse.ext_expires_in, 10) : serverTokenResponse.ext_expires_in) || 0;
var refreshIn = (typeof serverTokenResponse.refresh_in === "string" ? parseInt(serverTokenResponse.refresh_in, 10) : serverTokenResponse.refresh_in) || undefined;
var tokenExpirationSeconds = reqTimestamp + expiresIn;
var extendedTokenExpirationSeconds = tokenExpirationSeconds + extExpiresIn;
var refreshOnSeconds = refreshIn && refreshIn > 0 ? reqTimestamp + refreshIn : undefined;
const expiresIn = (typeof serverTokenResponse.expires_in === "string"
? parseInt(serverTokenResponse.expires_in, 10)
: serverTokenResponse.expires_in) || 0;
const extExpiresIn = (typeof serverTokenResponse.ext_expires_in === "string"
? parseInt(serverTokenResponse.ext_expires_in, 10)
: serverTokenResponse.ext_expires_in) || 0;
const refreshIn = (typeof serverTokenResponse.refresh_in === "string"
? parseInt(serverTokenResponse.refresh_in, 10)
: serverTokenResponse.refresh_in) || undefined;
const tokenExpirationSeconds = reqTimestamp + expiresIn;
const extendedTokenExpirationSeconds = tokenExpirationSeconds + extExpiresIn;
const refreshOnSeconds = refreshIn && refreshIn > 0
? reqTimestamp + refreshIn
: undefined;
// non AAD scenarios can have empty realm
cachedAccessToken = AccessTokenEntity.createAccessTokenEntity(this.homeAccountIdentifier, env, serverTokenResponse.access_token || Constants.EMPTY_STRING, this.clientId, idTokenObj ? idTokenObj.claims.tid || Constants.EMPTY_STRING : authority.tenant, responseScopes.printScopes(), tokenExpirationSeconds, extendedTokenExpirationSeconds, this.cryptoObj, refreshOnSeconds, serverTokenResponse.token_type, userAssertionHash, serverTokenResponse.key_id, request.claims, request.requestedClaimsHash);
cachedAccessToken = AccessTokenEntity.createAccessTokenEntity(this.homeAccountIdentifier, env, serverTokenResponse.access_token || Constants.EMPTY_STRING, this.clientId, idTokenObj
? idTokenObj.claims.tid || Constants.EMPTY_STRING
: authority.tenant, responseScopes.printScopes(), tokenExpirationSeconds, extendedTokenExpirationSeconds, this.cryptoObj, refreshOnSeconds, serverTokenResponse.token_type, userAssertionHash, serverTokenResponse.key_id, request.claims, request.requestedClaimsHash);
}
// refreshToken
var cachedRefreshToken = null;
let cachedRefreshToken = null;
if (!StringUtils.isEmpty(serverTokenResponse.refresh_token)) {

@@ -210,3 +222,3 @@ cachedRefreshToken = RefreshTokenEntity.createRefreshTokenEntity(this.homeAccountIdentifier, env, serverTokenResponse.refresh_token || Constants.EMPTY_STRING, this.clientId, serverTokenResponse.foci, userAssertionHash);

// appMetadata
var cachedAppMetadata = null;
let cachedAppMetadata = null;
if (!StringUtils.isEmpty(serverTokenResponse.foci)) {

@@ -216,3 +228,3 @@ cachedAppMetadata = AppMetadataEntity.createAppMetadataEntity(this.clientId, env, serverTokenResponse.foci);

return new CacheRecord(cachedAccount, cachedIdToken, cachedAccessToken, cachedRefreshToken, cachedAppMetadata);
};
}
/**

@@ -224,6 +236,10 @@ * Generate Account

*/
ResponseHandler.prototype.generateAccountEntity = function (serverTokenResponse, idToken, authority, authCodePayload) {
var authorityType = authority.authorityType;
var cloudGraphHostName = authCodePayload ? authCodePayload.cloud_graph_host_name : Constants.EMPTY_STRING;
var msGraphhost = authCodePayload ? authCodePayload.msgraph_host : Constants.EMPTY_STRING;
generateAccountEntity(serverTokenResponse, idToken, authority, authCodePayload) {
const authorityType = authority.authorityType;
const cloudGraphHostName = authCodePayload
? authCodePayload.cloud_graph_host_name
: Constants.EMPTY_STRING;
const msGraphhost = authCodePayload
? authCodePayload.msgraph_host
: Constants.EMPTY_STRING;
// ADFS does not require client_info in the response

@@ -235,9 +251,10 @@ if (authorityType === AuthorityType.Adfs) {

// This fallback applies to B2C as well as they fall under an AAD account type.
if (StringUtils.isEmpty(serverTokenResponse.client_info) && authority.protocolMode === "AAD") {
if (StringUtils.isEmpty(serverTokenResponse.client_info) &&
authority.protocolMode === "AAD") {
throw ClientAuthError.createClientInfoEmptyError();
}
return serverTokenResponse.client_info ?
AccountEntity.createAccount(serverTokenResponse.client_info, this.homeAccountIdentifier, idToken, authority, cloudGraphHostName, msGraphhost) :
AccountEntity.createGenericAccount(this.homeAccountIdentifier, idToken, authority, cloudGraphHostName, msGraphhost);
};
return serverTokenResponse.client_info
? AccountEntity.createAccount(serverTokenResponse.client_info, this.homeAccountIdentifier, idToken, authority, cloudGraphHostName, msGraphhost)
: AccountEntity.createGenericAccount(this.homeAccountIdentifier, idToken, authority, cloudGraphHostName, msGraphhost);
}
/**

@@ -253,72 +270,70 @@ * Creates an @AuthenticationResult from @CacheRecord , @IdToken , and a boolean that states whether or not the result is from cache.

*/
ResponseHandler.generateAuthenticationResult = function (cryptoObj, authority, cacheRecord, fromTokenCache, request, idTokenObj, requestState, serverTokenResponse, requestId) {
var _a, _b, _c;
return __awaiter(this, void 0, void 0, function () {
var accessToken, responseScopes, expiresOn, extExpiresOn, familyId, popTokenGenerator, _d, secret, keyId, uid, tid;
return __generator(this, function (_e) {
switch (_e.label) {
case 0:
accessToken = Constants.EMPTY_STRING;
responseScopes = [];
expiresOn = null;
familyId = Constants.EMPTY_STRING;
if (!cacheRecord.accessToken) return [3 /*break*/, 4];
if (!(cacheRecord.accessToken.tokenType === AuthenticationScheme.POP)) return [3 /*break*/, 2];
popTokenGenerator = new PopTokenGenerator(cryptoObj);
_d = cacheRecord.accessToken, secret = _d.secret, keyId = _d.keyId;
if (!keyId) {
throw ClientAuthError.createKeyIdMissingError();
}
return [4 /*yield*/, popTokenGenerator.signPopToken(secret, keyId, request)];
case 1:
accessToken = _e.sent();
return [3 /*break*/, 3];
case 2:
accessToken = cacheRecord.accessToken.secret;
_e.label = 3;
case 3:
responseScopes = ScopeSet.fromString(cacheRecord.accessToken.target).asArray();
expiresOn = new Date(Number(cacheRecord.accessToken.expiresOn) * 1000);
extExpiresOn = new Date(Number(cacheRecord.accessToken.extendedExpiresOn) * 1000);
_e.label = 4;
case 4:
if (cacheRecord.appMetadata) {
familyId = cacheRecord.appMetadata.familyId === THE_FAMILY_ID ? THE_FAMILY_ID : Constants.EMPTY_STRING;
}
uid = (idTokenObj === null || idTokenObj === void 0 ? void 0 : idTokenObj.claims.oid) || (idTokenObj === null || idTokenObj === void 0 ? void 0 : idTokenObj.claims.sub) || Constants.EMPTY_STRING;
tid = (idTokenObj === null || idTokenObj === void 0 ? void 0 : idTokenObj.claims.tid) || Constants.EMPTY_STRING;
// for hybrid + native bridge enablement, send back the native account Id
if ((serverTokenResponse === null || serverTokenResponse === void 0 ? void 0 : serverTokenResponse.spa_accountid) && !!cacheRecord.account) {
cacheRecord.account.nativeAccountId = serverTokenResponse === null || serverTokenResponse === void 0 ? void 0 : serverTokenResponse.spa_accountid;
}
return [2 /*return*/, {
authority: authority.canonicalAuthority,
uniqueId: uid,
tenantId: tid,
scopes: responseScopes,
account: cacheRecord.account ? cacheRecord.account.getAccountInfo() : null,
idToken: idTokenObj ? idTokenObj.rawToken : Constants.EMPTY_STRING,
idTokenClaims: idTokenObj ? idTokenObj.claims : {},
accessToken: accessToken,
fromCache: fromTokenCache,
expiresOn: expiresOn,
correlationId: request.correlationId,
requestId: requestId || Constants.EMPTY_STRING,
extExpiresOn: extExpiresOn,
familyId: familyId,
tokenType: ((_a = cacheRecord.accessToken) === null || _a === void 0 ? void 0 : _a.tokenType) || Constants.EMPTY_STRING,
state: requestState ? requestState.userRequestState : Constants.EMPTY_STRING,
cloudGraphHostName: ((_b = cacheRecord.account) === null || _b === void 0 ? void 0 : _b.cloudGraphHostName) || Constants.EMPTY_STRING,
msGraphHost: ((_c = cacheRecord.account) === null || _c === void 0 ? void 0 : _c.msGraphHost) || Constants.EMPTY_STRING,
code: serverTokenResponse === null || serverTokenResponse === void 0 ? void 0 : serverTokenResponse.spa_code,
fromNativeBroker: false,
}];
static async generateAuthenticationResult(cryptoObj, authority, cacheRecord, fromTokenCache, request, idTokenObj, requestState, serverTokenResponse, requestId) {
let accessToken = Constants.EMPTY_STRING;
let responseScopes = [];
let expiresOn = null;
let extExpiresOn;
let familyId = Constants.EMPTY_STRING;
if (cacheRecord.accessToken) {
if (cacheRecord.accessToken.tokenType === AuthenticationScheme.POP) {
const popTokenGenerator = new PopTokenGenerator(cryptoObj);
const { secret, keyId } = cacheRecord.accessToken;
if (!keyId) {
throw ClientAuthError.createKeyIdMissingError();
}
});
});
};
return ResponseHandler;
}());
accessToken = await popTokenGenerator.signPopToken(secret, keyId, request);
}
else {
accessToken = cacheRecord.accessToken.secret;
}
responseScopes = ScopeSet.fromString(cacheRecord.accessToken.target).asArray();
expiresOn = new Date(Number(cacheRecord.accessToken.expiresOn) * 1000);
extExpiresOn = new Date(Number(cacheRecord.accessToken.extendedExpiresOn) * 1000);
}
if (cacheRecord.appMetadata) {
familyId =
cacheRecord.appMetadata.familyId === THE_FAMILY_ID
? THE_FAMILY_ID
: Constants.EMPTY_STRING;
}
const uid = idTokenObj?.claims.oid ||
idTokenObj?.claims.sub ||
Constants.EMPTY_STRING;
const tid = idTokenObj?.claims.tid || Constants.EMPTY_STRING;
// for hybrid + native bridge enablement, send back the native account Id
if (serverTokenResponse?.spa_accountid && !!cacheRecord.account) {
cacheRecord.account.nativeAccountId =
serverTokenResponse?.spa_accountid;
}
return {
authority: authority.canonicalAuthority,
uniqueId: uid,
tenantId: tid,
scopes: responseScopes,
account: cacheRecord.account
? cacheRecord.account.getAccountInfo()
: null,
idToken: idTokenObj ? idTokenObj.rawToken : Constants.EMPTY_STRING,
idTokenClaims: idTokenObj ? idTokenObj.claims : {},
accessToken: accessToken,
fromCache: fromTokenCache,
expiresOn: expiresOn,
correlationId: request.correlationId,
requestId: requestId || Constants.EMPTY_STRING,
extExpiresOn: extExpiresOn,
familyId: familyId,
tokenType: cacheRecord.accessToken?.tokenType || Constants.EMPTY_STRING,
state: requestState
? requestState.userRequestState
: Constants.EMPTY_STRING,
cloudGraphHostName: cacheRecord.account?.cloudGraphHostName ||
Constants.EMPTY_STRING,
msGraphHost: cacheRecord.account?.msGraphHost || Constants.EMPTY_STRING,
code: serverTokenResponse?.spa_code,
fromNativeBroker: false,
};
}
}
export { ResponseHandler };
//# sourceMappingURL=ResponseHandler.js.map

@@ -9,3 +9,3 @@ /**

*/
export declare type ServerAuthorizationCodeResponse = {
export type ServerAuthorizationCodeResponse = {
code?: string;

@@ -12,0 +12,0 @@ client_info?: string;

@@ -22,3 +22,3 @@ import { AuthenticationScheme } from "../utils/Constants";

*/
export declare type ServerAuthorizationTokenResponse = {
export type ServerAuthorizationTokenResponse = {
token_type?: AuthenticationScheme;

@@ -25,0 +25,0 @@ scope?: string;

import { Counters, PerformanceEvent, PerformanceEvents, StaticFields } from "./PerformanceEvent";
import { IPerformanceMeasurement } from "./IPerformanceMeasurement";
export declare type PerformanceCallbackFunction = (events: PerformanceEvent[]) => void;
export declare type InProgressPerformanceEvent = {
export type PerformanceCallbackFunction = (events: PerformanceEvent[]) => void;
export type InProgressPerformanceEvent = {
endMeasurement: (event?: Partial<PerformanceEvent>) => PerformanceEvent | null;

@@ -20,3 +20,2 @@ discardMeasurement: () => void;

emitEvents(events: PerformanceEvent[], correlationId: string): void;
startPerformanceMeasuremeant(measureName: string, correlationId: string): IPerformanceMeasurement;
startPerformanceMeasurement(measureName: string, correlationId: string): IPerformanceMeasurement;

@@ -31,3 +30,3 @@ generateId(): string;

*/
export declare type QueueMeasurement = {
export type QueueMeasurement = {
/**

@@ -34,0 +33,0 @@ * Name of performance event

@@ -65,13 +65,5 @@ import { ApplicationTelemetry } from "../../config/ClientConfiguration";

*/
startPerformanceMeasurement(measureName: string, correlationId: string): IPerformanceMeasurement;
startPerformanceMeasurement(measureName: string, // eslint-disable-line @typescript-eslint/no-unused-vars
correlationId: string): IPerformanceMeasurement;
/**
* Starts and returns an platform-specific implementation of IPerformanceMeasurement.
* Note: this incorrectly-named function will be removed at the next major version bump.
*
* @param {string} measureName
* @param {string} correlationId
* @returns {IPerformanceMeasurement}
*/
startPerformanceMeasuremeant(measureName: string, correlationId: string): IPerformanceMeasurement;
/**
* Sets pre-queue time by correlation Id

@@ -78,0 +70,0 @@ *

@@ -1,4 +0,3 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';
import { __assign } from '../../_virtual/_tslib.js';
import { IntFields, PerformanceEventStatus } from './PerformanceEvent.js';

@@ -10,3 +9,3 @@

*/
var PerformanceClient = /** @class */ (function () {
class PerformanceClient {
/**

@@ -23,3 +22,3 @@ * Creates an instance of PerformanceClient,

*/
function PerformanceClient(clientId, authority, logger, libraryName, libraryVersion, applicationTelemetry) {
constructor(clientId, authority, logger, libraryName, libraryVersion, applicationTelemetry) {
this.authority = authority;

@@ -44,25 +43,14 @@ this.libraryName = libraryName;

*/
/* eslint-disable-next-line @typescript-eslint/no-unused-vars */
PerformanceClient.prototype.startPerformanceMeasurement = function (measureName, correlationId) {
startPerformanceMeasurement(measureName, // eslint-disable-line @typescript-eslint/no-unused-vars
correlationId // eslint-disable-line @typescript-eslint/no-unused-vars
) {
return {};
};
}
/**
* Starts and returns an platform-specific implementation of IPerformanceMeasurement.
* Note: this incorrectly-named function will be removed at the next major version bump.
*
* @param {string} measureName
* @param {string} correlationId
* @returns {IPerformanceMeasurement}
*/
/* eslint-disable-next-line @typescript-eslint/no-unused-vars */
PerformanceClient.prototype.startPerformanceMeasuremeant = function (measureName, correlationId) {
return {};
};
/**
* Get integral fields.
* Override to change the set.
*/
PerformanceClient.prototype.getIntFields = function () {
getIntFields() {
return IntFields;
};
}
/**

@@ -75,14 +63,14 @@ * Gets map of pre-queue times by correlation Id

*/
PerformanceClient.prototype.getPreQueueTime = function (eventName, correlationId) {
var preQueueEvent = this.preQueueTimeByCorrelationId.get(correlationId);
getPreQueueTime(eventName, correlationId) {
const preQueueEvent = this.preQueueTimeByCorrelationId.get(correlationId);
if (!preQueueEvent) {
this.logger.trace("PerformanceClient.getPreQueueTime: no pre-queue times found for correlationId: " + correlationId + ", unable to add queue measurement");
this.logger.trace(`PerformanceClient.getPreQueueTime: no pre-queue times found for correlationId: ${correlationId}, unable to add queue measurement`);
return;
}
else if (preQueueEvent.name !== eventName) {
this.logger.trace("PerformanceClient.getPreQueueTime: no pre-queue time found for " + eventName + ", unable to add queue measurement");
this.logger.trace(`PerformanceClient.getPreQueueTime: no pre-queue time found for ${eventName}, unable to add queue measurement`);
return;
}
return preQueueEvent.time;
};
}
/**

@@ -96,9 +84,9 @@ * Calculates the difference between current time and time when function was queued.

*/
PerformanceClient.prototype.calculateQueuedTime = function (preQueueTime, currentTime) {
calculateQueuedTime(preQueueTime, currentTime) {
if (preQueueTime < 1) {
this.logger.trace("PerformanceClient: preQueueTime should be a positive integer and not " + preQueueTime);
this.logger.trace(`PerformanceClient: preQueueTime should be a positive integer and not ${preQueueTime}`);
return 0;
}
if (currentTime < 1) {
this.logger.trace("PerformanceClient: currentTime should be a positive integer and not " + currentTime);
this.logger.trace(`PerformanceClient: currentTime should be a positive integer and not ${currentTime}`);
return 0;

@@ -111,3 +99,3 @@ }

return currentTime - preQueueTime;
};
}
/**

@@ -122,5 +110,5 @@ * Adds queue measurement time to QueueMeasurements array for given correlation ID.

*/
PerformanceClient.prototype.addQueueMeasurement = function (eventName, correlationId, queueTime, manuallyCompleted) {
addQueueMeasurement(eventName, correlationId, queueTime, manuallyCompleted) {
if (!correlationId) {
this.logger.trace("PerformanceClient.addQueueMeasurement: correlationId not provided for " + eventName + ", cannot add queue measurement");
this.logger.trace(`PerformanceClient.addQueueMeasurement: correlationId not provided for ${eventName}, cannot add queue measurement`);
return;

@@ -130,11 +118,15 @@ }

// Possible for there to be no queue time after calculation
this.logger.trace("PerformanceClient.addQueueMeasurement: queue time provided for " + eventName + " is " + queueTime);
this.logger.trace(`PerformanceClient.addQueueMeasurement: queue time provided for ${eventName} is ${queueTime}`);
}
else if (!queueTime) {
this.logger.trace("PerformanceClient.addQueueMeasurement: no queue time provided for " + eventName);
this.logger.trace(`PerformanceClient.addQueueMeasurement: no queue time provided for ${eventName}`);
return;
}
var queueMeasurement = { eventName: eventName, queueTime: queueTime, manuallyCompleted: manuallyCompleted };
const queueMeasurement = {
eventName,
queueTime,
manuallyCompleted,
};
// Adds to existing correlation Id if present in queueMeasurements
var existingMeasurements = this.queueMeasurements.get(correlationId);
const existingMeasurements = this.queueMeasurements.get(correlationId);
if (existingMeasurements) {

@@ -146,4 +138,4 @@ existingMeasurements.push(queueMeasurement);

// Sets new correlation Id if not present in queueMeasurements
this.logger.trace("PerformanceClient.addQueueMeasurement: adding correlationId " + correlationId + " to queue measurements");
var measurementArray = [queueMeasurement];
this.logger.trace(`PerformanceClient.addQueueMeasurement: adding correlationId ${correlationId} to queue measurements`);
const measurementArray = [queueMeasurement];
this.queueMeasurements.set(correlationId, measurementArray);

@@ -153,3 +145,3 @@ }

this.preQueueTimeByCorrelationId.delete(correlationId);
};
}
/**

@@ -162,15 +154,12 @@ * Starts measuring performance for a given operation. Returns a function that should be used to end the measurement.

*/
PerformanceClient.prototype.startMeasurement = function (measureName, correlationId) {
var _this = this;
var _a, _b;
startMeasurement(measureName, correlationId) {
// Generate a placeholder correlation if the request does not provide one
var eventCorrelationId = correlationId || this.generateId();
const eventCorrelationId = correlationId || this.generateId();
if (!correlationId) {
this.logger.info("PerformanceClient: No correlation id provided for " + measureName + ", generating", eventCorrelationId);
this.logger.info(`PerformanceClient: No correlation id provided for ${measureName}, generating`, eventCorrelationId);
}
// Duplicate code to address spelling error will be removed at the next major version bump.
this.logger.trace("PerformanceClient: Performance measurement started for " + measureName, eventCorrelationId);
var performanceMeasurement = this.startPerformanceMeasuremeant(measureName, eventCorrelationId);
this.logger.trace(`PerformanceClient: Performance measurement started for ${measureName}`, eventCorrelationId);
const performanceMeasurement = this.startPerformanceMeasurement(measureName, eventCorrelationId);
performanceMeasurement.startMeasurement();
var inProgressEvent = {
const inProgressEvent = {
eventId: this.generateId(),

@@ -185,4 +174,4 @@ status: PerformanceEventStatus.InProgress,

correlationId: eventCorrelationId,
appName: (_a = this.applicationTelemetry) === null || _a === void 0 ? void 0 : _a.appName,
appVersion: (_b = this.applicationTelemetry) === null || _b === void 0 ? void 0 : _b.appVersion,
appName: this.applicationTelemetry?.appName,
appVersion: this.applicationTelemetry?.appVersion,
};

@@ -193,18 +182,23 @@ // Store in progress events so they can be discarded if not ended properly

return {
endMeasurement: function (event) {
return _this.endMeasurement(__assign(__assign({}, inProgressEvent), event), performanceMeasurement);
endMeasurement: (event) => {
return this.endMeasurement({
// Initial set of event properties
...inProgressEvent,
// Properties set when event ends
...event,
}, performanceMeasurement);
},
discardMeasurement: function () {
return _this.discardMeasurements(inProgressEvent.correlationId);
discardMeasurement: () => {
return this.discardMeasurements(inProgressEvent.correlationId);
},
addStaticFields: function (fields) {
return _this.addStaticFields(fields, inProgressEvent.correlationId);
addStaticFields: (fields) => {
return this.addStaticFields(fields, inProgressEvent.correlationId);
},
increment: function (counters) {
return _this.increment(counters, inProgressEvent.correlationId);
increment: (counters) => {
return this.increment(counters, inProgressEvent.correlationId);
},
measurement: performanceMeasurement,
event: inProgressEvent
event: inProgressEvent,
};
};
}
/**

@@ -220,15 +214,13 @@ * Stops measuring the performance for an operation. Should only be called directly by PerformanceClient classes,

*/
PerformanceClient.prototype.endMeasurement = function (event, measurement) {
var _this = this;
var _a, _b;
var rootEvent = this.eventsByCorrelationId.get(event.correlationId);
endMeasurement(event, measurement) {
const rootEvent = this.eventsByCorrelationId.get(event.correlationId);
if (!rootEvent) {
this.logger.trace("PerformanceClient: Measurement not found for " + event.eventId, event.correlationId);
this.logger.trace(`PerformanceClient: Measurement not found for ${event.eventId}`, event.correlationId);
return null;
}
var isRoot = event.eventId === rootEvent.eventId;
var queueInfo = {
const isRoot = event.eventId === rootEvent.eventId;
let queueInfo = {
totalQueueTime: 0,
totalQueueCount: 0,
manuallyCompletedCount: 0
manuallyCompletedCount: 0,
};

@@ -240,6 +232,6 @@ if (isRoot) {

else {
(_a = rootEvent.incompleteSubMeasurements) === null || _a === void 0 ? void 0 : _a.delete(event.eventId);
rootEvent.incompleteSubMeasurements?.delete(event.eventId);
}
measurement === null || measurement === void 0 ? void 0 : measurement.endMeasurement();
var durationMs = measurement === null || measurement === void 0 ? void 0 : measurement.flushMeasurement();
measurement?.endMeasurement();
const durationMs = measurement?.flushMeasurement();
// null indicates no measurement was taken (e.g. needed performance APIs not present)

@@ -250,21 +242,29 @@ if (!durationMs) {

}
this.logger.trace("PerformanceClient: Performance measurement ended for " + event.name + ": " + durationMs + " ms", event.correlationId);
this.logger.trace(`PerformanceClient: Performance measurement ended for ${event.name}: ${durationMs} ms`, event.correlationId);
// Add sub-measurement attribute to root event.
if (!isRoot) {
rootEvent[event.name + "DurationMs"] = Math.floor(durationMs);
return __assign({}, rootEvent);
return { ...rootEvent };
}
var finalEvent = __assign(__assign({}, rootEvent), event);
var incompleteSubsCount = 0;
let finalEvent = { ...rootEvent, ...event };
let incompleteSubsCount = 0;
// Incomplete sub-measurements are discarded. They are likely an instrumentation bug that should be fixed.
(_b = finalEvent.incompleteSubMeasurements) === null || _b === void 0 ? void 0 : _b.forEach(function (subMeasurement) {
_this.logger.trace("PerformanceClient: Incomplete submeasurement " + subMeasurement.name + " found for " + event.name, finalEvent.correlationId);
finalEvent.incompleteSubMeasurements?.forEach((subMeasurement) => {
this.logger.trace(`PerformanceClient: Incomplete submeasurement ${subMeasurement.name} found for ${event.name}`, finalEvent.correlationId);
incompleteSubsCount++;
});
finalEvent.incompleteSubMeasurements = undefined;
finalEvent = __assign(__assign({}, finalEvent), { durationMs: Math.round(durationMs), queuedTimeMs: queueInfo.totalQueueTime, queuedCount: queueInfo.totalQueueCount, queuedManuallyCompletedCount: queueInfo.manuallyCompletedCount, status: PerformanceEventStatus.Completed, incompleteSubsCount: incompleteSubsCount });
finalEvent = {
...finalEvent,
durationMs: Math.round(durationMs),
queuedTimeMs: queueInfo.totalQueueTime,
queuedCount: queueInfo.totalQueueCount,
queuedManuallyCompletedCount: queueInfo.manuallyCompletedCount,
status: PerformanceEventStatus.Completed,
incompleteSubsCount,
};
this.truncateIntegralFields(finalEvent, this.getIntFields());
this.emitEvents([finalEvent], event.correlationId);
return finalEvent;
};
}
/**

@@ -275,7 +275,10 @@ * Saves extra information to be emitted when the measurements are flushed

*/
PerformanceClient.prototype.addStaticFields = function (fields, correlationId) {
addStaticFields(fields, correlationId) {
this.logger.trace("PerformanceClient: Updating static fields");
var event = this.eventsByCorrelationId.get(correlationId);
const event = this.eventsByCorrelationId.get(correlationId);
if (event) {
this.eventsByCorrelationId.set(correlationId, __assign(__assign({}, event), fields));
this.eventsByCorrelationId.set(correlationId, {
...event,
...fields,
});
}

@@ -285,3 +288,3 @@ else {

}
};
}
/**

@@ -292,7 +295,7 @@ * Increment counters to be emitted when the measurements are flushed

*/
PerformanceClient.prototype.increment = function (counters, correlationId) {
increment(counters, correlationId) {
this.logger.trace("PerformanceClient: Updating counters");
var event = this.eventsByCorrelationId.get(correlationId);
const event = this.eventsByCorrelationId.get(correlationId);
if (event) {
for (var counter in counters) {
for (const counter in counters) {
if (!event.hasOwnProperty(counter)) {

@@ -307,3 +310,3 @@ event[counter] = 0;

}
};
}
/**

@@ -318,23 +321,27 @@ * Upserts event into event cache.

*/
PerformanceClient.prototype.cacheEventByCorrelationId = function (event) {
var rootEvent = this.eventsByCorrelationId.get(event.correlationId);
cacheEventByCorrelationId(event) {
const rootEvent = this.eventsByCorrelationId.get(event.correlationId);
if (rootEvent) {
this.logger.trace("PerformanceClient: Performance measurement for " + event.name + " added/updated", event.correlationId);
rootEvent.incompleteSubMeasurements = rootEvent.incompleteSubMeasurements || new Map();
rootEvent.incompleteSubMeasurements.set(event.eventId, { name: event.name, startTimeMs: event.startTimeMs });
this.logger.trace(`PerformanceClient: Performance measurement for ${event.name} added/updated`, event.correlationId);
rootEvent.incompleteSubMeasurements =
rootEvent.incompleteSubMeasurements || new Map();
rootEvent.incompleteSubMeasurements.set(event.eventId, {
name: event.name,
startTimeMs: event.startTimeMs,
});
}
else {
this.logger.trace("PerformanceClient: Performance measurement for " + event.name + " started", event.correlationId);
this.eventsByCorrelationId.set(event.correlationId, __assign({}, event));
this.logger.trace(`PerformanceClient: Performance measurement for ${event.name} started`, event.correlationId);
this.eventsByCorrelationId.set(event.correlationId, { ...event });
}
};
PerformanceClient.prototype.getQueueInfo = function (correlationId) {
var queueMeasurementForCorrelationId = this.queueMeasurements.get(correlationId);
}
getQueueInfo(correlationId) {
const queueMeasurementForCorrelationId = this.queueMeasurements.get(correlationId);
if (!queueMeasurementForCorrelationId) {
this.logger.trace("PerformanceClient: no queue measurements found for for correlationId: " + correlationId);
this.logger.trace(`PerformanceClient: no queue measurements found for for correlationId: ${correlationId}`);
}
var totalQueueTime = 0;
var totalQueueCount = 0;
var manuallyCompletedCount = 0;
queueMeasurementForCorrelationId === null || queueMeasurementForCorrelationId === void 0 ? void 0 : queueMeasurementForCorrelationId.forEach(function (measurement) {
let totalQueueTime = 0;
let totalQueueCount = 0;
let manuallyCompletedCount = 0;
queueMeasurementForCorrelationId?.forEach((measurement) => {
totalQueueTime += measurement.queueTime;

@@ -345,7 +352,7 @@ totalQueueCount++;

return {
totalQueueTime: totalQueueTime,
totalQueueCount: totalQueueCount,
manuallyCompletedCount: manuallyCompletedCount
totalQueueTime,
totalQueueCount,
manuallyCompletedCount,
};
};
}
/**

@@ -356,6 +363,6 @@ * Removes measurements for a given correlation id.

*/
PerformanceClient.prototype.discardMeasurements = function (correlationId) {
discardMeasurements(correlationId) {
this.logger.trace("PerformanceClient: Performance measurements discarded", correlationId);
this.eventsByCorrelationId.delete(correlationId);
};
}
/**

@@ -366,3 +373,3 @@ * Removes cache for a given correlation id.

*/
PerformanceClient.prototype.discardCache = function (correlationId) {
discardCache(correlationId) {
this.discardMeasurements(correlationId);

@@ -373,3 +380,3 @@ this.logger.trace("PerformanceClient: QueueMeasurements discarded", correlationId);

this.preQueueTimeByCorrelationId.delete(correlationId);
};
}
/**

@@ -381,8 +388,8 @@ * Registers a callback function to receive performance events.

*/
PerformanceClient.prototype.addPerformanceCallback = function (callback) {
var callbackId = this.generateId();
addPerformanceCallback(callback) {
const callbackId = this.generateId();
this.callbacks.set(callbackId, callback);
this.logger.verbose("PerformanceClient: Performance callback registered with id: " + callbackId);
this.logger.verbose(`PerformanceClient: Performance callback registered with id: ${callbackId}`);
return callbackId;
};
}
/**

@@ -394,12 +401,12 @@ * Removes a callback registered with addPerformanceCallback.

*/
PerformanceClient.prototype.removePerformanceCallback = function (callbackId) {
var result = this.callbacks.delete(callbackId);
removePerformanceCallback(callbackId) {
const result = this.callbacks.delete(callbackId);
if (result) {
this.logger.verbose("PerformanceClient: Performance callback " + callbackId + " removed.");
this.logger.verbose(`PerformanceClient: Performance callback ${callbackId} removed.`);
}
else {
this.logger.verbose("PerformanceClient: Performance callback " + callbackId + " not removed.");
this.logger.verbose(`PerformanceClient: Performance callback ${callbackId} not removed.`);
}
return result;
};
}
/**

@@ -411,10 +418,9 @@ * Emits events to all registered callbacks.

*/
PerformanceClient.prototype.emitEvents = function (events, correlationId) {
var _this = this;
emitEvents(events, correlationId) {
this.logger.verbose("PerformanceClient: Emitting performance events", correlationId);
this.callbacks.forEach(function (callback, callbackId) {
_this.logger.trace("PerformanceClient: Emitting event to callback " + callbackId, correlationId);
this.callbacks.forEach((callback, callbackId) => {
this.logger.trace(`PerformanceClient: Emitting event to callback ${callbackId}`, correlationId);
callback.apply(null, [events]);
});
};
}
/**

@@ -425,4 +431,4 @@ * Enforce truncation of integral fields in performance event.

*/
PerformanceClient.prototype.truncateIntegralFields = function (event, intFields) {
intFields.forEach(function (key) {
truncateIntegralFields(event, intFields) {
intFields.forEach((key) => {
if (key in event && typeof event[key] === "number") {

@@ -432,7 +438,6 @@ event[key] = Math.floor(event[key]);

});
};
return PerformanceClient;
}());
}
}
export { PerformanceClient };
//# sourceMappingURL=PerformanceClient.js.map

@@ -214,3 +214,3 @@ /**

*/
export declare type StaticFields = {
export type StaticFields = {
/**

@@ -285,3 +285,3 @@ * The Silent Token Cache Lookup Policy

*/
export declare type Counters = {
export type Counters = {
visibilityChangeCount?: number;

@@ -302,3 +302,3 @@ incompleteSubsCount?: number;

};
export declare type SubMeasurement = {
export type SubMeasurement = {
name: PerformanceEvents;

@@ -313,3 +313,3 @@ startTimeMs: number;

*/
export declare type PerformanceEvent = StaticFields & Counters & {
export type PerformanceEvent = StaticFields & Counters & {
/**

@@ -316,0 +316,0 @@ * Unique id for the event

@@ -1,2 +0,2 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';

@@ -219,3 +219,3 @@ /*

})(PerformanceEventStatus || (PerformanceEventStatus = {}));
var IntFields = new Set([
const IntFields = new Set([
"accessTokenSize",

@@ -222,0 +222,0 @@ "durationMs",

@@ -12,8 +12,10 @@ import { IPerformanceClient } from "./IPerformanceClient";

generateId(): string;
startPerformanceMeasuremeant(): IPerformanceMeasurement;
startPerformanceMeasurement(): IPerformanceMeasurement;
calculateQueuedTime(preQueueTime: number, currentTime: number): number;
addQueueMeasurement(eventName: PerformanceEvents, correlationId: string, queueTime: number): void;
setPreQueueTime(eventName: PerformanceEvents, correlationId?: string | undefined): void;
addQueueMeasurement(eventName: PerformanceEvents, // eslint-disable-line @typescript-eslint/no-unused-vars
correlationId: string, // eslint-disable-line @typescript-eslint/no-unused-vars
queueTime: number): void;
setPreQueueTime(eventName: PerformanceEvents, // eslint-disable-line @typescript-eslint/no-unused-vars
correlationId?: string | undefined): void;
}
//# sourceMappingURL=StubPerformanceClient.d.ts.map

@@ -1,4 +0,3 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';
import { __extends } from '../../_virtual/_tslib.js';
import { PerformanceClient } from './PerformanceClient.js';

@@ -10,44 +9,36 @@

*/
var StubPerformanceMeasurement = /** @class */ (function () {
function StubPerformanceMeasurement() {
}
class StubPerformanceMeasurement {
/* eslint-disable-next-line @typescript-eslint/no-empty-function */
StubPerformanceMeasurement.prototype.startMeasurement = function () { };
startMeasurement() { }
/* eslint-disable-next-line @typescript-eslint/no-empty-function */
StubPerformanceMeasurement.prototype.endMeasurement = function () { };
StubPerformanceMeasurement.prototype.flushMeasurement = function () {
endMeasurement() { }
flushMeasurement() {
return null;
};
return StubPerformanceMeasurement;
}());
var StubPerformanceClient = /** @class */ (function (_super) {
__extends(StubPerformanceClient, _super);
function StubPerformanceClient() {
return _super !== null && _super.apply(this, arguments) || this;
}
StubPerformanceClient.prototype.generateId = function () {
}
class StubPerformanceClient extends PerformanceClient {
generateId() {
return "callback-id";
};
StubPerformanceClient.prototype.startPerformanceMeasuremeant = function () {
}
startPerformanceMeasurement() {
return new StubPerformanceMeasurement();
};
StubPerformanceClient.prototype.startPerformanceMeasurement = function () {
return new StubPerformanceMeasurement();
};
}
/* eslint-disable-next-line @typescript-eslint/no-unused-vars */
StubPerformanceClient.prototype.calculateQueuedTime = function (preQueueTime, currentTime) {
calculateQueuedTime(preQueueTime, currentTime) {
return 0;
};
/* eslint-disable-next-line @typescript-eslint/no-unused-vars */
StubPerformanceClient.prototype.addQueueMeasurement = function (eventName, correlationId, queueTime) {
}
addQueueMeasurement(eventName, // eslint-disable-line @typescript-eslint/no-unused-vars
correlationId, // eslint-disable-line @typescript-eslint/no-unused-vars
queueTime // eslint-disable-line @typescript-eslint/no-unused-vars
) {
return;
};
/* eslint-disable-next-line @typescript-eslint/no-unused-vars */
StubPerformanceClient.prototype.setPreQueueTime = function (eventName, correlationId) {
}
setPreQueueTime(eventName, // eslint-disable-line @typescript-eslint/no-unused-vars
correlationId // eslint-disable-line @typescript-eslint/no-unused-vars
) {
return;
};
return StubPerformanceClient;
}(PerformanceClient));
}
}
export { StubPerformanceClient, StubPerformanceMeasurement };
//# sourceMappingURL=StubPerformanceClient.js.map
import { CacheOutcome } from "../../utils/Constants";
import { CacheManager } from "../../cache/CacheManager";
import { AuthError } from "../../error/AuthError";
import { ServerTelemetryRequest } from "./ServerTelemetryRequest";

@@ -31,3 +30,3 @@ import { ServerTelemetryEntity } from "../../cache/entities/ServerTelemetryEntity";

*/
cacheFailedRequest(error: AuthError): void;
cacheFailedRequest(error: unknown): void;
/**

@@ -34,0 +33,0 @@ * Update server telemetry cache entry by incrementing cache hit counter

@@ -1,4 +0,5 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';
import { SERVER_TELEM_CONSTANTS, CacheOutcome, Constants, Separators } from '../../utils/Constants.js';
import { CacheOutcome, Constants, SERVER_TELEM_CONSTANTS, Separators } from '../../utils/Constants.js';
import { AuthError } from '../../error/AuthError.js';
import { ServerTelemetryEntity } from '../../cache/entities/ServerTelemetryEntity.js';

@@ -11,4 +12,4 @@ import { StringUtils } from '../../utils/StringUtils.js';

*/
var ServerTelemetryManager = /** @class */ (function () {
function ServerTelemetryManager(telemetryRequest, cacheManager) {
class ServerTelemetryManager {
constructor(telemetryRequest, cacheManager) {
this.cacheOutcome = CacheOutcome.NO_CACHE_HIT;

@@ -20,3 +21,6 @@ this.cacheManager = cacheManager;

this.wrapperVer = telemetryRequest.wrapperVer || Constants.EMPTY_STRING;
this.telemetryCacheKey = SERVER_TELEM_CONSTANTS.CACHE_KEY + Separators.CACHE_KEY_SEPARATOR + telemetryRequest.clientId;
this.telemetryCacheKey =
SERVER_TELEM_CONSTANTS.CACHE_KEY +
Separators.CACHE_KEY_SEPARATOR +
telemetryRequest.clientId;
}

@@ -26,23 +30,42 @@ /**

*/
ServerTelemetryManager.prototype.generateCurrentRequestHeaderValue = function () {
var request = "" + this.apiId + SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR + this.cacheOutcome;
var platformFields = [this.wrapperSKU, this.wrapperVer].join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR);
var regionDiscoveryFields = this.getRegionDiscoveryFields();
var requestWithRegionDiscoveryFields = [request, regionDiscoveryFields].join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR);
return [SERVER_TELEM_CONSTANTS.SCHEMA_VERSION, requestWithRegionDiscoveryFields, platformFields].join(SERVER_TELEM_CONSTANTS.CATEGORY_SEPARATOR);
};
generateCurrentRequestHeaderValue() {
const request = `${this.apiId}${SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR}${this.cacheOutcome}`;
const platformFields = [this.wrapperSKU, this.wrapperVer].join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR);
const regionDiscoveryFields = this.getRegionDiscoveryFields();
const requestWithRegionDiscoveryFields = [
request,
regionDiscoveryFields,
].join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR);
return [
SERVER_TELEM_CONSTANTS.SCHEMA_VERSION,
requestWithRegionDiscoveryFields,
platformFields,
].join(SERVER_TELEM_CONSTANTS.CATEGORY_SEPARATOR);
}
/**
* API to add MSER Telemetry for the last failed request
*/
ServerTelemetryManager.prototype.generateLastRequestHeaderValue = function () {
var lastRequests = this.getLastRequests();
var maxErrors = ServerTelemetryManager.maxErrorsToSend(lastRequests);
var failedRequests = lastRequests.failedRequests.slice(0, 2 * maxErrors).join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR);
var errors = lastRequests.errors.slice(0, maxErrors).join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR);
var errorCount = lastRequests.errors.length;
generateLastRequestHeaderValue() {
const lastRequests = this.getLastRequests();
const maxErrors = ServerTelemetryManager.maxErrorsToSend(lastRequests);
const failedRequests = lastRequests.failedRequests
.slice(0, 2 * maxErrors)
.join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR);
const errors = lastRequests.errors
.slice(0, maxErrors)
.join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR);
const errorCount = lastRequests.errors.length;
// Indicate whether this header contains all data or partial data
var overflow = maxErrors < errorCount ? SERVER_TELEM_CONSTANTS.OVERFLOW_TRUE : SERVER_TELEM_CONSTANTS.OVERFLOW_FALSE;
var platformFields = [errorCount, overflow].join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR);
return [SERVER_TELEM_CONSTANTS.SCHEMA_VERSION, lastRequests.cacheHits, failedRequests, errors, platformFields].join(SERVER_TELEM_CONSTANTS.CATEGORY_SEPARATOR);
};
const overflow = maxErrors < errorCount
? SERVER_TELEM_CONSTANTS.OVERFLOW_TRUE
: SERVER_TELEM_CONSTANTS.OVERFLOW_FALSE;
const platformFields = [errorCount, overflow].join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR);
return [
SERVER_TELEM_CONSTANTS.SCHEMA_VERSION,
lastRequests.cacheHits,
failedRequests,
errors,
platformFields,
].join(SERVER_TELEM_CONSTANTS.CATEGORY_SEPARATOR);
}
/**

@@ -52,5 +75,6 @@ * API to cache token failures for MSER data capture

*/
ServerTelemetryManager.prototype.cacheFailedRequest = function (error) {
var lastRequests = this.getLastRequests();
if (lastRequests.errors.length >= SERVER_TELEM_CONSTANTS.MAX_CACHED_ERRORS) {
cacheFailedRequest(error) {
const lastRequests = this.getLastRequests();
if (lastRequests.errors.length >=
SERVER_TELEM_CONSTANTS.MAX_CACHED_ERRORS) {
// Remove a cached error to make room, first in first out

@@ -62,11 +86,18 @@ lastRequests.failedRequests.shift(); // apiId

lastRequests.failedRequests.push(this.apiId, this.correlationId);
if (!StringUtils.isEmpty(error.subError)) {
lastRequests.errors.push(error.subError);
if (error instanceof Error && !!error && error.toString()) {
if (error instanceof AuthError) {
if (!StringUtils.isEmpty(error.subError)) {
lastRequests.errors.push(error.subError);
}
else if (!StringUtils.isEmpty(error.errorCode)) {
lastRequests.errors.push(error.errorCode);
}
else {
lastRequests.errors.push(error.toString());
}
}
else {
lastRequests.errors.push(error.toString());
}
}
else if (!StringUtils.isEmpty(error.errorCode)) {
lastRequests.errors.push(error.errorCode);
}
else if (!!error && error.toString()) {
lastRequests.errors.push(error.toString());
}
else {

@@ -77,27 +108,27 @@ lastRequests.errors.push(SERVER_TELEM_CONSTANTS.UNKNOWN_ERROR);

return;
};
}
/**
* Update server telemetry cache entry by incrementing cache hit counter
*/
ServerTelemetryManager.prototype.incrementCacheHits = function () {
var lastRequests = this.getLastRequests();
incrementCacheHits() {
const lastRequests = this.getLastRequests();
lastRequests.cacheHits += 1;
this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests);
return lastRequests.cacheHits;
};
}
/**
* Get the server telemetry entity from cache or initialize a new one
*/
ServerTelemetryManager.prototype.getLastRequests = function () {
var initialValue = new ServerTelemetryEntity();
var lastRequests = this.cacheManager.getServerTelemetry(this.telemetryCacheKey);
getLastRequests() {
const initialValue = new ServerTelemetryEntity();
const lastRequests = this.cacheManager.getServerTelemetry(this.telemetryCacheKey);
return lastRequests || initialValue;
};
}
/**
* Remove server telemetry cache entry
*/
ServerTelemetryManager.prototype.clearTelemetryCache = function () {
var lastRequests = this.getLastRequests();
var numErrorsFlushed = ServerTelemetryManager.maxErrorsToSend(lastRequests);
var errorCount = lastRequests.errors.length;
clearTelemetryCache() {
const lastRequests = this.getLastRequests();
const numErrorsFlushed = ServerTelemetryManager.maxErrorsToSend(lastRequests);
const errorCount = lastRequests.errors.length;
if (numErrorsFlushed === errorCount) {

@@ -109,8 +140,10 @@ // All errors were sent on last request, clear Telemetry cache

// Partial data was flushed to server, construct a new telemetry cache item with errors that were not flushed
var serverTelemEntity = new ServerTelemetryEntity();
serverTelemEntity.failedRequests = lastRequests.failedRequests.slice(numErrorsFlushed * 2); // failedRequests contains 2 items for each error
serverTelemEntity.errors = lastRequests.errors.slice(numErrorsFlushed);
const serverTelemEntity = new ServerTelemetryEntity();
serverTelemEntity.failedRequests =
lastRequests.failedRequests.slice(numErrorsFlushed * 2); // failedRequests contains 2 items for each error
serverTelemEntity.errors =
lastRequests.errors.slice(numErrorsFlushed);
this.cacheManager.setServerTelemetry(this.telemetryCacheKey, serverTelemEntity);
}
};
}
/**

@@ -120,14 +153,20 @@ * Returns the maximum number of errors that can be flushed to the server in the next network request

*/
ServerTelemetryManager.maxErrorsToSend = function (serverTelemetryEntity) {
var i;
var maxErrors = 0;
var dataSize = 0;
var errorCount = serverTelemetryEntity.errors.length;
static maxErrorsToSend(serverTelemetryEntity) {
let i;
let maxErrors = 0;
let dataSize = 0;
const errorCount = serverTelemetryEntity.errors.length;
for (i = 0; i < errorCount; i++) {
// failedRequests parameter contains pairs of apiId and correlationId, multiply index by 2 to preserve pairs
var apiId = serverTelemetryEntity.failedRequests[2 * i] || Constants.EMPTY_STRING;
var correlationId = serverTelemetryEntity.failedRequests[2 * i + 1] || Constants.EMPTY_STRING;
var errorCode = serverTelemetryEntity.errors[i] || Constants.EMPTY_STRING;
const apiId = serverTelemetryEntity.failedRequests[2 * i] ||
Constants.EMPTY_STRING;
const correlationId = serverTelemetryEntity.failedRequests[2 * i + 1] ||
Constants.EMPTY_STRING;
const errorCode = serverTelemetryEntity.errors[i] || Constants.EMPTY_STRING;
// Count number of characters that would be added to header, each character is 1 byte. Add 3 at the end to account for separators
dataSize += apiId.toString().length + correlationId.toString().length + errorCode.length + 3;
dataSize +=
apiId.toString().length +
correlationId.toString().length +
errorCode.length +
3;
if (dataSize < SERVER_TELEM_CONSTANTS.MAX_LAST_HEADER_BYTES) {

@@ -142,3 +181,3 @@ // Adding this entry to the header would still keep header size below the limit

return maxErrors;
};
}
/**

@@ -149,4 +188,4 @@ * Get the region discovery fields

*/
ServerTelemetryManager.prototype.getRegionDiscoveryFields = function () {
var regionDiscoveryFields = [];
getRegionDiscoveryFields() {
const regionDiscoveryFields = [];
regionDiscoveryFields.push(this.regionUsed || Constants.EMPTY_STRING);

@@ -156,3 +195,3 @@ regionDiscoveryFields.push(this.regionSource || Constants.EMPTY_STRING);

return regionDiscoveryFields.join(",");
};
}
/**

@@ -164,17 +203,16 @@ * Update the region discovery metadata

*/
ServerTelemetryManager.prototype.updateRegionDiscoveryMetadata = function (regionDiscoveryMetadata) {
updateRegionDiscoveryMetadata(regionDiscoveryMetadata) {
this.regionUsed = regionDiscoveryMetadata.region_used;
this.regionSource = regionDiscoveryMetadata.region_source;
this.regionOutcome = regionDiscoveryMetadata.region_outcome;
};
}
/**
* Set cache outcome
*/
ServerTelemetryManager.prototype.setCacheOutcome = function (cacheOutcome) {
setCacheOutcome(cacheOutcome) {
this.cacheOutcome = cacheOutcome;
};
return ServerTelemetryManager;
}());
}
}
export { ServerTelemetryManager };
//# sourceMappingURL=ServerTelemetryManager.js.map

@@ -1,2 +0,2 @@

export declare type ServerTelemetryRequest = {
export type ServerTelemetryRequest = {
clientId: string;

@@ -3,0 +3,0 @@ apiId: number;

@@ -1,2 +0,2 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';

@@ -15,4 +15,7 @@ import { ClientConfigurationError } from '../error/ClientConfigurationError.js';

*/
var UrlString = /** @class */ (function () {
function UrlString(url) {
class UrlString {
get urlString() {
return this._urlString;
}
constructor(url) {
this._urlString = url;

@@ -27,9 +30,2 @@ if (StringUtils.isEmpty(this._urlString)) {

}
Object.defineProperty(UrlString.prototype, "urlString", {
get: function () {
return this._urlString;
},
enumerable: false,
configurable: true
});
/**

@@ -39,5 +35,5 @@ * Ensure urls are lower case and end with a / character.

*/
UrlString.canonicalizeUri = function (url) {
static canonicalizeUri(url) {
if (url) {
var lowerCaseUrl = url.toLowerCase();
let lowerCaseUrl = url.toLowerCase();
if (StringUtils.endsWith(lowerCaseUrl, "?")) {

@@ -55,9 +51,9 @@ lowerCaseUrl = lowerCaseUrl.slice(0, -1);

return url;
};
}
/**
* Throws if urlString passed is not a valid authority URI string.
*/
UrlString.prototype.validateAsUri = function () {
validateAsUri() {
// Attempts to parse url for uri components
var components;
let components;
try {

@@ -71,9 +67,10 @@ components = this.getUrlComponents();

if (!components.HostNameAndPort || !components.PathSegments) {
throw ClientConfigurationError.createUrlParseError("Given url string: " + this.urlString);
throw ClientConfigurationError.createUrlParseError(`Given url string: ${this.urlString}`);
}
// Throw error if uri is insecure.
if (!components.Protocol || components.Protocol.toLowerCase() !== "https:") {
if (!components.Protocol ||
components.Protocol.toLowerCase() !== "https:") {
throw ClientConfigurationError.createInsecureAuthorityUriError(this.urlString);
}
};
}
/**

@@ -84,8 +81,10 @@ * Given a url and a query string return the url with provided query string appended

*/
UrlString.appendQueryString = function (url, queryString) {
static appendQueryString(url, queryString) {
if (StringUtils.isEmpty(queryString)) {
return url;
}
return url.indexOf("?") < 0 ? url + "?" + queryString : url + "&" + queryString;
};
return url.indexOf("?") < 0
? `${url}?${queryString}`
: `${url}&${queryString}`;
}
/**

@@ -95,5 +94,5 @@ * Returns a url with the hash removed

*/
UrlString.removeHashFromUrl = function (url) {
static removeHashFromUrl(url) {
return UrlString.canonicalizeUri(url.split("#")[0]);
};
}
/**

@@ -104,16 +103,19 @@ * Given a url like https://a:b/common/d?e=f#g, and a tenantId, returns https://a:b/tenantId/d

*/
UrlString.prototype.replaceTenantPath = function (tenantId) {
var urlObject = this.getUrlComponents();
var pathArray = urlObject.PathSegments;
if (tenantId && (pathArray.length !== 0 && (pathArray[0] === AADAuthorityConstants.COMMON || pathArray[0] === AADAuthorityConstants.ORGANIZATIONS))) {
replaceTenantPath(tenantId) {
const urlObject = this.getUrlComponents();
const pathArray = urlObject.PathSegments;
if (tenantId &&
pathArray.length !== 0 &&
(pathArray[0] === AADAuthorityConstants.COMMON ||
pathArray[0] === AADAuthorityConstants.ORGANIZATIONS)) {
pathArray[0] = tenantId;
}
return UrlString.constructAuthorityUriFromObject(urlObject);
};
}
/**
* Returns the anchor part(#) of the URL
*/
UrlString.prototype.getHash = function () {
getHash() {
return UrlString.parseHash(this.urlString);
};
}
/**

@@ -123,41 +125,45 @@ * Parses out the components from a url string.

*/
UrlString.prototype.getUrlComponents = function () {
getUrlComponents() {
// https://gist.github.com/curtisz/11139b2cfcaef4a261e0
var regEx = RegExp("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?");
const regEx = RegExp("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?");
// If url string does not match regEx, we throw an error
var match = this.urlString.match(regEx);
const match = this.urlString.match(regEx);
if (!match) {
throw ClientConfigurationError.createUrlParseError("Given url string: " + this.urlString);
throw ClientConfigurationError.createUrlParseError(`Given url string: ${this.urlString}`);
}
// Url component object
var urlComponents = {
const urlComponents = {
Protocol: match[1],
HostNameAndPort: match[4],
AbsolutePath: match[5],
QueryString: match[7]
QueryString: match[7],
};
var pathSegments = urlComponents.AbsolutePath.split("/");
pathSegments = pathSegments.filter(function (val) { return val && val.length > 0; }); // remove empty elements
let pathSegments = urlComponents.AbsolutePath.split("/");
pathSegments = pathSegments.filter((val) => val && val.length > 0); // remove empty elements
urlComponents.PathSegments = pathSegments;
if (!StringUtils.isEmpty(urlComponents.QueryString) && urlComponents.QueryString.endsWith("/")) {
if (!StringUtils.isEmpty(urlComponents.QueryString) &&
urlComponents.QueryString.endsWith("/")) {
urlComponents.QueryString = urlComponents.QueryString.substring(0, urlComponents.QueryString.length - 1);
}
return urlComponents;
};
UrlString.getDomainFromUrl = function (url) {
var regEx = RegExp("^([^:/?#]+://)?([^/?#]*)");
var match = url.match(regEx);
}
static getDomainFromUrl(url) {
const regEx = RegExp("^([^:/?#]+://)?([^/?#]*)");
const match = url.match(regEx);
if (!match) {
throw ClientConfigurationError.createUrlParseError("Given url string: " + url);
throw ClientConfigurationError.createUrlParseError(`Given url string: ${url}`);
}
return match[2];
};
UrlString.getAbsoluteUrl = function (relativeUrl, baseUrl) {
}
static getAbsoluteUrl(relativeUrl, baseUrl) {
if (relativeUrl[0] === Constants.FORWARD_SLASH) {
var url = new UrlString(baseUrl);
var baseComponents = url.getUrlComponents();
return baseComponents.Protocol + "//" + baseComponents.HostNameAndPort + relativeUrl;
const url = new UrlString(baseUrl);
const baseComponents = url.getUrlComponents();
return (baseComponents.Protocol +
"//" +
baseComponents.HostNameAndPort +
relativeUrl);
}
return relativeUrl;
};
}
/**

@@ -167,5 +173,5 @@ * Parses hash string from given string. Returns empty string if no hash symbol is found.

*/
UrlString.parseHash = function (hashString) {
var hashIndex1 = hashString.indexOf("#");
var hashIndex2 = hashString.indexOf("#/");
static parseHash(hashString) {
const hashIndex1 = hashString.indexOf("#");
const hashIndex2 = hashString.indexOf("#/");
if (hashIndex2 > -1) {

@@ -178,3 +184,3 @@ return hashString.substring(hashIndex2 + 2);

return Constants.EMPTY_STRING;
};
}
/**

@@ -184,5 +190,5 @@ * Parses query string from given string. Returns empty string if no query symbol is found.

*/
UrlString.parseQueryString = function (queryString) {
var queryIndex1 = queryString.indexOf("?");
var queryIndex2 = queryString.indexOf("/?");
static parseQueryString(queryString) {
const queryIndex1 = queryString.indexOf("?");
const queryIndex2 = queryString.indexOf("/?");
if (queryIndex2 > -1) {

@@ -195,10 +201,14 @@ return queryString.substring(queryIndex2 + 2);

return Constants.EMPTY_STRING;
};
UrlString.constructAuthorityUriFromObject = function (urlObject) {
return new UrlString(urlObject.Protocol + "//" + urlObject.HostNameAndPort + "/" + urlObject.PathSegments.join("/"));
};
}
static constructAuthorityUriFromObject(urlObject) {
return new UrlString(urlObject.Protocol +
"//" +
urlObject.HostNameAndPort +
"/" +
urlObject.PathSegments.join("/"));
}
/**
* Returns URL hash as server auth code response object.
*/
UrlString.getDeserializedHash = function (hash) {
static getDeserializedHash(hash) {
// Check if given hash is empty

@@ -209,5 +219,5 @@ if (StringUtils.isEmpty(hash)) {

// Strip the # symbol if present
var parsedHash = UrlString.parseHash(hash);
const parsedHash = UrlString.parseHash(hash);
// If # symbol was not present, above will return empty string, so give original hash value
var deserializedHash = StringUtils.queryStringToObject(StringUtils.isEmpty(parsedHash) ? hash : parsedHash);
const deserializedHash = StringUtils.queryStringToObject(StringUtils.isEmpty(parsedHash) ? hash : parsedHash);
// Check if deserialization didn't work

@@ -218,7 +228,7 @@ if (!deserializedHash) {

return deserializedHash;
};
}
/**
* Returns URL query string as server auth code response object.
*/
UrlString.getDeserializedQueryString = function (query) {
static getDeserializedQueryString(query) {
// Check if given query is empty

@@ -229,5 +239,7 @@ if (StringUtils.isEmpty(query)) {

// Strip the ? symbol if present
var parsedQueryString = UrlString.parseQueryString(query);
const parsedQueryString = UrlString.parseQueryString(query);
// If ? symbol was not present, above will return empty string, so give original query value
var deserializedQueryString = StringUtils.queryStringToObject(StringUtils.isEmpty(parsedQueryString) ? query : parsedQueryString);
const deserializedQueryString = StringUtils.queryStringToObject(StringUtils.isEmpty(parsedQueryString)
? query
: parsedQueryString);
// Check if deserialization didn't work

@@ -238,7 +250,7 @@ if (!deserializedQueryString) {

return deserializedQueryString;
};
}
/**
* Check if the hash of the URL string contains known properties
*/
UrlString.hashContainsKnownProperties = function (hash) {
static hashContainsKnownProperties(hash) {
if (StringUtils.isEmpty(hash) || hash.indexOf("=") < 0) {

@@ -248,3 +260,3 @@ // Hash doesn't contain key/value pairs

}
var parameters = UrlString.getDeserializedHash(hash);
const parameters = UrlString.getDeserializedHash(hash);
return !!(parameters.code ||

@@ -254,7 +266,6 @@ parameters.error_description ||

parameters.state);
};
return UrlString;
}());
}
}
export { UrlString };
//# sourceMappingURL=UrlString.js.map

@@ -1,5 +0,3 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';
import { __spreadArrays } from '../_virtual/_tslib.js';
/*

@@ -9,3 +7,3 @@ * Copyright (c) Microsoft Corporation. All rights reserved.

*/
var Constants = {
const Constants = {
LIBRARY_NAME: "MSAL.JS",

@@ -58,3 +56,8 @@ SKU: "msal.js.common",

REGIONAL_AUTH_NON_MSI_QUERY_STRING: "allowestsrnonmsi=true",
KNOWN_PUBLIC_CLOUDS: ["login.microsoftonline.com", "login.windows.net", "login.microsoft.com", "sts.windows.net"],
KNOWN_PUBLIC_CLOUDS: [
"login.microsoftonline.com",
"login.windows.net",
"login.microsoft.com",
"sts.windows.net",
],
TOKEN_RESPONSE_TYPE: "token",

@@ -65,10 +68,8 @@ ID_TOKEN_RESPONSE_TYPE: "id_token",

};
var OIDC_DEFAULT_SCOPES = [
const OIDC_DEFAULT_SCOPES = [
Constants.OPENID_SCOPE,
Constants.PROFILE_SCOPE,
Constants.OFFLINE_ACCESS_SCOPE
Constants.OFFLINE_ACCESS_SCOPE,
];
var OIDC_SCOPES = __spreadArrays(OIDC_DEFAULT_SCOPES, [
Constants.EMAIL_SCOPE
]);
const OIDC_SCOPES = [...OIDC_DEFAULT_SCOPES, Constants.EMAIL_SCOPE];
/**

@@ -98,3 +99,3 @@ * Request header names

PersistentCacheKeys["ACTIVE_ACCOUNT"] = "active-account";
PersistentCacheKeys["ACTIVE_ACCOUNT_FILTERS"] = "active-account-filters"; // new cache entry for active_account for a more robust version for browser
PersistentCacheKeys["ACTIVE_ACCOUNT_FILTERS"] = "active-account-filters";
})(PersistentCacheKeys || (PersistentCacheKeys = {}));

@@ -177,3 +178,3 @@ /**

*/
var PromptValue = {
const PromptValue = {
LOGIN: "login",

@@ -184,3 +185,3 @@ SELECT_ACCOUNT: "select_account",

CREATE: "create",
NO_SESSION: "no_session"
NO_SESSION: "no_session",
};

@@ -205,5 +206,5 @@ /**

*/
var CodeChallengeMethodValues = {
const CodeChallengeMethodValues = {
PLAIN: "plain",
S256: "S256"
S256: "S256",
};

@@ -240,3 +241,3 @@ /**

CacheAccountType["MSAV1_ACCOUNT_TYPE"] = "MSA";
CacheAccountType["GENERIC_ACCOUNT_TYPE"] = "Generic"; // NTLM, Kerberos, FBA, Basic etc
CacheAccountType["GENERIC_ACCOUNT_TYPE"] = "Generic";
})(CacheAccountType || (CacheAccountType = {}));

@@ -279,8 +280,8 @@ /**

*/
var APP_METADATA = "appmetadata";
var CLIENT_INFO = "client_info";
var THE_FAMILY_ID = "1";
var AUTHORITY_METADATA_CONSTANTS = {
const APP_METADATA = "appmetadata";
const CLIENT_INFO = "client_info";
const THE_FAMILY_ID = "1";
const AUTHORITY_METADATA_CONSTANTS = {
CACHE_KEY: "authority-metadata",
REFRESH_TIME_SECONDS: 3600 * 24 // 24 Hours
REFRESH_TIME_SECONDS: 3600 * 24, // 24 Hours
};

@@ -294,3 +295,3 @@ var AuthorityMetadataSource;

})(AuthorityMetadataSource || (AuthorityMetadataSource = {}));
var SERVER_TELEM_CONSTANTS = {
const SERVER_TELEM_CONSTANTS = {
SCHEMA_VERSION: 5,

@@ -305,3 +306,3 @@ MAX_CUR_HEADER_BYTES: 80,

OVERFLOW_FALSE: "0",
UNKNOWN_ERROR: "unknown_error"
UNKNOWN_ERROR: "unknown_error",
};

@@ -320,3 +321,3 @@ /**

*/
var ThrottlingConstants = {
const ThrottlingConstants = {
// Default time to throttle RequestThumbprint in seconds

@@ -329,5 +330,5 @@ DEFAULT_THROTTLE_TIME_SECONDS: 60,

// Value assigned to the x-ms-lib-capability header to indicate to the server the library supports throttling
X_MS_LIB_CAPABILITY_VALUE: "retry-after, h429"
X_MS_LIB_CAPABILITY_VALUE: "retry-after, h429",
};
var Errors = {
const Errors = {
INVALID_GRANT_ERROR: "invalid_grant",

@@ -387,5 +388,5 @@ CLIENT_MISMATCH_ERROR: "client_mismatch",

})(JsonTypes || (JsonTypes = {}));
var ONE_DAY_IN_MS = 86400000;
const ONE_DAY_IN_MS = 86400000;
export { AADAuthorityConstants, AADServerParamKeys, APP_METADATA, AUTHORITY_METADATA_CONSTANTS, AuthenticationScheme, AuthorityMetadataSource, CLIENT_INFO, CacheAccountType, CacheOutcome, CacheType, ClaimsRequestKeys, CodeChallengeMethodValues, Constants, CredentialType, Errors, GrantType, HeaderNames, JsonTypes, OIDC_DEFAULT_SCOPES, OIDC_SCOPES, ONE_DAY_IN_MS, PasswordGrantConstants, PersistentCacheKeys, PromptValue, RegionDiscoveryOutcomes, RegionDiscoverySources, ResponseCodes, ResponseMode, SERVER_TELEM_CONSTANTS, SSOTypes, Separators, THE_FAMILY_ID, ThrottlingConstants };
//# sourceMappingURL=Constants.js.map
/**
* Key-Value type to support queryParams, extraQueryParams and claims
*/
export declare type StringDict = {
export type StringDict = {
[key: string]: string;
};
//# sourceMappingURL=MsalTypes.d.ts.map

@@ -9,3 +9,3 @@ import { ICrypto } from "../crypto/ICrypto";

*/
export declare type LibraryStateObject = {
export type LibraryStateObject = {
id: string;

@@ -17,3 +17,3 @@ meta?: Record<string, string>;

*/
export declare type RequestStateObject = {
export type RequestStateObject = {
userRequestState: string;

@@ -20,0 +20,0 @@ libraryState: LibraryStateObject;

@@ -1,2 +0,2 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';

@@ -14,5 +14,3 @@ import { StringUtils } from './StringUtils.js';

*/
var ProtocolUtils = /** @class */ (function () {
function ProtocolUtils() {
}
class ProtocolUtils {
/**

@@ -23,6 +21,8 @@ * Appends user state with random guid, or returns random guid.

*/
ProtocolUtils.setRequestState = function (cryptoObj, userState, meta) {
var libraryState = ProtocolUtils.generateLibraryState(cryptoObj, meta);
return !StringUtils.isEmpty(userState) ? "" + libraryState + Constants.RESOURCE_DELIM + userState : libraryState;
};
static setRequestState(cryptoObj, userState, meta) {
const libraryState = ProtocolUtils.generateLibraryState(cryptoObj, meta);
return !StringUtils.isEmpty(userState)
? `${libraryState}${Constants.RESOURCE_DELIM}${userState}`
: libraryState;
}
/**

@@ -33,3 +33,3 @@ * Generates the state value used by the common library.

*/
ProtocolUtils.generateLibraryState = function (cryptoObj, meta) {
static generateLibraryState(cryptoObj, meta) {
if (!cryptoObj) {

@@ -39,4 +39,4 @@ throw ClientAuthError.createNoCryptoObjectError("generateLibraryState");

// Create a state object containing a unique id and the timestamp of the request creation
var stateObj = {
id: cryptoObj.createNewGuid()
const stateObj = {
id: cryptoObj.createNewGuid(),
};

@@ -46,5 +46,5 @@ if (meta) {

}
var stateString = JSON.stringify(stateObj);
const stateString = JSON.stringify(stateObj);
return cryptoObj.base64Encode(stateString);
};
}
/**

@@ -55,3 +55,3 @@ * Parses the state into the RequestStateObject, which contains the LibraryState info and the state passed by the user.

*/
ProtocolUtils.parseRequestState = function (cryptoObj, state) {
static parseRequestState(cryptoObj, state) {
if (!cryptoObj) {

@@ -65,10 +65,14 @@ throw ClientAuthError.createNoCryptoObjectError("parseRequestState");

// Split the state between library state and user passed state and decode them separately
var splitState = state.split(Constants.RESOURCE_DELIM);
var libraryState = splitState[0];
var userState = splitState.length > 1 ? splitState.slice(1).join(Constants.RESOURCE_DELIM) : Constants.EMPTY_STRING;
var libraryStateString = cryptoObj.base64Decode(libraryState);
var libraryStateObj = JSON.parse(libraryStateString);
const splitState = state.split(Constants.RESOURCE_DELIM);
const libraryState = splitState[0];
const userState = splitState.length > 1
? splitState.slice(1).join(Constants.RESOURCE_DELIM)
: Constants.EMPTY_STRING;
const libraryStateString = cryptoObj.base64Decode(libraryState);
const libraryStateObj = JSON.parse(libraryStateString);
return {
userRequestState: !StringUtils.isEmpty(userState) ? userState : Constants.EMPTY_STRING,
libraryState: libraryStateObj
userRequestState: !StringUtils.isEmpty(userState)
? userState
: Constants.EMPTY_STRING,
libraryState: libraryStateObj,
};

@@ -79,7 +83,6 @@ }

}
};
return ProtocolUtils;
}());
}
}
export { ProtocolUtils };
//# sourceMappingURL=ProtocolUtils.js.map

@@ -1,2 +0,2 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';

@@ -12,5 +12,3 @@ import { ClientAuthError } from '../error/ClientAuthError.js';

*/
var StringUtils = /** @class */ (function () {
function StringUtils() {
}
class StringUtils {
/**

@@ -21,18 +19,18 @@ * decode a JWT

*/
StringUtils.decodeAuthToken = function (authToken) {
static decodeAuthToken(authToken) {
if (StringUtils.isEmpty(authToken)) {
throw ClientAuthError.createTokenNullOrEmptyError(authToken);
}
var tokenPartsRegex = /^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/;
var matches = tokenPartsRegex.exec(authToken);
const tokenPartsRegex = /^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/;
const matches = tokenPartsRegex.exec(authToken);
if (!matches || matches.length < 4) {
throw ClientAuthError.createTokenParsingError("Given token is malformed: " + JSON.stringify(authToken));
throw ClientAuthError.createTokenParsingError(`Given token is malformed: ${JSON.stringify(authToken)}`);
}
var crackedToken = {
const crackedToken = {
header: matches[1],
JWSPayload: matches[2],
JWSSig: matches[3]
JWSSig: matches[3],
};
return crackedToken;
};
}
/**

@@ -43,5 +41,5 @@ * Check if a string is empty.

*/
StringUtils.isEmpty = function (str) {
return (typeof str === "undefined" || !str || 0 === str.length);
};
static isEmpty(str) {
return typeof str === "undefined" || !str || 0 === str.length;
}
/**

@@ -51,6 +49,6 @@ * Check if stringified object is empty

*/
StringUtils.isEmptyObj = function (strObj) {
static isEmptyObj(strObj) {
if (strObj && !StringUtils.isEmpty(strObj)) {
try {
var obj = JSON.parse(strObj);
const obj = JSON.parse(strObj);
return Object.keys(obj).length === 0;

@@ -61,9 +59,10 @@ }

return true;
};
StringUtils.startsWith = function (str, search) {
}
static startsWith(str, search) {
return str.indexOf(search) === 0;
};
StringUtils.endsWith = function (str, search) {
return (str.length >= search.length) && (str.lastIndexOf(search) === (str.length - search.length));
};
}
static endsWith(str, search) {
return (str.length >= search.length &&
str.lastIndexOf(search) === str.length - search.length);
}
/**

@@ -74,9 +73,9 @@ * Parses string into an object.

*/
StringUtils.queryStringToObject = function (query) {
var obj = {};
var params = query.split("&");
var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
params.forEach(function (pair) {
static queryStringToObject(query) {
const obj = {};
const params = query.split("&");
const decode = (s) => decodeURIComponent(s.replace(/\+/g, " "));
params.forEach((pair) => {
if (pair.trim()) {
var _a = pair.split(/=(.+)/g, 2), key = _a[0], value = _a[1]; // Split on the first occurence of the '=' character
const [key, value] = pair.split(/=(.+)/g, 2); // Split on the first occurence of the '=' character
if (key && value) {

@@ -88,3 +87,3 @@ obj[decode(key)] = decode(value);

return obj;
};
}
/**

@@ -95,5 +94,5 @@ * Trims entries in an array.

*/
StringUtils.trimArrayEntries = function (arr) {
return arr.map(function (entry) { return entry.trim(); });
};
static trimArrayEntries(arr) {
return arr.map((entry) => entry.trim());
}
/**

@@ -103,7 +102,7 @@ * Removes empty strings from array

*/
StringUtils.removeEmptyStringsFromArray = function (arr) {
return arr.filter(function (entry) {
static removeEmptyStringsFromArray(arr) {
return arr.filter((entry) => {
return !StringUtils.isEmpty(entry);
});
};
}
/**

@@ -113,3 +112,3 @@ * Attempts to parse a string into JSON

*/
StringUtils.jsonParseHelper = function (str) {
static jsonParseHelper(str) {
try {

@@ -121,3 +120,3 @@ return JSON.parse(str);

}
};
}
/**

@@ -128,3 +127,3 @@ * Tests if a given string matches a given pattern, with support for wildcards and queries.

*/
StringUtils.matchPattern = function (pattern, input) {
static matchPattern(pattern, input) {
/**

@@ -134,9 +133,12 @@ * Wildcard support: https://stackoverflow.com/a/3117248/4888559

*/
var regex = new RegExp(pattern.replace(/\\/g, "\\\\").replace(/\*/g, "[^ ]*").replace(/\?/g, "\\\?")); // eslint-disable-line security/detect-non-literal-regexp
// eslint-disable-next-line security/detect-non-literal-regexp
const regex = new RegExp(pattern
.replace(/\\/g, "\\\\")
.replace(/\*/g, "[^ ]*")
.replace(/\?/g, "\\?"));
return regex.test(input);
};
return StringUtils;
}());
}
}
export { StringUtils };
//# sourceMappingURL=StringUtils.js.map

@@ -1,2 +0,2 @@

/*! @azure/msal-common v13.0.0 2023-05-01 */
/*! @azure/msal-common v14.0.0-alpha.1 2023-05-08 */
'use strict';

@@ -10,12 +10,10 @@ /*

*/
var TimeUtils = /** @class */ (function () {
function TimeUtils() {
}
class TimeUtils {
/**
* return the current time in Unix time (seconds).
*/
TimeUtils.nowSeconds = function () {
static nowSeconds() {
// Date.getTime() returns in milliseconds.
return Math.round(new Date().getTime() / 1000.0);
};
}
/**

@@ -25,9 +23,9 @@ * check if a token is expired based on given UTC time in seconds.

*/
TimeUtils.isTokenExpired = function (expiresOn, offset) {
static isTokenExpired(expiresOn, offset) {
// check for access token expiry
var expirationSec = Number(expiresOn) || 0;
var offsetCurrentTimeSec = TimeUtils.nowSeconds() + offset;
const expirationSec = Number(expiresOn) || 0;
const offsetCurrentTimeSec = TimeUtils.nowSeconds() + offset;
// If current time + offset is greater than token expiration time, then token is expired.
return (offsetCurrentTimeSec > expirationSec);
};
return offsetCurrentTimeSec > expirationSec;
}
/**

@@ -39,6 +37,6 @@ * If the current time is earlier than the time that a token was cached at, we must discard the token

*/
TimeUtils.wasClockTurnedBack = function (cachedAt) {
var cachedAtSec = Number(cachedAt);
static wasClockTurnedBack(cachedAt) {
const cachedAtSec = Number(cachedAt);
return cachedAtSec > TimeUtils.nowSeconds();
};
}
/**

@@ -49,9 +47,8 @@ * Waits for t number of milliseconds

*/
TimeUtils.delay = function (t, value) {
return new Promise(function (resolve) { return setTimeout(function () { return resolve(value); }, t); });
};
return TimeUtils;
}());
static delay(t, value) {
return new Promise((resolve) => setTimeout(() => resolve(value), t));
}
}
export { TimeUtils };
//# sourceMappingURL=TimeUtils.js.map

@@ -13,3 +13,3 @@ {

},
"version": "13.0.0",
"version": "14.0.0-alpha.1",
"description": "Microsoft Authentication Library for js",

@@ -46,8 +46,10 @@ "keywords": [

"test:coverage:only": "npm run clean:coverage && npm run test:coverage",
"build:modules": "rollup -c",
"build:modules:watch": "rollup -cw",
"build:modules": "rollup -c --strictDeprecations --bundleConfigAsCjs",
"build:modules:watch": "rollup -cw --bundleConfigAsCjs",
"build": "npm run clean && npm run build:modules",
"build:all": "npm run build",
"prepack": "npm run build",
"metadata:check": "npx ts-node scripts/metadata.ts"
"metadata:check": "npx ts-node scripts/metadata.ts",
"format:check": "npx prettier --ignore-path .gitignore --check src test",
"format:fix": "npx prettier --ignore-path .gitignore --write src test"
},

@@ -60,2 +62,3 @@ "devDependencies": {

"@babel/preset-typescript": "^7.7.2",
"@rollup/plugin-typescript": "^11.0.0",
"@types/debug": "^4.1.5",

@@ -68,5 +71,5 @@ "@types/jest": "^27.0.0",

"lodash": "^4.17.21",
"prettier": "2.8.7",
"rimraf": "^3.0.2",
"rollup": "^2.46.0",
"rollup-plugin-typescript2": "^0.29.0",
"rollup": "^3.14.0",
"shx": "^0.3.2",

@@ -77,5 +80,5 @@ "sinon": "^7.5.0",

"tslint": "^5.20.0",
"typescript": "^3.7.5",
"typescript": "^4.9.5",
"yargs": "^17.5.1"
}
}
}

@@ -0,0 +0,0 @@ # Microsoft Authentication Library for JavaScript (MSAL.js) Common Protocols Package

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc