@azure/msal-common 14.0.0-beta.0 → 14.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/dist/account/AccountInfo.d.ts +1 -0
  2. package/dist/account/AccountInfo.d.ts.map +1 -1
  3. package/dist/account/AuthToken.js +1 -1
  4. package/dist/account/CcsCredential.d.ts +1 -1
  5. package/dist/account/CcsCredential.d.ts.map +1 -1
  6. package/dist/account/CcsCredential.js +1 -1
  7. package/dist/account/ClientInfo.js +1 -1
  8. package/dist/authority/Authority.d.ts +7 -1
  9. package/dist/authority/Authority.d.ts.map +1 -1
  10. package/dist/authority/Authority.js +122 -76
  11. package/dist/authority/Authority.js.map +1 -1
  12. package/dist/authority/AuthorityFactory.d.ts.map +1 -1
  13. package/dist/authority/AuthorityFactory.js +1 -1
  14. package/dist/authority/AuthorityFactory.js.map +1 -1
  15. package/dist/authority/AuthorityMetadata.d.ts +1 -0
  16. package/dist/authority/AuthorityMetadata.d.ts.map +1 -1
  17. package/dist/authority/AuthorityMetadata.js +10 -2
  18. package/dist/authority/AuthorityMetadata.js.map +1 -1
  19. package/dist/authority/AuthorityOptions.d.ts +3 -1
  20. package/dist/authority/AuthorityOptions.d.ts.map +1 -1
  21. package/dist/authority/AuthorityOptions.js +3 -3
  22. package/dist/authority/AuthorityOptions.js.map +1 -1
  23. package/dist/authority/AuthorityType.d.ts +1 -1
  24. package/dist/authority/AuthorityType.d.ts.map +1 -1
  25. package/dist/authority/AuthorityType.js +2 -2
  26. package/dist/authority/CloudInstanceDiscoveryErrorResponse.js +1 -1
  27. package/dist/authority/CloudInstanceDiscoveryResponse.js +1 -1
  28. package/dist/authority/OIDCOptions.d.ts +9 -0
  29. package/dist/authority/OIDCOptions.d.ts.map +1 -0
  30. package/dist/authority/OpenIdConfigResponse.js +1 -1
  31. package/dist/authority/ProtocolMode.d.ts +1 -1
  32. package/dist/authority/ProtocolMode.d.ts.map +1 -1
  33. package/dist/authority/ProtocolMode.js +1 -1
  34. package/dist/authority/RegionDiscovery.js +1 -1
  35. package/dist/cache/CacheManager.d.ts +2 -1
  36. package/dist/cache/CacheManager.d.ts.map +1 -1
  37. package/dist/cache/CacheManager.js +6 -5
  38. package/dist/cache/CacheManager.js.map +1 -1
  39. package/dist/cache/entities/AccessTokenEntity.js +1 -1
  40. package/dist/cache/entities/AccountEntity.d.ts +18 -17
  41. package/dist/cache/entities/AccountEntity.d.ts.map +1 -1
  42. package/dist/cache/entities/AccountEntity.js +60 -87
  43. package/dist/cache/entities/AccountEntity.js.map +1 -1
  44. package/dist/cache/entities/AppMetadataEntity.js +1 -1
  45. package/dist/cache/entities/AuthorityMetadataEntity.js +1 -1
  46. package/dist/cache/entities/CacheRecord.js +1 -1
  47. package/dist/cache/entities/CredentialEntity.js +1 -1
  48. package/dist/cache/entities/IdTokenEntity.js +1 -1
  49. package/dist/cache/entities/RefreshTokenEntity.js +1 -1
  50. package/dist/cache/entities/ServerTelemetryEntity.js +1 -1
  51. package/dist/cache/entities/ThrottlingEntity.js +1 -1
  52. package/dist/cache/interface/ICacheManager.d.ts +2 -1
  53. package/dist/cache/interface/ICacheManager.d.ts.map +1 -1
  54. package/dist/cache/persistence/TokenCacheContext.js +1 -1
  55. package/dist/client/AuthorizationCodeClient.d.ts +1 -0
  56. package/dist/client/AuthorizationCodeClient.d.ts.map +1 -1
  57. package/dist/client/AuthorizationCodeClient.js +15 -12
  58. package/dist/client/AuthorizationCodeClient.js.map +1 -1
  59. package/dist/client/BaseClient.js +1 -1
  60. package/dist/client/RefreshTokenClient.d.ts.map +1 -1
  61. package/dist/client/RefreshTokenClient.js +14 -13
  62. package/dist/client/RefreshTokenClient.js.map +1 -1
  63. package/dist/client/SilentFlowClient.d.ts.map +1 -1
  64. package/dist/client/SilentFlowClient.js +8 -1
  65. package/dist/client/SilentFlowClient.js.map +1 -1
  66. package/dist/config/ClientConfiguration.d.ts +16 -1
  67. package/dist/config/ClientConfiguration.d.ts.map +1 -1
  68. package/dist/config/ClientConfiguration.js +15 -3
  69. package/dist/config/ClientConfiguration.js.map +1 -1
  70. package/dist/crypto/ICrypto.js +1 -1
  71. package/dist/crypto/JoseHeader.js +1 -1
  72. package/dist/crypto/PopTokenGenerator.d.ts +1 -1
  73. package/dist/crypto/PopTokenGenerator.d.ts.map +1 -1
  74. package/dist/crypto/PopTokenGenerator.js +1 -1
  75. package/dist/error/AuthError.js +1 -1
  76. package/dist/error/ClientAuthError.js +1 -1
  77. package/dist/error/ClientConfigurationError.d.ts +16 -0
  78. package/dist/error/ClientConfigurationError.d.ts.map +1 -1
  79. package/dist/error/ClientConfigurationError.js +24 -4
  80. package/dist/error/ClientConfigurationError.js.map +1 -1
  81. package/dist/error/InteractionRequiredAuthError.js +1 -1
  82. package/dist/error/JoseHeaderError.js +1 -1
  83. package/dist/error/ServerError.js +1 -1
  84. package/dist/index.cjs.js +421 -275
  85. package/dist/index.cjs.js.map +1 -1
  86. package/dist/index.d.ts +5 -3
  87. package/dist/index.d.ts.map +1 -1
  88. package/dist/index.js +2 -2
  89. package/dist/logger/Logger.js +1 -1
  90. package/dist/network/INetworkModule.js +1 -1
  91. package/dist/network/NetworkManager.js +1 -1
  92. package/dist/network/ThrottlingUtils.js +1 -1
  93. package/dist/packageMetadata.d.ts +1 -1
  94. package/dist/packageMetadata.d.ts.map +1 -1
  95. package/dist/packageMetadata.js +2 -2
  96. package/dist/request/AuthenticationHeaderParser.js +1 -1
  97. package/dist/request/BaseAuthRequest.d.ts +3 -0
  98. package/dist/request/BaseAuthRequest.d.ts.map +1 -1
  99. package/dist/request/RequestParameterBuilder.d.ts +1 -1
  100. package/dist/request/RequestParameterBuilder.d.ts.map +1 -1
  101. package/dist/request/RequestParameterBuilder.js +10 -4
  102. package/dist/request/RequestParameterBuilder.js.map +1 -1
  103. package/dist/request/RequestValidator.js +2 -2
  104. package/dist/request/RequestValidator.js.map +1 -1
  105. package/dist/request/ScopeSet.js +1 -1
  106. package/dist/request/StoreInCache.d.ts +9 -0
  107. package/dist/request/StoreInCache.d.ts.map +1 -0
  108. package/dist/response/ResponseHandler.d.ts +0 -7
  109. package/dist/response/ResponseHandler.d.ts.map +1 -1
  110. package/dist/response/ResponseHandler.js +28 -38
  111. package/dist/response/ResponseHandler.js.map +1 -1
  112. package/dist/telemetry/performance/IPerformanceClient.d.ts +16 -7
  113. package/dist/telemetry/performance/IPerformanceClient.d.ts.map +1 -1
  114. package/dist/telemetry/performance/PerformanceClient.d.ts +14 -12
  115. package/dist/telemetry/performance/PerformanceClient.d.ts.map +1 -1
  116. package/dist/telemetry/performance/PerformanceClient.js +25 -23
  117. package/dist/telemetry/performance/PerformanceClient.js.map +1 -1
  118. package/dist/telemetry/performance/PerformanceEvent.d.ts +80 -95
  119. package/dist/telemetry/performance/PerformanceEvent.d.ts.map +1 -1
  120. package/dist/telemetry/performance/PerformanceEvent.js +2 -1
  121. package/dist/telemetry/performance/PerformanceEvent.js.map +1 -1
  122. package/dist/telemetry/performance/StubPerformanceClient.d.ts +9 -0
  123. package/dist/telemetry/performance/StubPerformanceClient.d.ts.map +1 -1
  124. package/dist/telemetry/performance/StubPerformanceClient.js +40 -6
  125. package/dist/telemetry/performance/StubPerformanceClient.js.map +1 -1
  126. package/dist/telemetry/server/ServerTelemetryManager.js +1 -1
  127. package/dist/url/UrlString.d.ts +13 -0
  128. package/dist/url/UrlString.d.ts.map +1 -1
  129. package/dist/url/UrlString.js +41 -2
  130. package/dist/url/UrlString.js.map +1 -1
  131. package/dist/utils/Constants.d.ts +29 -21
  132. package/dist/utils/Constants.d.ts.map +1 -1
  133. package/dist/utils/Constants.js +10 -4
  134. package/dist/utils/Constants.js.map +1 -1
  135. package/dist/utils/ProtocolUtils.js +1 -1
  136. package/dist/utils/StringUtils.js +1 -1
  137. package/dist/utils/TimeUtils.js +1 -1
  138. package/package.json +18 -13
package/dist/index.cjs.js CHANGED
@@ -1,4 +1,4 @@
1
- /*! @azure/msal-common v14.0.0-beta.0 2023-06-19 */
1
+ /*! @azure/msal-common v14.0.0 2023-08-08 */
2
2
  'use strict';
3
3
  'use strict';
4
4
 
@@ -198,11 +198,17 @@ const CodeChallengeMethodValues = {
198
198
  S256: "S256",
199
199
  };
200
200
  /**
201
- * allowed values for response_mode
201
+ * allowed values for server response type
202
202
  */
203
- const ResponseMode = {
203
+ const ServerResponseType = {
204
204
  QUERY: "query",
205
205
  FRAGMENT: "fragment",
206
+ };
207
+ /**
208
+ * allowed values for response_mode
209
+ */
210
+ const ResponseMode = {
211
+ ...ServerResponseType,
206
212
  FORM_POST: "form_post",
207
213
  };
208
214
  /**
@@ -1296,7 +1302,7 @@ class Logger {
1296
1302
 
1297
1303
  /* eslint-disable header/header */
1298
1304
  const name = "@azure/msal-common";
1299
- const version = "14.0.0-beta.0";
1305
+ const version = "14.0.0";
1300
1306
 
1301
1307
  /*
1302
1308
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -1309,9 +1315,9 @@ const AzureCloudInstance = {
1309
1315
  AzurePublic: "https://login.microsoftonline.com",
1310
1316
  // Microsoft PPE
1311
1317
  AzurePpe: "https://login.windows-ppe.net",
1312
- // Microsoft Chinese national cloud
1318
+ // Microsoft Chinese national/regional cloud
1313
1319
  AzureChina: "https://login.chinacloudapi.cn",
1314
- // Microsoft German national cloud ("Black Forest")
1320
+ // Microsoft German national/regional cloud ("Black Forest")
1315
1321
  AzureGermany: "https://login.microsoftonline.de",
1316
1322
  // US Government cloud
1317
1323
  AzureUsGovernment: "https://login.microsoftonline.us",
@@ -1415,12 +1421,20 @@ const ClientConfigurationErrorMessage = {
1415
1421
  },
1416
1422
  invalidAuthenticationHeader: {
1417
1423
  code: "invalid_authentication_header",
1418
- desc: "Invalid authentication header provided"
1424
+ desc: "Invalid authentication header provided",
1425
+ },
1426
+ cannotSetOIDCOptions: {
1427
+ code: "cannot_set_OIDCOptions",
1428
+ desc: "Cannot set OIDCOptions parameter. Please change the protocol mode to OIDC or use a non-Microsoft authority.",
1429
+ },
1430
+ cannotAllowNativeBroker: {
1431
+ code: "cannot_allow_native_broker",
1432
+ desc: "Cannot set allowNativeBroker parameter to true when not in AAD protocol mode.",
1419
1433
  },
1420
1434
  authorityMismatch: {
1421
1435
  code: "authority_mismatch",
1422
- desc: "Authority mismatch error. Authority provided in login request or PublicClientApplication config does not match the environment of the provided account. Please use a matching account or make an interactive request to login to this authority."
1423
- }
1436
+ desc: "Authority mismatch error. Authority provided in login request or PublicClientApplication config does not match the environment of the provided account. Please use a matching account or make an interactive request to login to this authority.",
1437
+ },
1424
1438
  };
1425
1439
  /**
1426
1440
  * Error thrown when there is an error in configuration of the MSAL.js library.
@@ -1569,6 +1583,18 @@ class ClientConfigurationError extends ClientAuthError {
1569
1583
  static createInvalidAuthenticationHeaderError(invalidHeaderName, details) {
1570
1584
  return new ClientConfigurationError(ClientConfigurationErrorMessage.invalidAuthenticationHeader.code, `${ClientConfigurationErrorMessage.invalidAuthenticationHeader.desc}. Invalid header: ${invalidHeaderName}. Details: ${details}`);
1571
1585
  }
1586
+ /**
1587
+ * Throws error when provided non-default OIDCOptions when not in OIDC protocol mode
1588
+ */
1589
+ static createCannotSetOIDCOptionsError() {
1590
+ return new ClientConfigurationError(ClientConfigurationErrorMessage.cannotSetOIDCOptions.code, ClientConfigurationErrorMessage.cannotSetOIDCOptions.desc);
1591
+ }
1592
+ /**
1593
+ * Throws error when allowNativeBroker is set to true when not in AAD protocol mode
1594
+ */
1595
+ static createCannotAllowNativeBrokerError() {
1596
+ return new ClientConfigurationError(ClientConfigurationErrorMessage.cannotAllowNativeBroker.code, ClientConfigurationErrorMessage.cannotAllowNativeBroker.desc);
1597
+ }
1572
1598
  /**
1573
1599
  * Create an error when the authority provided in request does not match authority provided in account or MSAL.js configuration.
1574
1600
  */
@@ -1824,7 +1850,19 @@ const AuthorityType = {
1824
1850
  Default: 0,
1825
1851
  Adfs: 1,
1826
1852
  Dsts: 2,
1827
- Ciam: 3
1853
+ Ciam: 3,
1854
+ };
1855
+
1856
+ /*
1857
+ * Copyright (c) Microsoft Corporation. All rights reserved.
1858
+ * Licensed under the MIT License.
1859
+ */
1860
+ /**
1861
+ * Protocol modes supported by MSAL.
1862
+ */
1863
+ const ProtocolMode = {
1864
+ AAD: "AAD",
1865
+ OIDC: "OIDC",
1828
1866
  };
1829
1867
 
1830
1868
  /*
@@ -1847,7 +1885,6 @@ const AuthorityType = {
1847
1885
  * username: primary username that represents the user, usually corresponds to preferred_username in the v2 endpt
1848
1886
  * authorityType: Accounts authority type as a string
1849
1887
  * name: Full name for the account, including given name and family name,
1850
- * clientInfo: Full base64 encoded client info received from ESTS
1851
1888
  * lastModificationTime: last time this entity was modified in the cache
1852
1889
  * lastModificationApp:
1853
1890
  * idTokenClaims: Object containing claims parsed from ID token
@@ -1874,24 +1911,6 @@ class AccountEntity {
1874
1911
  localAccountId: this.localAccountId,
1875
1912
  });
1876
1913
  }
1877
- /**
1878
- * returns the type of the cache (in this case account)
1879
- */
1880
- generateType() {
1881
- switch (this.authorityType) {
1882
- case CacheAccountType.ADFS_ACCOUNT_TYPE:
1883
- return CacheType.ADFS;
1884
- case CacheAccountType.MSAV1_ACCOUNT_TYPE:
1885
- return CacheType.MSA;
1886
- case CacheAccountType.MSSTS_ACCOUNT_TYPE:
1887
- return CacheType.MSSTS;
1888
- case CacheAccountType.GENERIC_ACCOUNT_TYPE:
1889
- return CacheType.GENERIC;
1890
- default: {
1891
- throw ClientAuthError.createUnexpectedAccountTypeError();
1892
- }
1893
- }
1894
- }
1895
1914
  /**
1896
1915
  * Returns the AccountInfo interface for this account.
1897
1916
  */
@@ -1905,6 +1924,7 @@ class AccountEntity {
1905
1924
  name: this.name,
1906
1925
  idTokenClaims: this.idTokenClaims,
1907
1926
  nativeAccountId: this.nativeAccountId,
1927
+ authorityType: this.authorityType,
1908
1928
  };
1909
1929
  }
1910
1930
  /**
@@ -1921,84 +1941,74 @@ class AccountEntity {
1921
1941
  }
1922
1942
  /**
1923
1943
  * Build Account cache from IdToken, clientInfo and authority/policy. Associated with AAD.
1924
- * @param clientInfo
1925
- * @param authority
1926
- * @param idToken
1927
- * @param policy
1944
+ * @param accountDetails
1928
1945
  */
1929
- static createAccount(clientInfo, homeAccountId, idToken, authority, cloudGraphHostName, msGraphHost, environment, nativeAccountId) {
1946
+ static createAccount(accountDetails, authority) {
1930
1947
  const account = new AccountEntity();
1931
- account.authorityType = CacheAccountType.MSSTS_ACCOUNT_TYPE;
1932
- account.clientInfo = clientInfo;
1933
- account.homeAccountId = homeAccountId;
1934
- account.nativeAccountId = nativeAccountId;
1935
- const env = environment || (authority && authority.getPreferredCache());
1948
+ if (authority.authorityType === AuthorityType.Adfs) {
1949
+ account.authorityType = CacheAccountType.ADFS_ACCOUNT_TYPE;
1950
+ }
1951
+ else if (authority.protocolMode === ProtocolMode.AAD) {
1952
+ account.authorityType = CacheAccountType.MSSTS_ACCOUNT_TYPE;
1953
+ }
1954
+ else {
1955
+ account.authorityType = CacheAccountType.GENERIC_ACCOUNT_TYPE;
1956
+ }
1957
+ account.clientInfo = accountDetails.clientInfo;
1958
+ account.homeAccountId = accountDetails.homeAccountId;
1959
+ account.nativeAccountId = accountDetails.nativeAccountId;
1960
+ const env = accountDetails.environment ||
1961
+ (authority && authority.getPreferredCache());
1936
1962
  if (!env) {
1937
1963
  throw ClientAuthError.createInvalidCacheEnvironmentError();
1938
1964
  }
1939
1965
  account.environment = env;
1940
1966
  // non AAD scenarios can have empty realm
1941
- account.realm = idToken?.claims?.tid || Constants.EMPTY_STRING;
1942
- if (idToken) {
1943
- account.idTokenClaims = idToken.claims;
1944
- // How do you account for MSA CID here?
1945
- account.localAccountId =
1946
- idToken?.claims?.oid ||
1947
- idToken?.claims?.sub ||
1948
- Constants.EMPTY_STRING;
1949
- /*
1950
- * In B2C scenarios the emails claim is used instead of preferred_username and it is an array.
1951
- * In most cases it will contain a single email. This field should not be relied upon if a custom
1952
- * policy is configured to return more than 1 email.
1953
- */
1954
- const preferredUsername = idToken?.claims?.preferred_username;
1955
- const email = idToken?.claims?.emails
1956
- ? idToken.claims.emails[0]
1957
- : null;
1958
- account.username =
1959
- preferredUsername || email || Constants.EMPTY_STRING;
1960
- account.name = idToken?.claims?.name;
1961
- }
1962
- account.cloudGraphHostName = cloudGraphHostName;
1963
- account.msGraphHost = msGraphHost;
1967
+ account.realm =
1968
+ accountDetails.idTokenClaims.tid || Constants.EMPTY_STRING;
1969
+ account.idTokenClaims = accountDetails.idTokenClaims;
1970
+ // How do you account for MSA CID here?
1971
+ account.localAccountId =
1972
+ accountDetails.idTokenClaims.oid ||
1973
+ accountDetails.idTokenClaims.sub ||
1974
+ Constants.EMPTY_STRING;
1975
+ /*
1976
+ * In B2C scenarios the emails claim is used instead of preferred_username and it is an array.
1977
+ * In most cases it will contain a single email. This field should not be relied upon if a custom
1978
+ * policy is configured to return more than 1 email.
1979
+ */
1980
+ const preferredUsername = accountDetails.idTokenClaims.preferred_username ||
1981
+ accountDetails.idTokenClaims.upn;
1982
+ const email = accountDetails.idTokenClaims.emails
1983
+ ? accountDetails.idTokenClaims.emails[0]
1984
+ : null;
1985
+ account.username = preferredUsername || email || Constants.EMPTY_STRING;
1986
+ account.name = accountDetails.idTokenClaims.name;
1987
+ account.cloudGraphHostName = accountDetails.cloudGraphHostName;
1988
+ account.msGraphHost = accountDetails.msGraphHost;
1964
1989
  return account;
1965
1990
  }
1966
1991
  /**
1967
- * Builds non-AAD/ADFS account.
1968
- * @param authority
1969
- * @param idToken
1992
+ * Creates an AccountEntity object from AccountInfo
1993
+ * @param accountInfo
1994
+ * @param cloudGraphHostName
1995
+ * @param msGraphHost
1996
+ * @returns
1970
1997
  */
1971
- static createGenericAccount(homeAccountId, idToken, authority, cloudGraphHostName, msGraphHost, environment) {
1998
+ static createFromAccountInfo(accountInfo, cloudGraphHostName, msGraphHost) {
1972
1999
  const account = new AccountEntity();
1973
2000
  account.authorityType =
1974
- authority && authority.authorityType === AuthorityType.Adfs
1975
- ? CacheAccountType.ADFS_ACCOUNT_TYPE
1976
- : CacheAccountType.GENERIC_ACCOUNT_TYPE;
1977
- account.homeAccountId = homeAccountId;
1978
- // non AAD scenarios can have empty realm
1979
- account.realm = Constants.EMPTY_STRING;
1980
- const env = environment || (authority && authority.getPreferredCache());
1981
- if (!env) {
1982
- throw ClientAuthError.createInvalidCacheEnvironmentError();
1983
- }
1984
- if (idToken) {
1985
- // How do you account for MSA CID here?
1986
- account.localAccountId =
1987
- idToken?.claims?.oid ||
1988
- idToken?.claims?.sub ||
1989
- Constants.EMPTY_STRING;
1990
- // upn claim for most ADFS scenarios
1991
- account.username = idToken?.claims?.upn || Constants.EMPTY_STRING;
1992
- account.name = idToken?.claims?.name || Constants.EMPTY_STRING;
1993
- account.idTokenClaims = idToken?.claims;
1994
- }
1995
- account.environment = env;
2001
+ accountInfo.authorityType || CacheAccountType.GENERIC_ACCOUNT_TYPE;
2002
+ account.homeAccountId = accountInfo.homeAccountId;
2003
+ account.localAccountId = accountInfo.localAccountId;
2004
+ account.nativeAccountId = accountInfo.nativeAccountId;
2005
+ account.realm = accountInfo.tenantId;
2006
+ account.environment = accountInfo.environment;
2007
+ account.username = accountInfo.username;
2008
+ account.name = accountInfo.name;
2009
+ account.idTokenClaims = accountInfo.idTokenClaims;
1996
2010
  account.cloudGraphHostName = cloudGraphHostName;
1997
2011
  account.msGraphHost = msGraphHost;
1998
- /*
1999
- * add uniqueName to claims
2000
- * account.name = idToken.claims.uniqueName;
2001
- */
2002
2012
  return account;
2003
2013
  }
2004
2014
  /**
@@ -2006,9 +2016,9 @@ class AccountEntity {
2006
2016
  * @param serverClientInfo
2007
2017
  * @param authType
2008
2018
  */
2009
- static generateHomeAccountId(serverClientInfo, authType, logger, cryptoObj, idToken) {
2010
- const accountId = idToken?.claims?.sub
2011
- ? idToken.claims.sub
2019
+ static generateHomeAccountId(serverClientInfo, authType, logger, cryptoObj, idTokenClaims) {
2020
+ const accountId = idTokenClaims?.sub
2021
+ ? idTokenClaims.sub
2012
2022
  : Constants.EMPTY_STRING;
2013
2023
  // since ADFS does not have tid and does not set client_info
2014
2024
  if (authType === AuthorityType.Adfs ||
@@ -2189,20 +2199,21 @@ class CacheManager {
2189
2199
  * saves a cache record
2190
2200
  * @param cacheRecord
2191
2201
  */
2192
- async saveCacheRecord(cacheRecord) {
2202
+ async saveCacheRecord(cacheRecord, storeInCache) {
2193
2203
  if (!cacheRecord) {
2194
2204
  throw ClientAuthError.createNullOrUndefinedCacheRecord();
2195
2205
  }
2196
2206
  if (!!cacheRecord.account) {
2197
2207
  this.setAccount(cacheRecord.account);
2198
2208
  }
2199
- if (!!cacheRecord.idToken) {
2209
+ if (!!cacheRecord.idToken && storeInCache?.idToken !== false) {
2200
2210
  this.setIdTokenCredential(cacheRecord.idToken);
2201
2211
  }
2202
- if (!!cacheRecord.accessToken) {
2212
+ if (!!cacheRecord.accessToken && storeInCache?.accessToken !== false) {
2203
2213
  await this.saveAccessToken(cacheRecord.accessToken);
2204
2214
  }
2205
- if (!!cacheRecord.refreshToken) {
2215
+ if (!!cacheRecord.refreshToken &&
2216
+ storeInCache?.refreshToken !== false) {
2206
2217
  this.setRefreshTokenCredential(cacheRecord.refreshToken);
2207
2218
  }
2208
2219
  if (!!cacheRecord.appMetadata) {
@@ -3155,6 +3166,9 @@ const DEFAULT_LOGGER_IMPLEMENTATION = {
3155
3166
  logLevel: exports.LogLevel.Info,
3156
3167
  correlationId: Constants.EMPTY_STRING,
3157
3168
  };
3169
+ const DEFAULT_CACHE_OPTIONS = {
3170
+ claimsBasedCachingEnabled: false,
3171
+ };
3158
3172
  const DEFAULT_NETWORK_IMPLEMENTATION = {
3159
3173
  async sendGetRequestAsync() {
3160
3174
  const notImplErr = "Network interface - sendGetRequestAsync() has not been implemented";
@@ -3192,7 +3206,7 @@ const DEFAULT_TELEMETRY_OPTIONS = {
3192
3206
  *
3193
3207
  * @returns Configuration
3194
3208
  */
3195
- 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, }) {
3209
+ function buildClientConfiguration({ authOptions: userAuthOptions, systemOptions: userSystemOptions, loggerOptions: userLoggerOption, cacheOptions: userCacheOptions, storageInterface: storageImplementation, networkInterface: networkImplementation, cryptoInterface: cryptoImplementation, clientCredentials: clientCredentials, libraryInfo: libraryInfo, telemetry: telemetry, serverTelemetryManager: serverTelemetryManager, persistencePlugin: persistencePlugin, serializableCache: serializableCache, }) {
3196
3210
  const loggerOptions = {
3197
3211
  ...DEFAULT_LOGGER_IMPLEMENTATION,
3198
3212
  ...userLoggerOption,
@@ -3201,6 +3215,7 @@ function buildClientConfiguration({ authOptions: userAuthOptions, systemOptions:
3201
3215
  authOptions: buildAuthOptions(userAuthOptions),
3202
3216
  systemOptions: { ...DEFAULT_SYSTEM_OPTIONS, ...userSystemOptions },
3203
3217
  loggerOptions: loggerOptions,
3218
+ cacheOptions: { ...DEFAULT_CACHE_OPTIONS, ...userCacheOptions },
3204
3219
  storageInterface: storageImplementation ||
3205
3220
  new DefaultStorageClass(userAuthOptions.clientId, DEFAULT_CRYPTO_IMPLEMENTATION, new Logger(loggerOptions)),
3206
3221
  networkInterface: networkImplementation || DEFAULT_NETWORK_IMPLEMENTATION,
@@ -3225,6 +3240,13 @@ function buildAuthOptions(authOptions) {
3225
3240
  ...authOptions,
3226
3241
  };
3227
3242
  }
3243
+ /**
3244
+ * Returns true if config has protocolMode set to ProtocolMode.OIDC, false otherwise
3245
+ * @param ClientConfiguration
3246
+ */
3247
+ function isOidcProtocolMode(config) {
3248
+ return (config.authOptions.authority.options.protocolMode === ProtocolMode.OIDC);
3249
+ }
3228
3250
 
3229
3251
  /*
3230
3252
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -3458,7 +3480,7 @@ class RequestValidator {
3458
3480
  }
3459
3481
  });
3460
3482
  // remove empty string parameters
3461
- return Object.fromEntries(Object.entries(eQParams).filter(kv => kv[1] !== ""));
3483
+ return Object.fromEntries(Object.entries(eQParams).filter((kv) => kv[1] !== ""));
3462
3484
  }
3463
3485
  }
3464
3486
 
@@ -3500,9 +3522,15 @@ class RequestParameterBuilder {
3500
3522
  * @param scopeSet
3501
3523
  * @param addOidcScopes
3502
3524
  */
3503
- addScopes(scopes, addOidcScopes = true) {
3525
+ addScopes(scopes, addOidcScopes = true, defaultScopes = OIDC_DEFAULT_SCOPES) {
3526
+ // Always add openid to the scopes when adding OIDC scopes
3527
+ if (addOidcScopes &&
3528
+ !defaultScopes.includes("openid") &&
3529
+ !scopes.includes("openid")) {
3530
+ defaultScopes.push("openid");
3531
+ }
3504
3532
  const requestScopes = addOidcScopes
3505
- ? [...(scopes || []), ...OIDC_DEFAULT_SCOPES]
3533
+ ? [...(scopes || []), ...defaultScopes]
3506
3534
  : scopes || [];
3507
3535
  const scopeSet = new ScopeSet(requestScopes);
3508
3536
  this.parameters.set(AADServerParamKeys.SCOPE, encodeURIComponent(scopeSet.printScopes()));
@@ -4689,6 +4717,30 @@ class UrlString {
4689
4717
  }
4690
4718
  return Constants.EMPTY_STRING;
4691
4719
  }
4720
+ /**
4721
+ * Parses query server response string from given string.
4722
+ * Extract hash between '?code=' and '#' if trailing '# is present.
4723
+ * Returns empty string if no query symbol is found.
4724
+ * @param queryString
4725
+ */
4726
+ static parseQueryServerResponse(queryString) {
4727
+ const queryIndex1 = queryString.indexOf("?code");
4728
+ const queryIndex2 = queryString.indexOf("/?code");
4729
+ const hashIndex = queryString.indexOf("#");
4730
+ if (queryIndex2 > -1 && hashIndex > -1) {
4731
+ return queryString.substring(queryIndex2 + 2, hashIndex);
4732
+ }
4733
+ else if (queryIndex2 > -1) {
4734
+ return queryString.substring(queryIndex2 + 2);
4735
+ }
4736
+ else if (queryIndex1 > -1 && hashIndex > -1) {
4737
+ return queryString.substring(queryIndex1 + 1, hashIndex);
4738
+ }
4739
+ else if (queryIndex1 > -1) {
4740
+ return queryString.substring(queryIndex1 + 1);
4741
+ }
4742
+ return Constants.EMPTY_STRING;
4743
+ }
4692
4744
  static constructAuthorityUriFromObject(urlObject) {
4693
4745
  return new UrlString(urlObject.Protocol +
4694
4746
  "//" +
@@ -4734,6 +4786,21 @@ class UrlString {
4734
4786
  }
4735
4787
  return deserializedQueryString;
4736
4788
  }
4789
+ /**
4790
+ * Returns either deserialized query string or deserialized hash, depending on the serverResponseType
4791
+ * as a server auth code response object.
4792
+ */
4793
+ static getDeserializedCodeResponse(serverResponseType, hashFragment) {
4794
+ const hashUrlString = new UrlString(hashFragment);
4795
+ let serverParams;
4796
+ if (serverResponseType === ServerResponseType.QUERY) {
4797
+ serverParams = UrlString.getDeserializedQueryString(hashFragment);
4798
+ }
4799
+ else {
4800
+ serverParams = UrlString.getDeserializedHash(hashUrlString.getHash());
4801
+ }
4802
+ return serverParams;
4803
+ }
4737
4804
  /**
4738
4805
  * Check if the hash of the URL string contains known properties
4739
4806
  */
@@ -4952,6 +5019,7 @@ const PerformanceEvents = {
4952
5019
  UpdateCloudDiscoveryMetadataMeasurement: "updateCloudDiscoveryMetadataMeasurement",
4953
5020
  UsernamePasswordClientAcquireToken: "usernamePasswordClientAcquireToken",
4954
5021
  NativeMessageHandlerHandshake: "nativeMessageHandlerHandshake",
5022
+ NativeGenerateAuthResult: "nativeGenerateAuthResult",
4955
5023
  };
4956
5024
  /**
4957
5025
  * State of the performance event.
@@ -5177,12 +5245,25 @@ class ResponseHandler {
5177
5245
  */
5178
5246
  validateServerAuthorizationCodeResponse(serverResponseHash, cachedState, cryptoObj) {
5179
5247
  if (!serverResponseHash.state || !cachedState) {
5180
- throw !serverResponseHash.state
5181
- ? ClientAuthError.createStateNotFoundError("Server State")
5182
- : ClientAuthError.createStateNotFoundError("Cached State");
5248
+ throw serverResponseHash.state
5249
+ ? ClientAuthError.createStateNotFoundError("Cached State")
5250
+ : ClientAuthError.createStateNotFoundError("Server State");
5251
+ }
5252
+ let decodedServerResponseHash;
5253
+ let decodedCachedState;
5254
+ try {
5255
+ decodedServerResponseHash = decodeURIComponent(serverResponseHash.state);
5256
+ }
5257
+ catch (e) {
5258
+ throw ClientAuthError.createInvalidStateError(serverResponseHash.state, `Server response hash URI could not be decoded`);
5259
+ }
5260
+ try {
5261
+ decodedCachedState = decodeURIComponent(cachedState);
5262
+ }
5263
+ catch (e) {
5264
+ throw ClientAuthError.createInvalidStateError(serverResponseHash.state, `Cached state URI could not be decoded`);
5183
5265
  }
5184
- if (decodeURIComponent(serverResponseHash.state) !==
5185
- decodeURIComponent(cachedState)) {
5266
+ if (decodedServerResponseHash !== decodedCachedState) {
5186
5267
  throw ClientAuthError.createStateMismatchError();
5187
5268
  }
5188
5269
  // Check for error
@@ -5242,7 +5323,7 @@ class ResponseHandler {
5242
5323
  }
5243
5324
  }
5244
5325
  // generate homeAccountId
5245
- this.homeAccountIdentifier = AccountEntity.generateHomeAccountId(serverTokenResponse.client_info || Constants.EMPTY_STRING, authority.authorityType, this.logger, this.cryptoObj, idTokenObj);
5326
+ this.homeAccountIdentifier = AccountEntity.generateHomeAccountId(serverTokenResponse.client_info || Constants.EMPTY_STRING, authority.authorityType, this.logger, this.cryptoObj, idTokenObj?.claims);
5246
5327
  // save the response tokens
5247
5328
  let requestStateObj;
5248
5329
  if (!!authCodePayload && !!authCodePayload.state) {
@@ -5275,7 +5356,7 @@ class ResponseHandler {
5275
5356
  return ResponseHandler.generateAuthenticationResult(this.cryptoObj, authority, cacheRecord, false, request, idTokenObj, requestStateObj, undefined, serverRequestId);
5276
5357
  }
5277
5358
  }
5278
- await this.cacheStorage.saveCacheRecord(cacheRecord);
5359
+ await this.cacheStorage.saveCacheRecord(cacheRecord, request.storeInCache);
5279
5360
  }
5280
5361
  finally {
5281
5362
  if (this.persistencePlugin &&
@@ -5304,7 +5385,13 @@ class ResponseHandler {
5304
5385
  if (!StringUtils.isEmpty(serverTokenResponse.id_token) &&
5305
5386
  !!idTokenObj) {
5306
5387
  cachedIdToken = IdTokenEntity.createIdTokenEntity(this.homeAccountIdentifier, env, serverTokenResponse.id_token || Constants.EMPTY_STRING, this.clientId, idTokenObj.claims.tid || Constants.EMPTY_STRING);
5307
- cachedAccount = this.generateAccountEntity(serverTokenResponse, idTokenObj, authority, authCodePayload);
5388
+ cachedAccount = AccountEntity.createAccount({
5389
+ homeAccountId: this.homeAccountIdentifier,
5390
+ idTokenClaims: idTokenObj.claims,
5391
+ clientInfo: serverTokenResponse.client_info,
5392
+ cloudGraphHostName: authCodePayload?.cloud_graph_host_name,
5393
+ msGraphHost: authCodePayload?.msgraph_host,
5394
+ }, authority);
5308
5395
  }
5309
5396
  // AccessToken
5310
5397
  let cachedAccessToken = null;
@@ -5348,34 +5435,6 @@ class ResponseHandler {
5348
5435
  }
5349
5436
  return new CacheRecord(cachedAccount, cachedIdToken, cachedAccessToken, cachedRefreshToken, cachedAppMetadata);
5350
5437
  }
5351
- /**
5352
- * Generate Account
5353
- * @param serverTokenResponse
5354
- * @param idToken
5355
- * @param authority
5356
- */
5357
- generateAccountEntity(serverTokenResponse, idToken, authority, authCodePayload) {
5358
- const authorityType = authority.authorityType;
5359
- const cloudGraphHostName = authCodePayload
5360
- ? authCodePayload.cloud_graph_host_name
5361
- : Constants.EMPTY_STRING;
5362
- const msGraphhost = authCodePayload
5363
- ? authCodePayload.msgraph_host
5364
- : Constants.EMPTY_STRING;
5365
- // ADFS does not require client_info in the response
5366
- if (authorityType === AuthorityType.Adfs) {
5367
- this.logger.verbose("Authority type is ADFS, creating ADFS account");
5368
- return AccountEntity.createGenericAccount(this.homeAccountIdentifier, idToken, authority, cloudGraphHostName, msGraphhost);
5369
- }
5370
- // This fallback applies to B2C as well as they fall under an AAD account type.
5371
- if (StringUtils.isEmpty(serverTokenResponse.client_info) &&
5372
- authority.protocolMode === "AAD") {
5373
- throw ClientAuthError.createClientInfoEmptyError();
5374
- }
5375
- return serverTokenResponse.client_info
5376
- ? AccountEntity.createAccount(serverTokenResponse.client_info, this.homeAccountIdentifier, idToken, authority, cloudGraphHostName, msGraphhost)
5377
- : AccountEntity.createGenericAccount(this.homeAccountIdentifier, idToken, authority, cloudGraphHostName, msGraphhost);
5378
- }
5379
5438
  /**
5380
5439
  * Creates an @AuthenticationResult from @CacheRecord , @IdToken , and a boolean that states whether or not the result is from cache.
5381
5440
  *
@@ -5465,6 +5524,8 @@ class AuthorizationCodeClient extends BaseClient {
5465
5524
  super(configuration, performanceClient);
5466
5525
  // Flag to indicate if client is for hybrid spa auth code redemption
5467
5526
  this.includeRedirectUri = true;
5527
+ this.oidcDefaultScopes =
5528
+ this.config.authOptions.authority.options.OIDCOptions?.defaultScopes;
5468
5529
  }
5469
5530
  /**
5470
5531
  * Creates the URL of the authorization request letting the user input credentials and consent to the
@@ -5503,7 +5564,7 @@ class AuthorizationCodeClient extends BaseClient {
5503
5564
  const requestId = response.headers?.[HeaderNames.X_MS_REQUEST_ID];
5504
5565
  const httpVerAuthority = response.headers?.[HeaderNames.X_MS_HTTP_VERSION];
5505
5566
  if (httpVerAuthority) {
5506
- atsMeasurement?.addStaticFields({
5567
+ atsMeasurement?.add({
5507
5568
  httpVerAuthority,
5508
5569
  });
5509
5570
  }
@@ -5514,14 +5575,14 @@ class AuthorizationCodeClient extends BaseClient {
5514
5575
  return responseHandler
5515
5576
  .handleServerTokenResponse(response.body, this.authority, reqTimestamp, request, authCodePayload, undefined, undefined, undefined, requestId)
5516
5577
  .then((result) => {
5517
- atsMeasurement?.endMeasurement({
5578
+ atsMeasurement?.end({
5518
5579
  success: true,
5519
5580
  });
5520
5581
  return result;
5521
5582
  })
5522
5583
  .catch((error) => {
5523
5584
  this.logger.verbose("Error in fetching token in ACC", request.correlationId);
5524
- atsMeasurement?.endMeasurement({
5585
+ atsMeasurement?.end({
5525
5586
  errorCode: error.errorCode,
5526
5587
  subErrorCode: error.subError,
5527
5588
  success: false,
@@ -5537,10 +5598,8 @@ class AuthorizationCodeClient extends BaseClient {
5537
5598
  handleFragmentResponse(hashFragment, cachedState) {
5538
5599
  // Handle responses.
5539
5600
  const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, null, null);
5540
- // Deserialize hash fragment response parameters.
5541
- const hashUrlString = new UrlString(hashFragment);
5542
- // Deserialize hash fragment response parameters.
5543
- const serverParams = UrlString.getDeserializedHash(hashUrlString.getHash());
5601
+ const serverParams = UrlString.getDeserializedCodeResponse(this.config.authOptions.authority.options.OIDCOptions
5602
+ ?.serverResponseType, hashFragment);
5544
5603
  // Get code response
5545
5604
  responseHandler.validateServerAuthorizationCodeResponse(serverParams, cachedState, this.cryptoUtils);
5546
5605
  // throw when there is no auth code in the response
@@ -5626,14 +5685,14 @@ class AuthorizationCodeClient extends BaseClient {
5626
5685
  parameterBuilder.addRedirectUri(request.redirectUri);
5627
5686
  }
5628
5687
  // Add scope array, parameter builder will add default scopes and dedupe
5629
- parameterBuilder.addScopes(request.scopes);
5688
+ parameterBuilder.addScopes(request.scopes, true, this.oidcDefaultScopes);
5630
5689
  // add code: user set, not validated
5631
5690
  parameterBuilder.addAuthorizationCode(request.code);
5632
5691
  // Add library metadata
5633
5692
  parameterBuilder.addLibraryInfo(this.config.libraryInfo);
5634
5693
  parameterBuilder.addApplicationTelemetry(this.config.telemetry.application);
5635
5694
  parameterBuilder.addThrottling();
5636
- if (this.serverTelemetryManager) {
5695
+ if (this.serverTelemetryManager && !isOidcProtocolMode(this.config)) {
5637
5696
  parameterBuilder.addServerTelemetry(this.serverTelemetryManager);
5638
5697
  }
5639
5698
  // add code_verifier if passed
@@ -5732,7 +5791,7 @@ class AuthorizationCodeClient extends BaseClient {
5732
5791
  ...(request.scopes || []),
5733
5792
  ...(request.extraScopesToConsent || []),
5734
5793
  ];
5735
- parameterBuilder.addScopes(requestScopes);
5794
+ parameterBuilder.addScopes(requestScopes, true, this.oidcDefaultScopes);
5736
5795
  // validate the redirectUri (to be a non null value)
5737
5796
  parameterBuilder.addRedirectUri(request.redirectUri);
5738
5797
  // generate the correlationId if not set by the user and add
@@ -5745,7 +5804,9 @@ class AuthorizationCodeClient extends BaseClient {
5745
5804
  parameterBuilder.addResponseTypeCode();
5746
5805
  // add library info parameters
5747
5806
  parameterBuilder.addLibraryInfo(this.config.libraryInfo);
5748
- parameterBuilder.addApplicationTelemetry(this.config.telemetry.application);
5807
+ if (!isOidcProtocolMode(this.config)) {
5808
+ parameterBuilder.addApplicationTelemetry(this.config.telemetry.application);
5809
+ }
5749
5810
  // add client_info=1
5750
5811
  parameterBuilder.addClientInfo();
5751
5812
  if (request.codeChallenge && request.codeChallengeMethod) {
@@ -5906,11 +5967,11 @@ class RefreshTokenClient extends BaseClient {
5906
5967
  this.performanceClient?.setPreQueueTime(PerformanceEvents.RefreshTokenClientExecuteTokenRequest, request.correlationId);
5907
5968
  const response = await this.executeTokenRequest(request, this.authority);
5908
5969
  const httpVerToken = response.headers?.[HeaderNames.X_MS_HTTP_VERSION];
5909
- atsMeasurement?.addStaticFields({
5970
+ atsMeasurement?.add({
5910
5971
  refreshTokenSize: response.body.refresh_token?.length || 0,
5911
5972
  });
5912
5973
  if (httpVerToken) {
5913
- atsMeasurement?.addStaticFields({
5974
+ atsMeasurement?.add({
5914
5975
  httpVerToken,
5915
5976
  });
5916
5977
  }
@@ -5922,14 +5983,14 @@ class RefreshTokenClient extends BaseClient {
5922
5983
  return responseHandler
5923
5984
  .handleServerTokenResponse(response.body, this.authority, reqTimestamp, request, undefined, undefined, true, request.forceCache, requestId)
5924
5985
  .then((result) => {
5925
- atsMeasurement?.endMeasurement({
5986
+ atsMeasurement?.end({
5926
5987
  success: true,
5927
5988
  });
5928
5989
  return result;
5929
5990
  })
5930
5991
  .catch((error) => {
5931
5992
  this.logger.verbose("Error in fetching refresh token", request.correlationId);
5932
- atsMeasurement?.endMeasurement({
5993
+ atsMeasurement?.end({
5933
5994
  errorCode: error.errorCode,
5934
5995
  subErrorCode: error.subError,
5935
5996
  success: false,
@@ -5993,11 +6054,11 @@ class RefreshTokenClient extends BaseClient {
5993
6054
  this.logger.verbose("RefreshTokenClientAcquireTokenWithCachedRefreshToken called", request.correlationId);
5994
6055
  const refreshToken = this.cacheManager.getRefreshToken(request.account, foci);
5995
6056
  if (!refreshToken) {
5996
- atsMeasurement?.discardMeasurement();
6057
+ atsMeasurement?.discard();
5997
6058
  throw InteractionRequiredAuthError.createNoTokensFoundError();
5998
6059
  }
5999
6060
  // attach cached RT size to the current measurement
6000
- atsMeasurement?.endMeasurement({
6061
+ atsMeasurement?.end({
6001
6062
  success: true,
6002
6063
  });
6003
6064
  const refreshTokenRequest = {
@@ -6038,13 +6099,13 @@ class RefreshTokenClient extends BaseClient {
6038
6099
  };
6039
6100
  return this.executePostToTokenEndpoint(endpoint, requestBody, headers, thumbprint)
6040
6101
  .then((result) => {
6041
- acquireTokenMeasurement?.endMeasurement({
6102
+ acquireTokenMeasurement?.end({
6042
6103
  success: true,
6043
6104
  });
6044
6105
  return result;
6045
6106
  })
6046
6107
  .catch((error) => {
6047
- acquireTokenMeasurement?.endMeasurement({
6108
+ acquireTokenMeasurement?.end({
6048
6109
  success: false,
6049
6110
  });
6050
6111
  throw error;
@@ -6060,13 +6121,13 @@ class RefreshTokenClient extends BaseClient {
6060
6121
  const acquireTokenMeasurement = this.performanceClient?.startMeasurement(PerformanceEvents.BaseClientCreateTokenRequestHeaders, correlationId);
6061
6122
  const parameterBuilder = new RequestParameterBuilder();
6062
6123
  parameterBuilder.addClientId(this.config.authOptions.clientId);
6063
- parameterBuilder.addScopes(request.scopes);
6124
+ parameterBuilder.addScopes(request.scopes, true, this.config.authOptions.authority.options.OIDCOptions?.defaultScopes);
6064
6125
  parameterBuilder.addGrantType(GrantType.REFRESH_TOKEN_GRANT);
6065
6126
  parameterBuilder.addClientInfo();
6066
6127
  parameterBuilder.addLibraryInfo(this.config.libraryInfo);
6067
6128
  parameterBuilder.addApplicationTelemetry(this.config.telemetry.application);
6068
6129
  parameterBuilder.addThrottling();
6069
- if (this.serverTelemetryManager) {
6130
+ if (this.serverTelemetryManager && !isOidcProtocolMode(this.config)) {
6070
6131
  parameterBuilder.addServerTelemetry(this.serverTelemetryManager);
6071
6132
  }
6072
6133
  parameterBuilder.addCorrelationId(correlationId);
@@ -6091,7 +6152,7 @@ class RefreshTokenClient extends BaseClient {
6091
6152
  parameterBuilder.addSshJwk(request.sshJwk);
6092
6153
  }
6093
6154
  else {
6094
- acquireTokenMeasurement?.endMeasurement({
6155
+ acquireTokenMeasurement?.end({
6095
6156
  success: false,
6096
6157
  });
6097
6158
  throw ClientConfigurationError.createMissingSshJwkError();
@@ -6120,7 +6181,7 @@ class RefreshTokenClient extends BaseClient {
6120
6181
  break;
6121
6182
  }
6122
6183
  }
6123
- acquireTokenMeasurement?.endMeasurement({
6184
+ acquireTokenMeasurement?.end({
6124
6185
  success: true,
6125
6186
  });
6126
6187
  return parameterBuilder.createQueryString();
@@ -6170,6 +6231,12 @@ class SilentFlowClient extends BaseClient {
6170
6231
  this.logger.info("SilentFlowClient:acquireCachedToken - Skipping cache because forceRefresh is true.");
6171
6232
  throw ClientAuthError.createRefreshRequiredError();
6172
6233
  }
6234
+ else if (!this.config.cacheOptions.claimsBasedCachingEnabled &&
6235
+ !StringUtils.isEmptyObj(request.claims)) {
6236
+ // Must refresh due to request parameters.
6237
+ this.logger.info("SilentFlowClient:acquireCachedToken - Skipping cache because claims-based caching is disabled and claims were requested.");
6238
+ throw ClientAuthError.createRefreshRequiredError();
6239
+ }
6173
6240
  // We currently do not support silent flow for account === null use cases; This will be revisited for confidential flow usecases
6174
6241
  if (!request.account) {
6175
6242
  throw ClientAuthError.createNoAccountInSilentRequestError();
@@ -7109,18 +7176,14 @@ const rawMetdataJSON = {
7109
7176
  };
7110
7177
  const EndpointMetadata = rawMetdataJSON.endpointMetadata;
7111
7178
  const InstanceDiscoveryMetadata = rawMetdataJSON.instanceDiscoveryMetadata;
7112
-
7113
- /*
7114
- * Copyright (c) Microsoft Corporation. All rights reserved.
7115
- * Licensed under the MIT License.
7116
- */
7117
- /**
7118
- * Protocol modes supported by MSAL.
7119
- */
7120
- const ProtocolMode = {
7121
- AAD: "AAD",
7122
- OIDC: "OIDC",
7123
- };
7179
+ const InstanceDiscoveryMetadataAliases = new Set();
7180
+ for (const key in InstanceDiscoveryMetadata) {
7181
+ for (const metadata of InstanceDiscoveryMetadata[key].metadata) {
7182
+ for (const alias of metadata.aliases) {
7183
+ InstanceDiscoveryMetadataAliases.add(alias);
7184
+ }
7185
+ }
7186
+ }
7124
7187
 
7125
7188
  /*
7126
7189
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -7498,10 +7561,10 @@ class Authority {
7498
7561
  * @private
7499
7562
  */
7500
7563
  canReplaceTenant(authorityUri) {
7501
- return authorityUri.PathSegments.length === 1
7502
- && !Authority.reservedTenantDomains.has(authorityUri.PathSegments[0])
7503
- && this.getAuthorityType(authorityUri) === AuthorityType.Default
7504
- && this.protocolMode === ProtocolMode.AAD;
7564
+ return (authorityUri.PathSegments.length === 1 &&
7565
+ !Authority.reservedTenantDomains.has(authorityUri.PathSegments[0]) &&
7566
+ this.getAuthorityType(authorityUri) === AuthorityType.Default &&
7567
+ this.protocolMode === ProtocolMode.AAD);
7505
7568
  }
7506
7569
  /**
7507
7570
  * Replaces tenant in url path with current tenant. Defaults to common.
@@ -7522,8 +7585,9 @@ class Authority {
7522
7585
  const currentAuthorityParts = this.canonicalAuthorityUrlComponents.PathSegments;
7523
7586
  currentAuthorityParts.forEach((currentPart, index) => {
7524
7587
  let cachedPart = cachedAuthorityParts[index];
7525
- if (index === 0 && this.canReplaceTenant(cachedAuthorityUrlComponents)) {
7526
- const tenantId = (new UrlString(this.metadata.authorization_endpoint)).getUrlComponents().PathSegments[0];
7588
+ if (index === 0 &&
7589
+ this.canReplaceTenant(cachedAuthorityUrlComponents)) {
7590
+ const tenantId = new UrlString(this.metadata.authorization_endpoint).getUrlComponents().PathSegments[0];
7527
7591
  /**
7528
7592
  * Check if AAD canonical authority contains tenant domain name, for example "testdomain.onmicrosoft.com",
7529
7593
  * by comparing its first path segment to the corresponding authorization endpoint path segment, which is
@@ -7544,8 +7608,9 @@ class Authority {
7544
7608
  * The default open id configuration endpoint for any canonical authority.
7545
7609
  */
7546
7610
  get defaultOpenIdConfigurationEndpoint() {
7611
+ const canonicalAuthorityHost = this.hostnameAndPort;
7547
7612
  if (this.authorityType === AuthorityType.Adfs ||
7548
- this.protocolMode === ProtocolMode.OIDC) {
7613
+ !this.isAliasOfKnownMicrosoftAuthority(canonicalAuthorityHost)) {
7549
7614
  return `${this.canonicalAuthority}.well-known/openid-configuration`;
7550
7615
  }
7551
7616
  return `${this.canonicalAuthority}v2.0/.well-known/openid-configuration`;
@@ -7588,41 +7653,65 @@ class Authority {
7588
7653
  */
7589
7654
  async updateEndpointMetadata(metadataEntity) {
7590
7655
  this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityUpdateEndpointMetadata, this.correlationId);
7656
+ this.logger.verbose("Attempting to get endpoint metadata from authority configuration");
7591
7657
  let metadata = this.getEndpointMetadataFromConfig();
7592
7658
  if (metadata) {
7659
+ this.logger.verbose("Found endpoint metadata in authority configuration");
7593
7660
  metadataEntity.updateEndpointMetadata(metadata, false);
7594
7661
  return AuthorityMetadataSource.CONFIG;
7595
7662
  }
7663
+ this.logger.verbose("Did not find endpoint metadata in the config... Attempting to get endpoint metadata from the hardcoded values.");
7664
+ // skipAuthorityMetadataCache is used to bypass hardcoded authority metadata and force a network metadata cache lookup and network metadata request if no cached response is available.
7665
+ if (this.authorityOptions.skipAuthorityMetadataCache) {
7666
+ this.logger.verbose("Skipping hardcoded metadata cache since skipAuthorityMetadataCache is set to true. Attempting to get endpoint metadata from the network metadata cache.");
7667
+ }
7668
+ else {
7669
+ let hardcodedMetadata = this.getEndpointMetadataFromHardcodedValues();
7670
+ if (hardcodedMetadata) {
7671
+ this.logger.verbose("Found endpoint metadata from hardcoded values.");
7672
+ // If the user prefers to use an azure region replace the global endpoints with regional information.
7673
+ if (this.authorityOptions.azureRegionConfiguration?.azureRegion) {
7674
+ this.performanceClient?.setPreQueueTime(PerformanceEvents.AuthorityUpdateMetadataWithRegionalInformation, this.correlationId);
7675
+ this.logger.verbose("Found azure region configuration. Updating endpoints with regional information.");
7676
+ hardcodedMetadata =
7677
+ await this.updateMetadataWithRegionalInformation(hardcodedMetadata);
7678
+ }
7679
+ metadataEntity.updateEndpointMetadata(hardcodedMetadata, false);
7680
+ return AuthorityMetadataSource.HARDCODED_VALUES;
7681
+ }
7682
+ else {
7683
+ this.logger.verbose("Did not find endpoint metadata in hardcoded values... Attempting to get endpoint metadata from the network metadata cache.");
7684
+ }
7685
+ }
7686
+ // Check cached metadata entity expiration status
7687
+ const metadataEntityExpired = metadataEntity.isExpired();
7596
7688
  if (this.isAuthoritySameType(metadataEntity) &&
7597
7689
  metadataEntity.endpointsFromNetwork &&
7598
- !metadataEntity.isExpired()) {
7690
+ !metadataEntityExpired) {
7599
7691
  // No need to update
7692
+ this.logger.verbose("Found endpoint metadata in the cache.");
7600
7693
  return AuthorityMetadataSource.CACHE;
7601
7694
  }
7695
+ else if (metadataEntityExpired) {
7696
+ this.logger.verbose("The metadata entity is expired.");
7697
+ }
7698
+ this.logger.verbose("Did not find cached endpoint metadata... Attempting to get endpoint metadata from the network.");
7602
7699
  this.performanceClient?.setPreQueueTime(PerformanceEvents.AuthorityGetEndpointMetadataFromNetwork, this.correlationId);
7603
7700
  metadata = await this.getEndpointMetadataFromNetwork();
7604
7701
  if (metadata) {
7702
+ this.logger.verbose("Endpoint metadata was successfully returned from getEndpointMetadataFromNetwork()");
7605
7703
  // If the user prefers to use an azure region replace the global endpoints with regional information.
7606
7704
  if (this.authorityOptions.azureRegionConfiguration?.azureRegion) {
7607
7705
  this.performanceClient?.setPreQueueTime(PerformanceEvents.AuthorityUpdateMetadataWithRegionalInformation, this.correlationId);
7706
+ this.logger.verbose("Found azure region configuration. Updating endpoints with regional information.");
7608
7707
  metadata = await this.updateMetadataWithRegionalInformation(metadata);
7609
7708
  }
7610
7709
  metadataEntity.updateEndpointMetadata(metadata, true);
7611
7710
  return AuthorityMetadataSource.NETWORK;
7612
7711
  }
7613
- let harcodedMetadata = this.getEndpointMetadataFromHardcodedValues();
7614
- if (harcodedMetadata &&
7615
- !this.authorityOptions.skipAuthorityMetadataCache) {
7616
- // If the user prefers to use an azure region replace the global endpoints with regional information.
7617
- if (this.authorityOptions.azureRegionConfiguration?.azureRegion) {
7618
- this.performanceClient?.setPreQueueTime(PerformanceEvents.AuthorityUpdateMetadataWithRegionalInformation, this.correlationId);
7619
- harcodedMetadata =
7620
- await this.updateMetadataWithRegionalInformation(harcodedMetadata);
7621
- }
7622
- metadataEntity.updateEndpointMetadata(harcodedMetadata, false);
7623
- return AuthorityMetadataSource.HARDCODED_VALUES;
7624
- }
7625
7712
  else {
7713
+ // Metadata could not be obtained from the config, cache, network or hardcoded values
7714
+ this.logger.error("Did not find endpoint metadata from network... Metadata could not be obtained from config, cache, network or hardcoded values. Throwing Untrusted Authority Error.");
7626
7715
  throw ClientAuthError.createUnableToGetOpenidConfigError(this.defaultOpenIdConfigurationEndpoint);
7627
7716
  }
7628
7717
  }
@@ -7671,17 +7760,23 @@ class Authority {
7671
7760
  const response = await this.networkInterface.sendGetRequestAsync(openIdConfigurationEndpoint, options);
7672
7761
  const isValidResponse = isOpenIdConfigResponse(response.body);
7673
7762
  if (isValidResponse) {
7674
- perfEvent?.endMeasurement({ success: true });
7763
+ perfEvent?.end({ success: true });
7675
7764
  return response.body;
7676
7765
  }
7677
7766
  else {
7678
- perfEvent?.endMeasurement({ success: false, errorCode: "invalid_response" });
7767
+ perfEvent?.end({
7768
+ success: false,
7769
+ errorCode: "invalid_response",
7770
+ });
7679
7771
  this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: could not parse response as OpenID configuration`);
7680
7772
  return null;
7681
7773
  }
7682
7774
  }
7683
7775
  catch (e) {
7684
- perfEvent?.endMeasurement({ success: false, errorCode: "request_failure" });
7776
+ perfEvent?.end({
7777
+ success: false,
7778
+ errorCode: "request_failure",
7779
+ });
7685
7780
  this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: ${e}`);
7686
7781
  return null;
7687
7782
  }
@@ -7697,37 +7792,32 @@ class Authority {
7697
7792
  }
7698
7793
  /**
7699
7794
  * Update the retrieved metadata with regional information.
7795
+ * User selected Azure region will be used if configured.
7700
7796
  */
7701
7797
  async updateMetadataWithRegionalInformation(metadata) {
7702
7798
  this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityUpdateMetadataWithRegionalInformation, this.correlationId);
7703
- this.performanceClient?.setPreQueueTime(PerformanceEvents.RegionDiscoveryDetectRegion, this.correlationId);
7704
- const autodetectedRegionName = await this.regionDiscovery.detectRegion(this.authorityOptions.azureRegionConfiguration?.environmentRegion, this.regionDiscoveryMetadata);
7705
- const azureRegion = this.authorityOptions.azureRegionConfiguration?.azureRegion ===
7706
- Constants.AZURE_REGION_AUTO_DISCOVER_FLAG
7707
- ? autodetectedRegionName
7708
- : this.authorityOptions.azureRegionConfiguration?.azureRegion;
7709
- if (this.authorityOptions.azureRegionConfiguration?.azureRegion ===
7710
- Constants.AZURE_REGION_AUTO_DISCOVER_FLAG) {
7711
- this.regionDiscoveryMetadata.region_outcome = autodetectedRegionName
7712
- ? RegionDiscoveryOutcomes.AUTO_DETECTION_REQUESTED_SUCCESSFUL
7713
- : RegionDiscoveryOutcomes.AUTO_DETECTION_REQUESTED_FAILED;
7714
- }
7715
- else {
7716
- if (autodetectedRegionName) {
7799
+ const userConfiguredAzureRegion = this.authorityOptions.azureRegionConfiguration?.azureRegion;
7800
+ if (userConfiguredAzureRegion) {
7801
+ if (userConfiguredAzureRegion !==
7802
+ Constants.AZURE_REGION_AUTO_DISCOVER_FLAG) {
7717
7803
  this.regionDiscoveryMetadata.region_outcome =
7718
- this.authorityOptions.azureRegionConfiguration
7719
- ?.azureRegion === autodetectedRegionName
7720
- ? RegionDiscoveryOutcomes.CONFIGURED_MATCHES_DETECTED
7721
- : RegionDiscoveryOutcomes.CONFIGURED_NOT_DETECTED;
7804
+ RegionDiscoveryOutcomes.CONFIGURED_NO_AUTO_DETECTION;
7805
+ this.regionDiscoveryMetadata.region_used =
7806
+ userConfiguredAzureRegion;
7807
+ return Authority.replaceWithRegionalInformation(metadata, userConfiguredAzureRegion);
7722
7808
  }
7723
- else {
7809
+ this.performanceClient?.setPreQueueTime(PerformanceEvents.RegionDiscoveryDetectRegion, this.correlationId);
7810
+ const autodetectedRegionName = await this.regionDiscovery.detectRegion(this.authorityOptions.azureRegionConfiguration
7811
+ ?.environmentRegion, this.regionDiscoveryMetadata);
7812
+ if (autodetectedRegionName) {
7724
7813
  this.regionDiscoveryMetadata.region_outcome =
7725
- RegionDiscoveryOutcomes.CONFIGURED_NO_AUTO_DETECTION;
7814
+ RegionDiscoveryOutcomes.AUTO_DETECTION_REQUESTED_SUCCESSFUL;
7815
+ this.regionDiscoveryMetadata.region_used =
7816
+ autodetectedRegionName;
7817
+ return Authority.replaceWithRegionalInformation(metadata, autodetectedRegionName);
7726
7818
  }
7727
- }
7728
- if (azureRegion) {
7729
- this.regionDiscoveryMetadata.region_used = azureRegion;
7730
- return Authority.replaceWithRegionalInformation(metadata, azureRegion);
7819
+ this.regionDiscoveryMetadata.region_outcome =
7820
+ RegionDiscoveryOutcomes.AUTO_DETECTION_REQUESTED_FAILED;
7731
7821
  }
7732
7822
  return metadata;
7733
7823
  }
@@ -7739,7 +7829,7 @@ class Authority {
7739
7829
  */
7740
7830
  async updateCloudDiscoveryMetadata(metadataEntity) {
7741
7831
  this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityUpdateCloudDiscoveryMetadata, this.correlationId);
7742
- this.logger.verbose("Attempting to get cloud discovery metadata in the config");
7832
+ this.logger.verbose("Attempting to get cloud discovery metadata from authority configuration");
7743
7833
  this.logger.verbosePii(`Known Authorities: ${this.authorityOptions.knownAuthorities ||
7744
7834
  Constants.NOT_APPLICABLE}`);
7745
7835
  this.logger.verbosePii(`Authority Metadata: ${this.authorityOptions.authorityMetadata ||
@@ -7747,17 +7837,29 @@ class Authority {
7747
7837
  this.logger.verbosePii(`Canonical Authority: ${metadataEntity.canonical_authority || Constants.NOT_APPLICABLE}`);
7748
7838
  let metadata = this.getCloudDiscoveryMetadataFromConfig();
7749
7839
  if (metadata) {
7750
- this.logger.verbose("Found cloud discovery metadata in the config.");
7840
+ this.logger.verbose("Found cloud discovery metadata in authority configuration");
7751
7841
  metadataEntity.updateCloudDiscoveryMetadata(metadata, false);
7752
7842
  return AuthorityMetadataSource.CONFIG;
7753
7843
  }
7754
- // If the cached metadata came from config but that config was not passed to this instance, we must go to the network
7755
- this.logger.verbose("Did not find cloud discovery metadata in the config... Attempting to get cloud discovery metadata from the cache.");
7844
+ // If the cached metadata came from config but that config was not passed to this instance, we must go to hardcoded values
7845
+ this.logger.verbose("Did not find cloud discovery metadata in the config... Attempting to get cloud discovery metadata from the hardcoded values.");
7846
+ if (this.options.skipAuthorityMetadataCache) {
7847
+ this.logger.verbose("Skipping hardcoded cloud discovery metadata cache since skipAuthorityMetadataCache is set to true. Attempting to get cloud discovery metadata from the network metadata cache.");
7848
+ }
7849
+ else {
7850
+ const hardcodedMetadata = this.getCloudDiscoveryMetadataFromHardcodedValues();
7851
+ if (hardcodedMetadata) {
7852
+ this.logger.verbose("Found cloud discovery metadata from hardcoded values.");
7853
+ metadataEntity.updateCloudDiscoveryMetadata(hardcodedMetadata, false);
7854
+ return AuthorityMetadataSource.HARDCODED_VALUES;
7855
+ }
7856
+ this.logger.verbose("Did not find cloud discovery metadata in hardcoded values... Attempting to get cloud discovery metadata from the network metadata cache.");
7857
+ }
7756
7858
  const metadataEntityExpired = metadataEntity.isExpired();
7757
7859
  if (this.isAuthoritySameType(metadataEntity) &&
7758
7860
  metadataEntity.aliasesFromNetwork &&
7759
7861
  !metadataEntityExpired) {
7760
- this.logger.verbose("Found metadata in the cache.");
7862
+ this.logger.verbose("Found cloud discovery metadata in the cache.");
7761
7863
  // No need to update
7762
7864
  return AuthorityMetadataSource.CACHE;
7763
7865
  }
@@ -7772,15 +7874,8 @@ class Authority {
7772
7874
  metadataEntity.updateCloudDiscoveryMetadata(metadata, true);
7773
7875
  return AuthorityMetadataSource.NETWORK;
7774
7876
  }
7775
- this.logger.verbose("Did not find cloud discovery metadata from the network... Attempting to get cloud discovery metadata from hardcoded values.");
7776
- const harcodedMetadata = this.getCloudDiscoveryMetadataFromHarcodedValues();
7777
- if (harcodedMetadata && !this.options.skipAuthorityMetadataCache) {
7778
- this.logger.verbose("Found cloud discovery metadata from hardcoded values.");
7779
- metadataEntity.updateCloudDiscoveryMetadata(harcodedMetadata, false);
7780
- return AuthorityMetadataSource.HARDCODED_VALUES;
7781
- }
7782
7877
  // Metadata could not be obtained from the config, cache, network or hardcoded values
7783
- 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.");
7878
+ this.logger.error("Did not find cloud discovery metadata from network... Metadata could not be obtained from config, cache, network or hardcoded values. Throwing Untrusted Authority Error.");
7784
7879
  throw ClientConfigurationError.createUntrustedAuthorityError();
7785
7880
  }
7786
7881
  /**
@@ -7885,9 +7980,11 @@ class Authority {
7885
7980
  /**
7886
7981
  * Get cloud discovery metadata for common authorities
7887
7982
  */
7888
- getCloudDiscoveryMetadataFromHarcodedValues() {
7983
+ getCloudDiscoveryMetadataFromHardcodedValues() {
7889
7984
  if (this.canonicalAuthority in InstanceDiscoveryMetadata) {
7890
- return InstanceDiscoveryMetadata[this.canonicalAuthority];
7985
+ const hardcodedMetadataResponse = InstanceDiscoveryMetadata[this.canonicalAuthority];
7986
+ const metadata = Authority.getCloudDiscoveryMetadataFromNetworkResponse(hardcodedMetadataResponse.metadata, this.hostnameAndPort);
7987
+ return metadata;
7891
7988
  }
7892
7989
  return null;
7893
7990
  }
@@ -7962,6 +8059,13 @@ class Authority {
7962
8059
  isAlias(host) {
7963
8060
  return this.metadata.aliases.indexOf(host) > -1;
7964
8061
  }
8062
+ /**
8063
+ * Returns whether or not the provided host is an alias of a known Microsoft authority for purposes of endpoint discovery
8064
+ * @param host
8065
+ */
8066
+ isAliasOfKnownMicrosoftAuthority(host) {
8067
+ return InstanceDiscoveryMetadataAliases.has(host);
8068
+ }
7965
8069
  /**
7966
8070
  * Checks whether the provided host is that of a public cloud authority
7967
8071
  *
@@ -8003,15 +8107,17 @@ class Authority {
8003
8107
  * @param azureRegion string
8004
8108
  */
8005
8109
  static replaceWithRegionalInformation(metadata, azureRegion) {
8006
- metadata.authorization_endpoint =
8007
- Authority.buildRegionalAuthorityString(metadata.authorization_endpoint, azureRegion);
8110
+ const regionalMetadata = { ...metadata };
8111
+ regionalMetadata.authorization_endpoint =
8112
+ Authority.buildRegionalAuthorityString(regionalMetadata.authorization_endpoint, azureRegion);
8008
8113
  // TODO: Enquire on whether we should leave the query string or remove it before releasing the feature
8009
- metadata.token_endpoint = Authority.buildRegionalAuthorityString(metadata.token_endpoint, azureRegion, Constants.REGIONAL_AUTH_NON_MSI_QUERY_STRING);
8010
- if (metadata.end_session_endpoint) {
8011
- metadata.end_session_endpoint =
8012
- Authority.buildRegionalAuthorityString(metadata.end_session_endpoint, azureRegion);
8114
+ regionalMetadata.token_endpoint =
8115
+ Authority.buildRegionalAuthorityString(regionalMetadata.token_endpoint, azureRegion, Constants.REGIONAL_AUTH_NON_MSI_QUERY_STRING);
8116
+ if (regionalMetadata.end_session_endpoint) {
8117
+ regionalMetadata.end_session_endpoint =
8118
+ Authority.buildRegionalAuthorityString(regionalMetadata.end_session_endpoint, azureRegion);
8013
8119
  }
8014
- return metadata;
8120
+ return regionalMetadata;
8015
8121
  }
8016
8122
  /**
8017
8123
  * Transform CIAM_AUTHORIY as per the below rules:
@@ -8023,11 +8129,14 @@ class Authority {
8023
8129
  * @param authority
8024
8130
  */
8025
8131
  static transformCIAMAuthority(authority) {
8026
- let ciamAuthority = authority.endsWith(Constants.FORWARD_SLASH) ? authority : `${authority}${Constants.FORWARD_SLASH}`;
8132
+ let ciamAuthority = authority.endsWith(Constants.FORWARD_SLASH)
8133
+ ? authority
8134
+ : `${authority}${Constants.FORWARD_SLASH}`;
8027
8135
  const authorityUrl = new UrlString(authority);
8028
8136
  const authorityUrlComponents = authorityUrl.getUrlComponents();
8029
8137
  // check if transformation is needed
8030
- if (authorityUrlComponents.PathSegments.length === 0 && (authorityUrlComponents.HostNameAndPort.endsWith(Constants.CIAM_AUTH_URL))) {
8138
+ if (authorityUrlComponents.PathSegments.length === 0 &&
8139
+ authorityUrlComponents.HostNameAndPort.endsWith(Constants.CIAM_AUTH_URL)) {
8031
8140
  const tenantIdOrDomain = authorityUrlComponents.HostNameAndPort.split(".")[0];
8032
8141
  ciamAuthority = `${ciamAuthority}${tenantIdOrDomain}${Constants.AAD_TENANT_DOMAIN_SUFFIX}`;
8033
8142
  }
@@ -8035,13 +8144,13 @@ class Authority {
8035
8144
  }
8036
8145
  }
8037
8146
  // Reserved tenant domain names that will not be replaced with tenant id
8038
- Authority.reservedTenantDomains = (new Set([
8147
+ Authority.reservedTenantDomains = new Set([
8039
8148
  "{tenant}",
8040
8149
  "{tenantid}",
8041
8150
  AADAuthorityConstants.COMMON,
8042
8151
  AADAuthorityConstants.CONSUMERS,
8043
- AADAuthorityConstants.ORGANIZATIONS
8044
- ]));
8152
+ AADAuthorityConstants.ORGANIZATIONS,
8153
+ ]);
8045
8154
 
8046
8155
  /*
8047
8156
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -8503,8 +8612,10 @@ class PerformanceClient {
8503
8612
  * @param {Logger} logger Logger used by the application
8504
8613
  * @param {string} libraryName Name of the library
8505
8614
  * @param {string} libraryVersion Version of the library
8615
+ * @param {ApplicationTelemetry} applicationTelemetry application name and version
8616
+ * @param {Set<String>} intFields integer fields to be truncated
8506
8617
  */
8507
- constructor(clientId, authority, logger, libraryName, libraryVersion, applicationTelemetry) {
8618
+ constructor(clientId, authority, logger, libraryName, libraryVersion, applicationTelemetry, intFields) {
8508
8619
  this.authority = authority;
8509
8620
  this.libraryName = libraryName;
8510
8621
  this.libraryVersion = libraryVersion;
@@ -8515,6 +8626,10 @@ class PerformanceClient {
8515
8626
  this.eventsByCorrelationId = new Map();
8516
8627
  this.queueMeasurements = new Map();
8517
8628
  this.preQueueTimeByCorrelationId = new Map();
8629
+ this.intFields = intFields || new Set();
8630
+ for (const item of IntFields) {
8631
+ this.intFields.add(item);
8632
+ }
8518
8633
  }
8519
8634
  /**
8520
8635
  * Starts and returns an platform-specific implementation of IPerformanceMeasurement.
@@ -8529,13 +8644,6 @@ class PerformanceClient {
8529
8644
  ) {
8530
8645
  return {};
8531
8646
  }
8532
- /**
8533
- * Get integral fields.
8534
- * Override to change the set.
8535
- */
8536
- getIntFields() {
8537
- return IntFields;
8538
- }
8539
8647
  /**
8540
8648
  * Gets map of pre-queue times by correlation Id
8541
8649
  *
@@ -8653,7 +8761,7 @@ class PerformanceClient {
8653
8761
  this.cacheEventByCorrelationId(inProgressEvent);
8654
8762
  // Return the event and functions the caller can use to properly end/flush the measurement
8655
8763
  return {
8656
- endMeasurement: (event) => {
8764
+ end: (event) => {
8657
8765
  return this.endMeasurement({
8658
8766
  // Initial set of event properties
8659
8767
  ...inProgressEvent,
@@ -8661,14 +8769,14 @@ class PerformanceClient {
8661
8769
  ...event,
8662
8770
  }, performanceMeasurement);
8663
8771
  },
8664
- discardMeasurement: () => {
8772
+ discard: () => {
8665
8773
  return this.discardMeasurements(inProgressEvent.correlationId);
8666
8774
  },
8667
- addStaticFields: (fields) => {
8668
- return this.addStaticFields(fields, inProgressEvent.correlationId);
8775
+ add: (fields) => {
8776
+ return this.addFields(fields, inProgressEvent.correlationId);
8669
8777
  },
8670
- increment: (counters) => {
8671
- return this.increment(counters, inProgressEvent.correlationId);
8778
+ increment: (fields) => {
8779
+ return this.incrementFields(fields, inProgressEvent.correlationId);
8672
8780
  },
8673
8781
  measurement: performanceMeasurement,
8674
8782
  event: inProgressEvent,
@@ -8733,7 +8841,7 @@ class PerformanceClient {
8733
8841
  status: PerformanceEventStatus.Completed,
8734
8842
  incompleteSubsCount,
8735
8843
  };
8736
- this.truncateIntegralFields(finalEvent, this.getIntFields());
8844
+ this.truncateIntegralFields(finalEvent);
8737
8845
  this.emitEvents([finalEvent], event.correlationId);
8738
8846
  return finalEvent;
8739
8847
  }
@@ -8742,7 +8850,7 @@ class PerformanceClient {
8742
8850
  * @param fields
8743
8851
  * @param correlationId
8744
8852
  */
8745
- addStaticFields(fields, correlationId) {
8853
+ addFields(fields, correlationId) {
8746
8854
  this.logger.trace("PerformanceClient: Updating static fields");
8747
8855
  const event = this.eventsByCorrelationId.get(correlationId);
8748
8856
  if (event) {
@@ -8757,18 +8865,21 @@ class PerformanceClient {
8757
8865
  }
8758
8866
  /**
8759
8867
  * Increment counters to be emitted when the measurements are flushed
8760
- * @param counters {Counters}
8868
+ * @param fields {string[]}
8761
8869
  * @param correlationId {string} correlation identifier
8762
8870
  */
8763
- increment(counters, correlationId) {
8871
+ incrementFields(fields, correlationId) {
8764
8872
  this.logger.trace("PerformanceClient: Updating counters");
8765
8873
  const event = this.eventsByCorrelationId.get(correlationId);
8766
8874
  if (event) {
8767
- for (const counter in counters) {
8875
+ for (const counter in fields) {
8768
8876
  if (!event.hasOwnProperty(counter)) {
8769
8877
  event[counter] = 0;
8770
8878
  }
8771
- event[counter] += counters[counter];
8879
+ else if (isNaN(Number(event[counter]))) {
8880
+ return;
8881
+ }
8882
+ event[counter] += fields[counter];
8772
8883
  }
8773
8884
  }
8774
8885
  else {
@@ -8886,8 +8997,8 @@ class PerformanceClient {
8886
8997
  * @param {PerformanceEvent} event performance event to update.
8887
8998
  * @param {Set<string>} intFields integral fields.
8888
8999
  */
8889
- truncateIntegralFields(event, intFields) {
8890
- intFields.forEach((key) => {
9000
+ truncateIntegralFields(event) {
9001
+ this.intFields.forEach((key) => {
8891
9002
  if (key in event && typeof event[key] === "number") {
8892
9003
  event[key] = Math.floor(event[key]);
8893
9004
  }
@@ -8900,9 +9011,15 @@ class PerformanceClient {
8900
9011
  * Licensed under the MIT License.
8901
9012
  */
8902
9013
  class StubPerformanceMeasurement {
8903
- startMeasurement() { return; }
8904
- endMeasurement() { return; }
8905
- flushMeasurement() { return null; }
9014
+ startMeasurement() {
9015
+ return;
9016
+ }
9017
+ endMeasurement() {
9018
+ return;
9019
+ }
9020
+ flushMeasurement() {
9021
+ return null;
9022
+ }
8906
9023
  }
8907
9024
  class StubPerformanceClient extends PerformanceClient {
8908
9025
  generateId() {
@@ -8914,8 +9031,36 @@ class StubPerformanceClient extends PerformanceClient {
8914
9031
  calculateQueuedTime() {
8915
9032
  return 0;
8916
9033
  }
8917
- addQueueMeasurement() { return; }
8918
- setPreQueueTime() { return; }
9034
+ addQueueMeasurement() {
9035
+ return;
9036
+ }
9037
+ setPreQueueTime() {
9038
+ return;
9039
+ }
9040
+ endMeasurement() {
9041
+ return null;
9042
+ }
9043
+ discardMeasurements() {
9044
+ return;
9045
+ }
9046
+ removePerformanceCallback() {
9047
+ return true;
9048
+ }
9049
+ addPerformanceCallback() {
9050
+ return "";
9051
+ }
9052
+ emitEvents() {
9053
+ return;
9054
+ }
9055
+ addFields() {
9056
+ return;
9057
+ }
9058
+ incrementFields() {
9059
+ return;
9060
+ }
9061
+ cacheEventByCorrelationId() {
9062
+ return;
9063
+ }
8919
9064
  }
8920
9065
 
8921
9066
  exports.AADAuthorityConstants = AADAuthorityConstants;
@@ -8983,6 +9128,7 @@ exports.ResponseMode = ResponseMode;
8983
9128
  exports.SSOTypes = SSOTypes;
8984
9129
  exports.ScopeSet = ScopeSet;
8985
9130
  exports.ServerError = ServerError;
9131
+ exports.ServerResponseType = ServerResponseType;
8986
9132
  exports.ServerTelemetryEntity = ServerTelemetryEntity;
8987
9133
  exports.ServerTelemetryManager = ServerTelemetryManager;
8988
9134
  exports.SilentFlowClient = SilentFlowClient;