@azure/msal-common 14.0.3 → 14.1.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 (226) hide show
  1. package/dist/account/AccountInfo.d.ts +0 -1
  2. package/dist/account/AccountInfo.d.ts.map +1 -1
  3. package/dist/account/AuthToken.d.ts.map +1 -1
  4. package/dist/account/AuthToken.mjs +7 -6
  5. package/dist/account/AuthToken.mjs.map +1 -1
  6. package/dist/account/CcsCredential.mjs +1 -1
  7. package/dist/account/ClientInfo.d.ts.map +1 -1
  8. package/dist/account/ClientInfo.mjs +6 -5
  9. package/dist/account/ClientInfo.mjs.map +1 -1
  10. package/dist/authority/Authority.d.ts.map +1 -1
  11. package/dist/authority/Authority.mjs +28 -50
  12. package/dist/authority/Authority.mjs.map +1 -1
  13. package/dist/authority/AuthorityFactory.d.ts.map +1 -1
  14. package/dist/authority/AuthorityFactory.mjs +9 -7
  15. package/dist/authority/AuthorityFactory.mjs.map +1 -1
  16. package/dist/authority/AuthorityMetadata.mjs +1 -1
  17. package/dist/authority/AuthorityOptions.mjs +1 -1
  18. package/dist/authority/AuthorityType.mjs +1 -1
  19. package/dist/authority/CloudInstanceDiscoveryErrorResponse.mjs +1 -1
  20. package/dist/authority/CloudInstanceDiscoveryResponse.mjs +1 -1
  21. package/dist/authority/OpenIdConfigResponse.mjs +1 -1
  22. package/dist/authority/ProtocolMode.mjs +1 -1
  23. package/dist/authority/RegionDiscovery.d.ts +3 -1
  24. package/dist/authority/RegionDiscovery.d.ts.map +1 -1
  25. package/dist/authority/RegionDiscovery.mjs +7 -8
  26. package/dist/authority/RegionDiscovery.mjs.map +1 -1
  27. package/dist/cache/CacheManager.d.ts +25 -7
  28. package/dist/cache/CacheManager.d.ts.map +1 -1
  29. package/dist/cache/CacheManager.mjs +98 -71
  30. package/dist/cache/CacheManager.mjs.map +1 -1
  31. package/dist/cache/entities/AccessTokenEntity.d.ts.map +1 -1
  32. package/dist/cache/entities/AccessTokenEntity.mjs +4 -3
  33. package/dist/cache/entities/AccessTokenEntity.mjs.map +1 -1
  34. package/dist/cache/entities/AccountEntity.d.ts.map +1 -1
  35. package/dist/cache/entities/AccountEntity.mjs +4 -3
  36. package/dist/cache/entities/AccountEntity.mjs.map +1 -1
  37. package/dist/cache/entities/AppMetadataEntity.mjs +1 -1
  38. package/dist/cache/entities/AuthorityMetadataEntity.mjs +1 -1
  39. package/dist/cache/entities/CacheRecord.mjs +1 -1
  40. package/dist/cache/entities/CredentialEntity.d.ts.map +1 -1
  41. package/dist/cache/entities/CredentialEntity.mjs +4 -3
  42. package/dist/cache/entities/CredentialEntity.mjs.map +1 -1
  43. package/dist/cache/entities/IdTokenEntity.mjs +1 -1
  44. package/dist/cache/entities/RefreshTokenEntity.mjs +1 -1
  45. package/dist/cache/entities/ServerTelemetryEntity.mjs +1 -1
  46. package/dist/cache/entities/ThrottlingEntity.mjs +1 -1
  47. package/dist/cache/persistence/TokenCacheContext.mjs +1 -1
  48. package/dist/cache/utils/CacheTypes.d.ts +3 -6
  49. package/dist/cache/utils/CacheTypes.d.ts.map +1 -1
  50. package/dist/client/AuthorizationCodeClient.d.ts.map +1 -1
  51. package/dist/client/AuthorizationCodeClient.mjs +13 -11
  52. package/dist/client/AuthorizationCodeClient.mjs.map +1 -1
  53. package/dist/client/BaseClient.d.ts.map +1 -1
  54. package/dist/client/BaseClient.mjs +5 -4
  55. package/dist/client/BaseClient.mjs.map +1 -1
  56. package/dist/client/RefreshTokenClient.d.ts.map +1 -1
  57. package/dist/client/RefreshTokenClient.mjs +33 -74
  58. package/dist/client/RefreshTokenClient.mjs.map +1 -1
  59. package/dist/client/SilentFlowClient.d.ts +2 -1
  60. package/dist/client/SilentFlowClient.d.ts.map +1 -1
  61. package/dist/client/SilentFlowClient.mjs +43 -19
  62. package/dist/client/SilentFlowClient.mjs.map +1 -1
  63. package/dist/config/ClientConfiguration.d.ts.map +1 -1
  64. package/dist/config/ClientConfiguration.mjs +5 -6
  65. package/dist/config/ClientConfiguration.mjs.map +1 -1
  66. package/dist/crypto/ICrypto.d.ts +0 -4
  67. package/dist/crypto/ICrypto.d.ts.map +1 -1
  68. package/dist/crypto/ICrypto.mjs +11 -22
  69. package/dist/crypto/ICrypto.mjs.map +1 -1
  70. package/dist/crypto/JoseHeader.d.ts.map +1 -1
  71. package/dist/crypto/JoseHeader.mjs +5 -4
  72. package/dist/crypto/JoseHeader.mjs.map +1 -1
  73. package/dist/crypto/PopTokenGenerator.d.ts +2 -1
  74. package/dist/crypto/PopTokenGenerator.d.ts.map +1 -1
  75. package/dist/crypto/PopTokenGenerator.mjs +4 -4
  76. package/dist/crypto/PopTokenGenerator.mjs.map +1 -1
  77. package/dist/error/AuthError.d.ts +8 -11
  78. package/dist/error/AuthError.d.ts.map +1 -1
  79. package/dist/error/AuthError.mjs +19 -21
  80. package/dist/error/AuthError.mjs.map +1 -1
  81. package/dist/error/AuthErrorCodes.d.ts +6 -0
  82. package/dist/error/AuthErrorCodes.d.ts.map +1 -0
  83. package/dist/error/AuthErrorCodes.mjs +14 -0
  84. package/dist/error/AuthErrorCodes.mjs.map +1 -0
  85. package/dist/error/ClientAuthError.d.ts +54 -234
  86. package/dist/error/ClientAuthError.d.ts.map +1 -1
  87. package/dist/error/ClientAuthError.mjs +149 -421
  88. package/dist/error/ClientAuthError.mjs.map +1 -1
  89. package/dist/error/ClientAuthErrorCodes.d.ts +44 -0
  90. package/dist/error/ClientAuthErrorCodes.d.ts.map +1 -0
  91. package/dist/error/ClientAuthErrorCodes.mjs +52 -0
  92. package/dist/error/ClientAuthErrorCodes.mjs.map +1 -0
  93. package/dist/error/ClientConfigurationError.d.ts +31 -125
  94. package/dist/error/ClientConfigurationError.d.ts.map +1 -1
  95. package/dist/error/ClientConfigurationError.mjs +81 -222
  96. package/dist/error/ClientConfigurationError.mjs.map +1 -1
  97. package/dist/error/ClientConfigurationErrorCodes.d.ts +23 -0
  98. package/dist/error/ClientConfigurationErrorCodes.d.ts.map +1 -0
  99. package/dist/error/ClientConfigurationErrorCodes.mjs +31 -0
  100. package/dist/error/ClientConfigurationErrorCodes.mjs.map +1 -0
  101. package/dist/error/InteractionRequiredAuthError.d.ts +14 -16
  102. package/dist/error/InteractionRequiredAuthError.d.ts.map +1 -1
  103. package/dist/error/InteractionRequiredAuthError.mjs +42 -41
  104. package/dist/error/InteractionRequiredAuthError.mjs.map +1 -1
  105. package/dist/error/InteractionRequiredAuthErrorCodes.d.ts +6 -0
  106. package/dist/error/InteractionRequiredAuthErrorCodes.d.ts.map +1 -0
  107. package/dist/error/InteractionRequiredAuthErrorCodes.mjs +16 -0
  108. package/dist/error/InteractionRequiredAuthErrorCodes.mjs.map +1 -0
  109. package/dist/error/JoseHeaderError.d.ts +7 -20
  110. package/dist/error/JoseHeaderError.d.ts.map +1 -1
  111. package/dist/error/JoseHeaderError.mjs +10 -26
  112. package/dist/error/JoseHeaderError.mjs.map +1 -1
  113. package/dist/error/JoseHeaderErrorCodes.d.ts +3 -0
  114. package/dist/error/JoseHeaderErrorCodes.d.ts.map +1 -0
  115. package/dist/error/JoseHeaderErrorCodes.mjs +11 -0
  116. package/dist/error/JoseHeaderErrorCodes.mjs.map +1 -0
  117. package/dist/error/ServerError.mjs +1 -1
  118. package/dist/index.cjs +942 -1210
  119. package/dist/index.cjs.map +1 -1
  120. package/dist/index.d.ts +5 -5
  121. package/dist/index.d.ts.map +1 -1
  122. package/dist/index.mjs +13 -5
  123. package/dist/index.mjs.map +1 -1
  124. package/dist/logger/Logger.mjs +1 -1
  125. package/dist/network/INetworkModule.d.ts.map +1 -1
  126. package/dist/network/INetworkModule.mjs +5 -6
  127. package/dist/network/INetworkModule.mjs.map +1 -1
  128. package/dist/network/NetworkManager.d.ts.map +1 -1
  129. package/dist/network/NetworkManager.mjs +4 -3
  130. package/dist/network/NetworkManager.mjs.map +1 -1
  131. package/dist/network/ThrottlingUtils.mjs +1 -1
  132. package/dist/packageMetadata.d.ts +1 -1
  133. package/dist/packageMetadata.mjs +2 -2
  134. package/dist/request/AuthenticationHeaderParser.d.ts.map +1 -1
  135. package/dist/request/AuthenticationHeaderParser.mjs +7 -6
  136. package/dist/request/AuthenticationHeaderParser.mjs.map +1 -1
  137. package/dist/request/CommonRefreshTokenRequest.d.ts +3 -0
  138. package/dist/request/CommonRefreshTokenRequest.d.ts.map +1 -1
  139. package/dist/request/CommonSilentFlowRequest.d.ts +2 -0
  140. package/dist/request/CommonSilentFlowRequest.d.ts.map +1 -1
  141. package/dist/request/RequestParameterBuilder.d.ts.map +1 -1
  142. package/dist/request/RequestParameterBuilder.mjs +5 -4
  143. package/dist/request/RequestParameterBuilder.mjs.map +1 -1
  144. package/dist/request/RequestValidator.d.ts.map +1 -1
  145. package/dist/request/RequestValidator.mjs +8 -7
  146. package/dist/request/RequestValidator.mjs.map +1 -1
  147. package/dist/request/ScopeSet.d.ts.map +1 -1
  148. package/dist/request/ScopeSet.mjs +10 -8
  149. package/dist/request/ScopeSet.mjs.map +1 -1
  150. package/dist/response/ResponseHandler.d.ts.map +1 -1
  151. package/dist/response/ResponseHandler.mjs +15 -14
  152. package/dist/response/ResponseHandler.mjs.map +1 -1
  153. package/dist/telemetry/performance/PerformanceClient.d.ts.map +1 -1
  154. package/dist/telemetry/performance/PerformanceClient.mjs +3 -2
  155. package/dist/telemetry/performance/PerformanceClient.mjs.map +1 -1
  156. package/dist/telemetry/performance/PerformanceEvent.d.ts +8 -0
  157. package/dist/telemetry/performance/PerformanceEvent.d.ts.map +1 -1
  158. package/dist/telemetry/performance/PerformanceEvent.mjs +9 -1
  159. package/dist/telemetry/performance/PerformanceEvent.mjs.map +1 -1
  160. package/dist/telemetry/performance/StubPerformanceClient.mjs +1 -1
  161. package/dist/telemetry/server/ServerTelemetryManager.d.ts.map +1 -1
  162. package/dist/telemetry/server/ServerTelemetryManager.mjs +2 -2
  163. package/dist/telemetry/server/ServerTelemetryManager.mjs.map +1 -1
  164. package/dist/url/UrlString.d.ts.map +1 -1
  165. package/dist/url/UrlString.mjs +13 -11
  166. package/dist/url/UrlString.mjs.map +1 -1
  167. package/dist/utils/Constants.d.ts +6 -3
  168. package/dist/utils/Constants.d.ts.map +1 -1
  169. package/dist/utils/Constants.mjs +12 -4
  170. package/dist/utils/Constants.mjs.map +1 -1
  171. package/dist/utils/FunctionWrappers.d.ts.map +1 -1
  172. package/dist/utils/FunctionWrappers.mjs +1 -2
  173. package/dist/utils/FunctionWrappers.mjs.map +1 -1
  174. package/dist/utils/ProtocolUtils.d.ts.map +1 -1
  175. package/dist/utils/ProtocolUtils.mjs +7 -6
  176. package/dist/utils/ProtocolUtils.mjs.map +1 -1
  177. package/dist/utils/StringUtils.mjs +1 -1
  178. package/dist/utils/TimeUtils.mjs +1 -1
  179. package/package.json +1 -1
  180. package/src/account/AccountInfo.ts +0 -1
  181. package/src/account/AuthToken.ts +8 -7
  182. package/src/account/ClientInfo.ts +9 -6
  183. package/src/authority/Authority.ts +76 -94
  184. package/src/authority/AuthorityFactory.ts +21 -9
  185. package/src/authority/RegionDiscovery.ts +21 -18
  186. package/src/cache/CacheManager.ts +133 -95
  187. package/src/cache/entities/AccessTokenEntity.ts +7 -2
  188. package/src/cache/entities/AccountEntity.ts +7 -2
  189. package/src/cache/entities/CredentialEntity.ts +7 -2
  190. package/src/cache/utils/CacheTypes.ts +6 -6
  191. package/src/client/AuthorizationCodeClient.ts +35 -11
  192. package/src/client/BaseClient.ts +7 -4
  193. package/src/client/RefreshTokenClient.ts +100 -126
  194. package/src/client/SilentFlowClient.ts +72 -19
  195. package/src/config/ClientConfiguration.ts +6 -7
  196. package/src/crypto/ICrypto.ts +12 -34
  197. package/src/crypto/JoseHeader.ts +6 -3
  198. package/src/crypto/PopTokenGenerator.ts +10 -5
  199. package/src/error/AuthError.ts +24 -26
  200. package/src/error/AuthErrorCodes.ts +10 -0
  201. package/src/error/ClientAuthError.ts +227 -632
  202. package/src/error/ClientAuthErrorCodes.ts +51 -0
  203. package/src/error/ClientConfigurationError.ts +146 -332
  204. package/src/error/ClientConfigurationErrorCodes.ts +28 -0
  205. package/src/error/InteractionRequiredAuthError.ts +60 -55
  206. package/src/error/InteractionRequiredAuthErrorCodes.ts +13 -0
  207. package/src/error/JoseHeaderError.ts +11 -31
  208. package/src/error/JoseHeaderErrorCodes.ts +7 -0
  209. package/src/index.ts +13 -1
  210. package/src/network/INetworkModule.ts +10 -7
  211. package/src/network/NetworkManager.ts +5 -5
  212. package/src/packageMetadata.ts +1 -1
  213. package/src/request/AuthenticationHeaderParser.ts +11 -8
  214. package/src/request/CommonRefreshTokenRequest.ts +3 -0
  215. package/src/request/CommonSilentFlowRequest.ts +2 -0
  216. package/src/request/RequestParameterBuilder.ts +10 -3
  217. package/src/request/RequestValidator.ts +19 -6
  218. package/src/request/ScopeSet.ts +23 -7
  219. package/src/response/ResponseHandler.ts +37 -17
  220. package/src/telemetry/performance/PerformanceClient.ts +2 -1
  221. package/src/telemetry/performance/PerformanceEvent.ts +9 -0
  222. package/src/telemetry/server/ServerTelemetryManager.ts +1 -1
  223. package/src/url/UrlString.ts +26 -16
  224. package/src/utils/Constants.ts +11 -3
  225. package/src/utils/FunctionWrappers.ts +0 -1
  226. package/src/utils/ProtocolUtils.ts +8 -12
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- /*! @azure/msal-common v14.0.3 2023-09-05 */
1
+ /*! @azure/msal-common v14.1.0 2023-10-05 */
2
2
  'use strict';
3
3
  'use strict';
4
4
 
@@ -357,12 +357,20 @@ const RegionDiscoveryOutcomes = {
357
357
  AUTO_DETECTION_REQUESTED_SUCCESSFUL: "4",
358
358
  AUTO_DETECTION_REQUESTED_FAILED: "5",
359
359
  };
360
+ /**
361
+ * Specifies the reason for fetching the access token from the identity provider
362
+ */
360
363
  const CacheOutcome = {
361
- NO_CACHE_HIT: "0",
362
- FORCE_REFRESH: "1",
364
+ // When a token is found in the cache or the cache is not supposed to be hit when making the request
365
+ NOT_APPLICABLE: "0",
366
+ // When the token request goes to the identity provider because force_refresh was set to true. Also occurs if claims were requested
367
+ FORCE_REFRESH_OR_CLAIMS: "1",
368
+ // When the token request goes to the identity provider because no cached access token exists
363
369
  NO_CACHED_ACCESS_TOKEN: "2",
370
+ // When the token request goes to the identity provider because cached access token expired
364
371
  CACHED_ACCESS_TOKEN_EXPIRED: "3",
365
- REFRESH_CACHED_ACCESS_TOKEN: "4",
372
+ // When the token request goes to the identity provider because refresh_in was used and the existing token needs to be refreshed
373
+ PROACTIVELY_REFRESHED: "4",
366
374
  };
367
375
  const JsonTypes = {
368
376
  Jwt: "JWT",
@@ -378,14 +386,35 @@ const ONE_DAY_IN_MS = 86400000;
378
386
  /**
379
387
  * AuthErrorMessage class containing string constants used by error codes and messages.
380
388
  */
389
+ const unexpectedError = "unexpected_error";
390
+ const postRequestFailed = "post_request_failed";
391
+
392
+ var AuthErrorCodes = /*#__PURE__*/Object.freeze({
393
+ __proto__: null,
394
+ postRequestFailed: postRequestFailed,
395
+ unexpectedError: unexpectedError
396
+ });
397
+
398
+ /*
399
+ * Copyright (c) Microsoft Corporation. All rights reserved.
400
+ * Licensed under the MIT License.
401
+ */
402
+ const AuthErrorMessages = {
403
+ [unexpectedError]: "Unexpected error in authentication.",
404
+ [postRequestFailed]: "Post request failed from the network, could be a 4xx/5xx or a network unavailability. Please check the exact error code for details.",
405
+ };
406
+ /**
407
+ * AuthErrorMessage class containing string constants used by error codes and messages.
408
+ * @deprecated Use AuthErrorCodes instead
409
+ */
381
410
  const AuthErrorMessage = {
382
411
  unexpectedError: {
383
- code: "unexpected_error",
384
- desc: "Unexpected error in authentication.",
412
+ code: unexpectedError,
413
+ desc: AuthErrorMessages[unexpectedError],
385
414
  },
386
415
  postRequestFailed: {
387
- code: "post_request_failed",
388
- desc: "Post request failed from the network, could be a 4xx/5xx or a network unavailability. Please check the exact error code for details.",
416
+ code: postRequestFailed,
417
+ desc: AuthErrorMessages[postRequestFailed],
389
418
  },
390
419
  };
391
420
  /**
@@ -406,22 +435,352 @@ class AuthError extends Error {
406
435
  setCorrelationId(correlationId) {
407
436
  this.correlationId = correlationId;
408
437
  }
409
- /**
410
- * Creates an error that is thrown when something unexpected happens in the library.
411
- * @param errDesc
412
- */
413
- static createUnexpectedError(errDesc) {
414
- return new AuthError(AuthErrorMessage.unexpectedError.code, `${AuthErrorMessage.unexpectedError.desc}: ${errDesc}`);
415
- }
416
- /**
417
- * Creates an error for post request failures.
418
- * @param errDesc
419
- * @returns
420
- */
421
- static createPostRequestFailed(errDesc) {
422
- return new AuthError(AuthErrorMessage.postRequestFailed.code, `${AuthErrorMessage.postRequestFailed.desc}: ${errDesc}`);
438
+ }
439
+ function createAuthError(code, additionalMessage) {
440
+ return new AuthError(code, additionalMessage
441
+ ? `${AuthErrorMessages[code]} ${additionalMessage}`
442
+ : AuthErrorMessages[code]);
443
+ }
444
+
445
+ /*
446
+ * Copyright (c) Microsoft Corporation. All rights reserved.
447
+ * Licensed under the MIT License.
448
+ */
449
+ const clientInfoDecodingError = "client_info_decoding_error";
450
+ const clientInfoEmptyError = "client_info_empty_error";
451
+ const tokenParsingError = "token_parsing_error";
452
+ const nullOrEmptyToken = "null_or_empty_token";
453
+ const endpointResolutionError = "endpoints_resolution_error";
454
+ const networkError = "network_error";
455
+ const openIdConfigError = "openid_config_error";
456
+ const hashNotDeserialized = "hash_not_deserialized";
457
+ const invalidState = "invalid_state";
458
+ const stateMismatch = "state_mismatch";
459
+ const stateNotFound = "state_not_found";
460
+ const nonceMismatch = "nonce_mismatch";
461
+ const authTimeNotFound = "auth_time_not_found";
462
+ const maxAgeTranspired = "max_age_transpired";
463
+ const multipleMatchingTokens = "multiple_matching_tokens";
464
+ const multipleMatchingAccounts = "multiple_matching_accounts";
465
+ const multipleMatchingAppMetadata = "multiple_matching_appMetadata";
466
+ const requestCannotBeMade = "request_cannot_be_made";
467
+ const cannotRemoveEmptyScope = "cannot_remove_empty_scope";
468
+ const cannotAppendScopeSet = "cannot_append_scopeset";
469
+ const emptyInputScopeSet = "empty_input_scopeset";
470
+ const deviceCodePollingCancelled = "device_code_polling_cancelled";
471
+ const deviceCodeExpired = "device_code_expired";
472
+ const deviceCodeUnknownError = "device_code_unknown_error";
473
+ const noAccountInSilentRequest = "no_account_in_silent_request";
474
+ const invalidCacheRecord = "invalid_cache_record";
475
+ const invalidCacheEnvironment = "invalid_cache_environment";
476
+ const noAccountFound = "no_account_found";
477
+ const noCryptoObject = "no_crypto_object";
478
+ const unexpectedCredentialType = "unexpected_credential_type";
479
+ const invalidAssertion = "invalid_assertion";
480
+ const invalidClientCredential = "invalid_client_credential";
481
+ const tokenRefreshRequired = "token_refresh_required";
482
+ const userTimeoutReached = "user_timeout_reached";
483
+ const tokenClaimsCnfRequiredForSignedJwt = "token_claims_cnf_required_for_signedjwt";
484
+ const authorizationCodeMissingFromServerResponse = "authorization_code_missing_from_server_response";
485
+ const bindingKeyNotRemoved = "binding_key_not_removed";
486
+ const endSessionEndpointNotSupported = "end_session_endpoint_not_supported";
487
+ const keyIdMissing = "key_id_missing";
488
+ const noNetworkConnectivity = "no_network_connectivity";
489
+ const userCanceled = "user_canceled";
490
+ const missingTenantIdError = "missing_tenant_id_error";
491
+ const methodNotImplemented = "method_not_implemented";
492
+
493
+ var ClientAuthErrorCodes = /*#__PURE__*/Object.freeze({
494
+ __proto__: null,
495
+ authTimeNotFound: authTimeNotFound,
496
+ authorizationCodeMissingFromServerResponse: authorizationCodeMissingFromServerResponse,
497
+ bindingKeyNotRemoved: bindingKeyNotRemoved,
498
+ cannotAppendScopeSet: cannotAppendScopeSet,
499
+ cannotRemoveEmptyScope: cannotRemoveEmptyScope,
500
+ clientInfoDecodingError: clientInfoDecodingError,
501
+ clientInfoEmptyError: clientInfoEmptyError,
502
+ deviceCodeExpired: deviceCodeExpired,
503
+ deviceCodePollingCancelled: deviceCodePollingCancelled,
504
+ deviceCodeUnknownError: deviceCodeUnknownError,
505
+ emptyInputScopeSet: emptyInputScopeSet,
506
+ endSessionEndpointNotSupported: endSessionEndpointNotSupported,
507
+ endpointResolutionError: endpointResolutionError,
508
+ hashNotDeserialized: hashNotDeserialized,
509
+ invalidAssertion: invalidAssertion,
510
+ invalidCacheEnvironment: invalidCacheEnvironment,
511
+ invalidCacheRecord: invalidCacheRecord,
512
+ invalidClientCredential: invalidClientCredential,
513
+ invalidState: invalidState,
514
+ keyIdMissing: keyIdMissing,
515
+ maxAgeTranspired: maxAgeTranspired,
516
+ methodNotImplemented: methodNotImplemented,
517
+ missingTenantIdError: missingTenantIdError,
518
+ multipleMatchingAccounts: multipleMatchingAccounts,
519
+ multipleMatchingAppMetadata: multipleMatchingAppMetadata,
520
+ multipleMatchingTokens: multipleMatchingTokens,
521
+ networkError: networkError,
522
+ noAccountFound: noAccountFound,
523
+ noAccountInSilentRequest: noAccountInSilentRequest,
524
+ noCryptoObject: noCryptoObject,
525
+ noNetworkConnectivity: noNetworkConnectivity,
526
+ nonceMismatch: nonceMismatch,
527
+ nullOrEmptyToken: nullOrEmptyToken,
528
+ openIdConfigError: openIdConfigError,
529
+ requestCannotBeMade: requestCannotBeMade,
530
+ stateMismatch: stateMismatch,
531
+ stateNotFound: stateNotFound,
532
+ tokenClaimsCnfRequiredForSignedJwt: tokenClaimsCnfRequiredForSignedJwt,
533
+ tokenParsingError: tokenParsingError,
534
+ tokenRefreshRequired: tokenRefreshRequired,
535
+ unexpectedCredentialType: unexpectedCredentialType,
536
+ userCanceled: userCanceled,
537
+ userTimeoutReached: userTimeoutReached
538
+ });
539
+
540
+ /*
541
+ * Copyright (c) Microsoft Corporation. All rights reserved.
542
+ * Licensed under the MIT License.
543
+ */
544
+ /**
545
+ * ClientAuthErrorMessage class containing string constants used by error codes and messages.
546
+ */
547
+ const ClientAuthErrorMessages = {
548
+ [clientInfoDecodingError]: "The client info could not be parsed/decoded correctly",
549
+ [clientInfoEmptyError]: "The client info was empty",
550
+ [tokenParsingError]: "Token cannot be parsed",
551
+ [nullOrEmptyToken]: "The token is null or empty",
552
+ [endpointResolutionError]: "Endpoints cannot be resolved",
553
+ [networkError]: "Network request failed",
554
+ [openIdConfigError]: "Could not retrieve endpoints. Check your authority and verify the .well-known/openid-configuration endpoint returns the required endpoints.",
555
+ [hashNotDeserialized]: "The hash parameters could not be deserialized",
556
+ [invalidState]: "State was not the expected format",
557
+ [stateMismatch]: "State mismatch error",
558
+ [stateNotFound]: "State not found",
559
+ [nonceMismatch]: "Nonce mismatch error",
560
+ [authTimeNotFound]: "Max Age was requested and the ID token is missing the auth_time variable." +
561
+ " auth_time is an optional claim and is not enabled by default - it must be enabled." +
562
+ " See https://aka.ms/msaljs/optional-claims for more information.",
563
+ [maxAgeTranspired]: "Max Age is set to 0, or too much time has elapsed since the last end-user authentication.",
564
+ [multipleMatchingTokens]: "The cache contains multiple tokens satisfying the requirements. " +
565
+ "Call AcquireToken again providing more requirements such as authority or account.",
566
+ [multipleMatchingAccounts]: "The cache contains multiple accounts satisfying the given parameters. Please pass more info to obtain the correct account",
567
+ [multipleMatchingAppMetadata]: "The cache contains multiple appMetadata satisfying the given parameters. Please pass more info to obtain the correct appMetadata",
568
+ [requestCannotBeMade]: "Token request cannot be made without authorization code or refresh token.",
569
+ [cannotRemoveEmptyScope]: "Cannot remove null or empty scope from ScopeSet",
570
+ [cannotAppendScopeSet]: "Cannot append ScopeSet",
571
+ [emptyInputScopeSet]: "Empty input ScopeSet cannot be processed",
572
+ [deviceCodePollingCancelled]: "Caller has cancelled token endpoint polling during device code flow by setting DeviceCodeRequest.cancel = true.",
573
+ [deviceCodeExpired]: "Device code is expired.",
574
+ [deviceCodeUnknownError]: "Device code stopped polling for unknown reasons.",
575
+ [noAccountInSilentRequest]: "Please pass an account object, silent flow is not supported without account information",
576
+ [invalidCacheRecord]: "Cache record object was null or undefined.",
577
+ [invalidCacheEnvironment]: "Invalid environment when attempting to create cache entry",
578
+ [noAccountFound]: "No account found in cache for given key.",
579
+ [noCryptoObject]: "No crypto object detected.",
580
+ [unexpectedCredentialType]: "Unexpected credential type.",
581
+ [invalidAssertion]: "Client assertion must meet requirements described in https://tools.ietf.org/html/rfc7515",
582
+ [invalidClientCredential]: "Client credential (secret, certificate, or assertion) must not be empty when creating a confidential client. An application should at most have one credential",
583
+ [tokenRefreshRequired]: "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.",
584
+ [userTimeoutReached]: "User defined timeout for device code polling reached",
585
+ [tokenClaimsCnfRequiredForSignedJwt]: "Cannot generate a POP jwt if the token_claims are not populated",
586
+ [authorizationCodeMissingFromServerResponse]: "Server response does not contain an authorization code to proceed",
587
+ [bindingKeyNotRemoved]: "Could not remove the credential's binding key from storage.",
588
+ [endSessionEndpointNotSupported]: "The provided authority does not support logout",
589
+ [keyIdMissing]: "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.",
590
+ [noNetworkConnectivity]: "No network connectivity. Check your internet connection.",
591
+ [userCanceled]: "User cancelled the flow.",
592
+ [missingTenantIdError]: "A tenant id - not common, organizations, or consumers - must be specified when using the client_credentials flow.",
593
+ [methodNotImplemented]: "This method has not been implemented",
594
+ };
595
+ /**
596
+ * String constants used by error codes and messages.
597
+ * @deprecated Use ClientAuthErrorCodes instead
598
+ */
599
+ const ClientAuthErrorMessage = {
600
+ clientInfoDecodingError: {
601
+ code: clientInfoDecodingError,
602
+ desc: ClientAuthErrorMessages[clientInfoDecodingError],
603
+ },
604
+ clientInfoEmptyError: {
605
+ code: clientInfoEmptyError,
606
+ desc: ClientAuthErrorMessages[clientInfoEmptyError],
607
+ },
608
+ tokenParsingError: {
609
+ code: tokenParsingError,
610
+ desc: ClientAuthErrorMessages[tokenParsingError],
611
+ },
612
+ nullOrEmptyToken: {
613
+ code: nullOrEmptyToken,
614
+ desc: ClientAuthErrorMessages[nullOrEmptyToken],
615
+ },
616
+ endpointResolutionError: {
617
+ code: endpointResolutionError,
618
+ desc: ClientAuthErrorMessages[endpointResolutionError],
619
+ },
620
+ networkError: {
621
+ code: networkError,
622
+ desc: ClientAuthErrorMessages[networkError],
623
+ },
624
+ unableToGetOpenidConfigError: {
625
+ code: openIdConfigError,
626
+ desc: ClientAuthErrorMessages[openIdConfigError],
627
+ },
628
+ hashNotDeserialized: {
629
+ code: hashNotDeserialized,
630
+ desc: ClientAuthErrorMessages[hashNotDeserialized],
631
+ },
632
+ invalidStateError: {
633
+ code: invalidState,
634
+ desc: ClientAuthErrorMessages[invalidState],
635
+ },
636
+ stateMismatchError: {
637
+ code: stateMismatch,
638
+ desc: ClientAuthErrorMessages[stateMismatch],
639
+ },
640
+ stateNotFoundError: {
641
+ code: stateNotFound,
642
+ desc: ClientAuthErrorMessages[stateNotFound],
643
+ },
644
+ nonceMismatchError: {
645
+ code: nonceMismatch,
646
+ desc: ClientAuthErrorMessages[nonceMismatch],
647
+ },
648
+ authTimeNotFoundError: {
649
+ code: authTimeNotFound,
650
+ desc: ClientAuthErrorMessages[authTimeNotFound],
651
+ },
652
+ maxAgeTranspired: {
653
+ code: maxAgeTranspired,
654
+ desc: ClientAuthErrorMessages[maxAgeTranspired],
655
+ },
656
+ multipleMatchingTokens: {
657
+ code: multipleMatchingTokens,
658
+ desc: ClientAuthErrorMessages[multipleMatchingTokens],
659
+ },
660
+ multipleMatchingAccounts: {
661
+ code: multipleMatchingAccounts,
662
+ desc: ClientAuthErrorMessages[multipleMatchingAccounts],
663
+ },
664
+ multipleMatchingAppMetadata: {
665
+ code: multipleMatchingAppMetadata,
666
+ desc: ClientAuthErrorMessages[multipleMatchingAppMetadata],
667
+ },
668
+ tokenRequestCannotBeMade: {
669
+ code: requestCannotBeMade,
670
+ desc: ClientAuthErrorMessages[requestCannotBeMade],
671
+ },
672
+ removeEmptyScopeError: {
673
+ code: cannotRemoveEmptyScope,
674
+ desc: ClientAuthErrorMessages[cannotRemoveEmptyScope],
675
+ },
676
+ appendScopeSetError: {
677
+ code: cannotAppendScopeSet,
678
+ desc: ClientAuthErrorMessages[cannotAppendScopeSet],
679
+ },
680
+ emptyInputScopeSetError: {
681
+ code: emptyInputScopeSet,
682
+ desc: ClientAuthErrorMessages[emptyInputScopeSet],
683
+ },
684
+ DeviceCodePollingCancelled: {
685
+ code: deviceCodePollingCancelled,
686
+ desc: ClientAuthErrorMessages[deviceCodePollingCancelled],
687
+ },
688
+ DeviceCodeExpired: {
689
+ code: deviceCodeExpired,
690
+ desc: ClientAuthErrorMessages[deviceCodeExpired],
691
+ },
692
+ DeviceCodeUnknownError: {
693
+ code: deviceCodeUnknownError,
694
+ desc: ClientAuthErrorMessages[deviceCodeUnknownError],
695
+ },
696
+ NoAccountInSilentRequest: {
697
+ code: noAccountInSilentRequest,
698
+ desc: ClientAuthErrorMessages[noAccountInSilentRequest],
699
+ },
700
+ invalidCacheRecord: {
701
+ code: invalidCacheRecord,
702
+ desc: ClientAuthErrorMessages[invalidCacheRecord],
703
+ },
704
+ invalidCacheEnvironment: {
705
+ code: invalidCacheEnvironment,
706
+ desc: ClientAuthErrorMessages[invalidCacheEnvironment],
707
+ },
708
+ noAccountFound: {
709
+ code: noAccountFound,
710
+ desc: ClientAuthErrorMessages[noAccountFound],
711
+ },
712
+ noCryptoObj: {
713
+ code: noCryptoObject,
714
+ desc: ClientAuthErrorMessages[noCryptoObject],
715
+ },
716
+ unexpectedCredentialType: {
717
+ code: unexpectedCredentialType,
718
+ desc: ClientAuthErrorMessages[unexpectedCredentialType],
719
+ },
720
+ invalidAssertion: {
721
+ code: invalidAssertion,
722
+ desc: ClientAuthErrorMessages[invalidAssertion],
723
+ },
724
+ invalidClientCredential: {
725
+ code: invalidClientCredential,
726
+ desc: ClientAuthErrorMessages[invalidClientCredential],
727
+ },
728
+ tokenRefreshRequired: {
729
+ code: tokenRefreshRequired,
730
+ desc: ClientAuthErrorMessages[tokenRefreshRequired],
731
+ },
732
+ userTimeoutReached: {
733
+ code: userTimeoutReached,
734
+ desc: ClientAuthErrorMessages[userTimeoutReached],
735
+ },
736
+ tokenClaimsRequired: {
737
+ code: tokenClaimsCnfRequiredForSignedJwt,
738
+ desc: ClientAuthErrorMessages[tokenClaimsCnfRequiredForSignedJwt],
739
+ },
740
+ noAuthorizationCodeFromServer: {
741
+ code: authorizationCodeMissingFromServerResponse,
742
+ desc: ClientAuthErrorMessages[authorizationCodeMissingFromServerResponse],
743
+ },
744
+ bindingKeyNotRemovedError: {
745
+ code: bindingKeyNotRemoved,
746
+ desc: ClientAuthErrorMessages[bindingKeyNotRemoved],
747
+ },
748
+ logoutNotSupported: {
749
+ code: endSessionEndpointNotSupported,
750
+ desc: ClientAuthErrorMessages[endSessionEndpointNotSupported],
751
+ },
752
+ keyIdMissing: {
753
+ code: keyIdMissing,
754
+ desc: ClientAuthErrorMessages[keyIdMissing],
755
+ },
756
+ noNetworkConnectivity: {
757
+ code: noNetworkConnectivity,
758
+ desc: ClientAuthErrorMessages[noNetworkConnectivity],
759
+ },
760
+ userCanceledError: {
761
+ code: userCanceled,
762
+ desc: ClientAuthErrorMessages[userCanceled],
763
+ },
764
+ missingTenantIdError: {
765
+ code: missingTenantIdError,
766
+ desc: ClientAuthErrorMessages[missingTenantIdError],
767
+ },
768
+ };
769
+ /**
770
+ * Error thrown when there is an error in the client code running on the browser.
771
+ */
772
+ class ClientAuthError extends AuthError {
773
+ constructor(errorCode, additionalMessage) {
774
+ super(errorCode, additionalMessage
775
+ ? `${ClientAuthErrorMessages[errorCode]}: ${additionalMessage}`
776
+ : ClientAuthErrorMessages[errorCode]);
777
+ this.name = "ClientAuthError";
778
+ Object.setPrototypeOf(this, ClientAuthError.prototype);
423
779
  }
424
780
  }
781
+ function createClientAuthError(errorCode, additionalMessage) {
782
+ return new ClientAuthError(errorCode, additionalMessage);
783
+ }
425
784
 
426
785
  /*
427
786
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -429,40 +788,28 @@ class AuthError extends Error {
429
788
  */
430
789
  const DEFAULT_CRYPTO_IMPLEMENTATION = {
431
790
  createNewGuid: () => {
432
- const notImplErr = "Crypto interface - createNewGuid() has not been implemented";
433
- throw AuthError.createUnexpectedError(notImplErr);
791
+ throw createClientAuthError(methodNotImplemented);
434
792
  },
435
793
  base64Decode: () => {
436
- const notImplErr = "Crypto interface - base64Decode() has not been implemented";
437
- throw AuthError.createUnexpectedError(notImplErr);
794
+ throw createClientAuthError(methodNotImplemented);
438
795
  },
439
796
  base64Encode: () => {
440
- const notImplErr = "Crypto interface - base64Encode() has not been implemented";
441
- throw AuthError.createUnexpectedError(notImplErr);
442
- },
443
- async generatePkceCodes() {
444
- const notImplErr = "Crypto interface - generatePkceCodes() has not been implemented";
445
- throw AuthError.createUnexpectedError(notImplErr);
797
+ throw createClientAuthError(methodNotImplemented);
446
798
  },
447
799
  async getPublicKeyThumbprint() {
448
- const notImplErr = "Crypto interface - getPublicKeyThumbprint() has not been implemented";
449
- throw AuthError.createUnexpectedError(notImplErr);
800
+ throw createClientAuthError(methodNotImplemented);
450
801
  },
451
802
  async removeTokenBindingKey() {
452
- const notImplErr = "Crypto interface - removeTokenBindingKey() has not been implemented";
453
- throw AuthError.createUnexpectedError(notImplErr);
803
+ throw createClientAuthError(methodNotImplemented);
454
804
  },
455
805
  async clearKeystore() {
456
- const notImplErr = "Crypto interface - clearKeystore() has not been implemented";
457
- throw AuthError.createUnexpectedError(notImplErr);
806
+ throw createClientAuthError(methodNotImplemented);
458
807
  },
459
808
  async signJwt() {
460
- const notImplErr = "Crypto interface - signJwt() has not been implemented";
461
- throw AuthError.createUnexpectedError(notImplErr);
809
+ throw createClientAuthError(methodNotImplemented);
462
810
  },
463
811
  async hashString() {
464
- const notImplErr = "Crypto interface - hashString() has not been implemented";
465
- throw AuthError.createUnexpectedError(notImplErr);
812
+ throw createClientAuthError(methodNotImplemented);
466
813
  },
467
814
  };
468
815
 
@@ -657,7 +1004,7 @@ class Logger {
657
1004
 
658
1005
  /* eslint-disable header/header */
659
1006
  const name = "@azure/msal-common";
660
- const version = "14.0.3";
1007
+ const version = "14.1.0";
661
1008
 
662
1009
  /*
663
1010
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -682,800 +1029,189 @@ const AzureCloudInstance = {
682
1029
  * Copyright (c) Microsoft Corporation. All rights reserved.
683
1030
  * Licensed under the MIT License.
684
1031
  */
685
- /**
686
- * ClientAuthErrorMessage class containing string constants used by error codes and messages.
687
- */
688
- const ClientAuthErrorMessage = {
689
- clientInfoDecodingError: {
690
- code: "client_info_decoding_error",
691
- desc: "The client info could not be parsed/decoded correctly. Please review the trace to determine the root cause.",
692
- },
693
- clientInfoEmptyError: {
694
- code: "client_info_empty_error",
695
- desc: "The client info was empty. Please review the trace to determine the root cause.",
696
- },
697
- tokenParsingError: {
698
- code: "token_parsing_error",
699
- desc: "Token cannot be parsed. Please review stack trace to determine root cause.",
700
- },
701
- nullOrEmptyToken: {
702
- code: "null_or_empty_token",
703
- desc: "The token is null or empty. Please review the trace to determine the root cause.",
704
- },
705
- endpointResolutionError: {
706
- code: "endpoints_resolution_error",
707
- desc: "Error: could not resolve endpoints. Please check network and try again.",
708
- },
709
- networkError: {
710
- code: "network_error",
711
- desc: "Network request failed. Please check network trace to determine root cause.",
712
- },
713
- unableToGetOpenidConfigError: {
714
- code: "openid_config_error",
715
- desc: "Could not retrieve endpoints. Check your authority and verify the .well-known/openid-configuration endpoint returns the required endpoints.",
716
- },
717
- hashNotDeserialized: {
718
- code: "hash_not_deserialized",
719
- desc: "The hash parameters could not be deserialized. Please review the trace to determine the root cause.",
720
- },
721
- blankGuidGenerated: {
722
- code: "blank_guid_generated",
723
- desc: "The guid generated was blank. Please review the trace to determine the root cause.",
724
- },
725
- invalidStateError: {
726
- code: "invalid_state",
727
- desc: "State was not the expected format. Please check the logs to determine whether the request was sent using ProtocolUtils.setRequestState().",
728
- },
729
- stateMismatchError: {
730
- code: "state_mismatch",
731
- desc: "State mismatch error. Please check your network. Continued requests may cause cache overflow.",
732
- },
733
- stateNotFoundError: {
734
- code: "state_not_found",
735
- desc: "State not found",
736
- },
737
- nonceMismatchError: {
738
- code: "nonce_mismatch",
739
- desc: "Nonce mismatch error. This may be caused by a race condition in concurrent requests.",
740
- },
741
- nonceNotFoundError: {
742
- code: "nonce_not_found",
743
- desc: "nonce not found",
744
- },
745
- authTimeNotFoundError: {
746
- code: "auth_time_not_found",
747
- desc: "Max Age was requested and the ID token is missing the auth_time variable." +
748
- " auth_time is an optional claim and is not enabled by default - it must be enabled." +
749
- " See https://aka.ms/msaljs/optional-claims for more information.",
750
- },
751
- maxAgeTranspiredError: {
752
- code: "max_age_transpired",
753
- desc: "Max Age is set to 0, or too much time has elapsed since the last end-user authentication.",
754
- },
755
- noTokensFoundError: {
756
- code: "no_tokens_found",
757
- 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().",
758
- },
759
- multipleMatchingTokens: {
760
- code: "multiple_matching_tokens",
761
- desc: "The cache contains multiple tokens satisfying the requirements. " +
762
- "Call AcquireToken again providing more requirements such as authority or account.",
763
- },
764
- multipleMatchingAccounts: {
765
- code: "multiple_matching_accounts",
766
- desc: "The cache contains multiple accounts satisfying the given parameters. Please pass more info to obtain the correct account",
767
- },
768
- multipleMatchingAppMetadata: {
769
- code: "multiple_matching_appMetadata",
770
- desc: "The cache contains multiple appMetadata satisfying the given parameters. Please pass more info to obtain the correct appMetadata",
771
- },
772
- tokenRequestCannotBeMade: {
773
- code: "request_cannot_be_made",
774
- desc: "Token request cannot be made without authorization code or refresh token.",
775
- },
776
- appendEmptyScopeError: {
777
- code: "cannot_append_empty_scope",
778
- desc: "Cannot append null or empty scope to ScopeSet. Please check the stack trace for more info.",
779
- },
780
- removeEmptyScopeError: {
781
- code: "cannot_remove_empty_scope",
782
- desc: "Cannot remove null or empty scope from ScopeSet. Please check the stack trace for more info.",
783
- },
784
- appendScopeSetError: {
785
- code: "cannot_append_scopeset",
786
- desc: "Cannot append ScopeSet due to error.",
787
- },
788
- emptyInputScopeSetError: {
789
- code: "empty_input_scopeset",
790
- desc: "Empty input ScopeSet cannot be processed.",
791
- },
792
- DeviceCodePollingCancelled: {
793
- code: "device_code_polling_cancelled",
794
- desc: "Caller has cancelled token endpoint polling during device code flow by setting DeviceCodeRequest.cancel = true.",
795
- },
796
- DeviceCodeExpired: {
797
- code: "device_code_expired",
798
- desc: "Device code is expired.",
799
- },
800
- DeviceCodeUnknownError: {
801
- code: "device_code_unknown_error",
802
- desc: "Device code stopped polling for unknown reasons.",
803
- },
804
- NoAccountInSilentRequest: {
805
- code: "no_account_in_silent_request",
806
- desc: "Please pass an account object, silent flow is not supported without account information",
807
- },
808
- invalidCacheRecord: {
809
- code: "invalid_cache_record",
810
- desc: "Cache record object was null or undefined.",
811
- },
812
- invalidCacheEnvironment: {
813
- code: "invalid_cache_environment",
814
- desc: "Invalid environment when attempting to create cache entry",
815
- },
816
- noAccountFound: {
817
- code: "no_account_found",
818
- desc: "No account found in cache for given key.",
819
- },
820
- CachePluginError: {
821
- code: "no cache plugin set on CacheManager",
822
- desc: "ICachePlugin needs to be set before using readFromStorage or writeFromStorage",
823
- },
824
- noCryptoObj: {
825
- code: "no_crypto_object",
826
- desc: "No crypto object detected. This is required for the following operation: ",
827
- },
828
- invalidCacheType: {
829
- code: "invalid_cache_type",
830
- desc: "Invalid cache type",
831
- },
832
- unexpectedAccountType: {
833
- code: "unexpected_account_type",
834
- desc: "Unexpected account type.",
835
- },
836
- unexpectedCredentialType: {
837
- code: "unexpected_credential_type",
838
- desc: "Unexpected credential type.",
839
- },
840
- invalidAssertion: {
841
- code: "invalid_assertion",
842
- desc: "Client assertion must meet requirements described in https://tools.ietf.org/html/rfc7515",
843
- },
844
- invalidClientCredential: {
845
- code: "invalid_client_credential",
846
- desc: "Client credential (secret, certificate, or assertion) must not be empty when creating a confidential client. An application should at most have one credential",
847
- },
848
- tokenRefreshRequired: {
849
- code: "token_refresh_required",
850
- 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.",
851
- },
852
- userTimeoutReached: {
853
- code: "user_timeout_reached",
854
- desc: "User defined timeout for device code polling reached",
855
- },
856
- tokenClaimsRequired: {
857
- code: "token_claims_cnf_required_for_signedjwt",
858
- desc: "Cannot generate a POP jwt if the token_claims are not populated",
859
- },
860
- noAuthorizationCodeFromServer: {
861
- code: "authorization_code_missing_from_server_response",
862
- desc: "Server response does not contain an authorization code to proceed",
863
- },
864
- noAzureRegionDetected: {
865
- code: "no_azure_region_detected",
866
- desc: "No azure region was detected and no fallback was made available",
867
- },
868
- accessTokenEntityNullError: {
869
- code: "access_token_entity_null",
870
- desc: "Access token entity is null, please check logs and cache to ensure a valid access token is present.",
871
- },
872
- bindingKeyNotRemovedError: {
873
- code: "binding_key_not_removed",
874
- desc: "Could not remove the credential's binding key from storage.",
875
- },
876
- logoutNotSupported: {
877
- code: "end_session_endpoint_not_supported",
878
- desc: "Provided authority does not support logout.",
879
- },
880
- keyIdMissing: {
881
- code: "key_id_missing",
882
- 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.",
883
- },
884
- noNetworkConnectivity: {
885
- code: "no_network_connectivity",
886
- desc: "No network connectivity. Check your internet connection.",
887
- },
888
- userCanceledError: {
889
- code: "user_canceled",
890
- desc: "User canceled the flow.",
891
- },
892
- missingTenantIdError: {
893
- code: "missing_tenant_id_error",
894
- desc: "A tenant id - not common, organizations, or consumers - must be specified when using the client_credentials flow.",
895
- },
896
- };
897
- /**
898
- * Error thrown when there is an error in the client code running on the browser.
899
- */
900
- class ClientAuthError extends AuthError {
901
- constructor(errorCode, errorMessage) {
902
- super(errorCode, errorMessage);
903
- this.name = "ClientAuthError";
904
- Object.setPrototypeOf(this, ClientAuthError.prototype);
905
- }
906
- /**
907
- * Creates an error thrown when client info object doesn't decode correctly.
908
- * @param caughtError
909
- */
910
- static createClientInfoDecodingError(caughtError) {
911
- return new ClientAuthError(ClientAuthErrorMessage.clientInfoDecodingError.code, `${ClientAuthErrorMessage.clientInfoDecodingError.desc} Failed with error: ${caughtError}`);
912
- }
913
- /**
914
- * Creates an error thrown if the client info is empty.
915
- * @param rawClientInfo
916
- */
917
- static createClientInfoEmptyError() {
918
- return new ClientAuthError(ClientAuthErrorMessage.clientInfoEmptyError.code, `${ClientAuthErrorMessage.clientInfoEmptyError.desc}`);
919
- }
920
- /**
921
- * Creates an error thrown when the id token extraction errors out.
922
- * @param err
923
- */
924
- static createTokenParsingError(caughtExtractionError) {
925
- return new ClientAuthError(ClientAuthErrorMessage.tokenParsingError.code, `${ClientAuthErrorMessage.tokenParsingError.desc} Failed with error: ${caughtExtractionError}`);
926
- }
927
- /**
928
- * Creates an error thrown when the id token string is null or empty.
929
- * @param invalidRawTokenString
930
- */
931
- static createTokenNullOrEmptyError(invalidRawTokenString) {
932
- return new ClientAuthError(ClientAuthErrorMessage.nullOrEmptyToken.code, `${ClientAuthErrorMessage.nullOrEmptyToken.desc} Raw Token Value: ${invalidRawTokenString}`);
933
- }
934
- /**
935
- * Creates an error thrown when the endpoint discovery doesn't complete correctly.
936
- */
937
- static createEndpointDiscoveryIncompleteError(errDetail) {
938
- return new ClientAuthError(ClientAuthErrorMessage.endpointResolutionError.code, `${ClientAuthErrorMessage.endpointResolutionError.desc} Detail: ${errDetail}`);
939
- }
940
- /**
941
- * Creates an error thrown when the fetch client throws
942
- */
943
- static createNetworkError(endpoint, errDetail) {
944
- return new ClientAuthError(ClientAuthErrorMessage.networkError.code, `${ClientAuthErrorMessage.networkError.desc} | Fetch client threw: ${errDetail} | Attempted to reach: ${endpoint.split("?")[0]}`);
945
- }
946
- /**
947
- * Creates an error thrown when the openid-configuration endpoint cannot be reached or does not contain the required data
948
- */
949
- static createUnableToGetOpenidConfigError(errDetail) {
950
- return new ClientAuthError(ClientAuthErrorMessage.unableToGetOpenidConfigError.code, `${ClientAuthErrorMessage.unableToGetOpenidConfigError.desc} Attempted to retrieve endpoints from: ${errDetail}`);
951
- }
952
- /**
953
- * Creates an error thrown when the hash cannot be deserialized.
954
- * @param hashParamObj
955
- */
956
- static createHashNotDeserializedError(hashParamObj) {
957
- return new ClientAuthError(ClientAuthErrorMessage.hashNotDeserialized.code, `${ClientAuthErrorMessage.hashNotDeserialized.desc} Given Object: ${hashParamObj}`);
958
- }
959
- /**
960
- * Creates an error thrown when the state cannot be parsed.
961
- * @param invalidState
962
- */
963
- static createInvalidStateError(invalidState, errorString) {
964
- return new ClientAuthError(ClientAuthErrorMessage.invalidStateError.code, `${ClientAuthErrorMessage.invalidStateError.desc} Invalid State: ${invalidState}, Root Err: ${errorString}`);
965
- }
966
- /**
967
- * Creates an error thrown when two states do not match.
968
- */
969
- static createStateMismatchError() {
970
- return new ClientAuthError(ClientAuthErrorMessage.stateMismatchError.code, ClientAuthErrorMessage.stateMismatchError.desc);
971
- }
972
- /**
973
- * Creates an error thrown when the state is not present
974
- * @param missingState
975
- */
976
- static createStateNotFoundError(missingState) {
977
- return new ClientAuthError(ClientAuthErrorMessage.stateNotFoundError.code, `${ClientAuthErrorMessage.stateNotFoundError.desc}: ${missingState}`);
978
- }
979
- /**
980
- * Creates an error thrown when the nonce does not match.
981
- */
982
- static createNonceMismatchError() {
983
- return new ClientAuthError(ClientAuthErrorMessage.nonceMismatchError.code, ClientAuthErrorMessage.nonceMismatchError.desc);
984
- }
985
- /**
986
- * Creates an error thrown when max_age was provided in the request, but auth_time is not in the token claims
987
- * @param missingNonce
988
- */
989
- static createAuthTimeNotFoundError() {
990
- return new ClientAuthError(ClientAuthErrorMessage.authTimeNotFoundError.code, ClientAuthErrorMessage.authTimeNotFoundError.desc);
991
- }
992
- /**
993
- * Creates an error thrown when too much time has elapsed since the last end-user authentication
994
- */
995
- static createMaxAgeTranspiredError() {
996
- return new ClientAuthError(ClientAuthErrorMessage.maxAgeTranspiredError.code, ClientAuthErrorMessage.maxAgeTranspiredError.desc);
997
- }
998
- /**
999
- * Creates an error thrown when the mnonce is not present
1000
- * @param missingNonce
1001
- */
1002
- static createNonceNotFoundError(missingNonce) {
1003
- return new ClientAuthError(ClientAuthErrorMessage.nonceNotFoundError.code, `${ClientAuthErrorMessage.nonceNotFoundError.desc}: ${missingNonce}`);
1004
- }
1005
- /**
1006
- * Throws error when multiple tokens are in cache.
1007
- */
1008
- static createMultipleMatchingTokensInCacheError() {
1009
- return new ClientAuthError(ClientAuthErrorMessage.multipleMatchingTokens.code, `${ClientAuthErrorMessage.multipleMatchingTokens.desc}.`);
1010
- }
1011
- /**
1012
- * Throws error when multiple accounts are in cache for the given params
1013
- */
1014
- static createMultipleMatchingAccountsInCacheError() {
1015
- return new ClientAuthError(ClientAuthErrorMessage.multipleMatchingAccounts.code, ClientAuthErrorMessage.multipleMatchingAccounts.desc);
1016
- }
1017
- /**
1018
- * Throws error when multiple appMetada are in cache for the given clientId.
1019
- */
1020
- static createMultipleMatchingAppMetadataInCacheError() {
1021
- return new ClientAuthError(ClientAuthErrorMessage.multipleMatchingAppMetadata.code, ClientAuthErrorMessage.multipleMatchingAppMetadata.desc);
1022
- }
1023
- /**
1024
- * Throws error when no auth code or refresh token is given to ServerTokenRequestParameters.
1025
- */
1026
- static createTokenRequestCannotBeMadeError() {
1027
- return new ClientAuthError(ClientAuthErrorMessage.tokenRequestCannotBeMade.code, ClientAuthErrorMessage.tokenRequestCannotBeMade.desc);
1028
- }
1029
- /**
1030
- * Throws error when attempting to append a null, undefined or empty scope to a set
1031
- * @param givenScope
1032
- */
1033
- static createAppendEmptyScopeToSetError(givenScope) {
1034
- return new ClientAuthError(ClientAuthErrorMessage.appendEmptyScopeError.code, `${ClientAuthErrorMessage.appendEmptyScopeError.desc} Given Scope: ${givenScope}`);
1035
- }
1036
- /**
1037
- * Throws error when attempting to append a null, undefined or empty scope to a set
1038
- * @param givenScope
1039
- */
1040
- static createRemoveEmptyScopeFromSetError(givenScope) {
1041
- return new ClientAuthError(ClientAuthErrorMessage.removeEmptyScopeError.code, `${ClientAuthErrorMessage.removeEmptyScopeError.desc} Given Scope: ${givenScope}`);
1042
- }
1043
- /**
1044
- * Throws error when attempting to append null or empty ScopeSet.
1045
- * @param appendError
1046
- */
1047
- static createAppendScopeSetError(appendError) {
1048
- return new ClientAuthError(ClientAuthErrorMessage.appendScopeSetError.code, `${ClientAuthErrorMessage.appendScopeSetError.desc} Detail Error: ${appendError}`);
1049
- }
1050
- /**
1051
- * Throws error if ScopeSet is null or undefined.
1052
- * @param givenScopeSet
1053
- */
1054
- static createEmptyInputScopeSetError() {
1055
- return new ClientAuthError(ClientAuthErrorMessage.emptyInputScopeSetError.code, `${ClientAuthErrorMessage.emptyInputScopeSetError.desc}`);
1056
- }
1057
- /**
1058
- * Throws error if user sets CancellationToken.cancel = true during polling of token endpoint during device code flow
1059
- */
1060
- static createDeviceCodeCancelledError() {
1061
- return new ClientAuthError(ClientAuthErrorMessage.DeviceCodePollingCancelled.code, `${ClientAuthErrorMessage.DeviceCodePollingCancelled.desc}`);
1062
- }
1063
- /**
1064
- * Throws error if device code is expired
1065
- */
1066
- static createDeviceCodeExpiredError() {
1067
- return new ClientAuthError(ClientAuthErrorMessage.DeviceCodeExpired.code, `${ClientAuthErrorMessage.DeviceCodeExpired.desc}`);
1068
- }
1069
- /**
1070
- * Throws error if device code is expired
1071
- */
1072
- static createDeviceCodeUnknownError() {
1073
- return new ClientAuthError(ClientAuthErrorMessage.DeviceCodeUnknownError.code, `${ClientAuthErrorMessage.DeviceCodeUnknownError.desc}`);
1074
- }
1075
- /**
1076
- * Throws error when silent requests are made without an account object
1077
- */
1078
- static createNoAccountInSilentRequestError() {
1079
- return new ClientAuthError(ClientAuthErrorMessage.NoAccountInSilentRequest.code, `${ClientAuthErrorMessage.NoAccountInSilentRequest.desc}`);
1080
- }
1081
- /**
1082
- * Throws error when cache record is null or undefined.
1083
- */
1084
- static createNullOrUndefinedCacheRecord() {
1085
- return new ClientAuthError(ClientAuthErrorMessage.invalidCacheRecord.code, ClientAuthErrorMessage.invalidCacheRecord.desc);
1086
- }
1087
- /**
1088
- * Throws error when provided environment is not part of the CloudDiscoveryMetadata object
1089
- */
1090
- static createInvalidCacheEnvironmentError() {
1091
- return new ClientAuthError(ClientAuthErrorMessage.invalidCacheEnvironment.code, ClientAuthErrorMessage.invalidCacheEnvironment.desc);
1092
- }
1093
- /**
1094
- * Throws error when account is not found in cache.
1095
- */
1096
- static createNoAccountFoundError() {
1097
- return new ClientAuthError(ClientAuthErrorMessage.noAccountFound.code, ClientAuthErrorMessage.noAccountFound.desc);
1098
- }
1099
- /**
1100
- * Throws error if ICachePlugin not set on CacheManager.
1101
- */
1102
- static createCachePluginError() {
1103
- return new ClientAuthError(ClientAuthErrorMessage.CachePluginError.code, `${ClientAuthErrorMessage.CachePluginError.desc}`);
1104
- }
1105
- /**
1106
- * Throws error if crypto object not found.
1107
- * @param operationName
1108
- */
1109
- static createNoCryptoObjectError(operationName) {
1110
- return new ClientAuthError(ClientAuthErrorMessage.noCryptoObj.code, `${ClientAuthErrorMessage.noCryptoObj.desc}${operationName}`);
1111
- }
1112
- /**
1113
- * Throws error if cache type is invalid.
1114
- */
1115
- static createInvalidCacheTypeError() {
1116
- return new ClientAuthError(ClientAuthErrorMessage.invalidCacheType.code, `${ClientAuthErrorMessage.invalidCacheType.desc}`);
1117
- }
1118
- /**
1119
- * Throws error if unexpected account type.
1120
- */
1121
- static createUnexpectedAccountTypeError() {
1122
- return new ClientAuthError(ClientAuthErrorMessage.unexpectedAccountType.code, `${ClientAuthErrorMessage.unexpectedAccountType.desc}`);
1123
- }
1124
- /**
1125
- * Throws error if unexpected credential type.
1126
- */
1127
- static createUnexpectedCredentialTypeError() {
1128
- return new ClientAuthError(ClientAuthErrorMessage.unexpectedCredentialType.code, `${ClientAuthErrorMessage.unexpectedCredentialType.desc}`);
1129
- }
1130
- /**
1131
- * Throws error if client assertion is not valid.
1132
- */
1133
- static createInvalidAssertionError() {
1134
- return new ClientAuthError(ClientAuthErrorMessage.invalidAssertion.code, `${ClientAuthErrorMessage.invalidAssertion.desc}`);
1135
- }
1136
- /**
1137
- * Throws error if client assertion is not valid.
1138
- */
1139
- static createInvalidCredentialError() {
1140
- return new ClientAuthError(ClientAuthErrorMessage.invalidClientCredential.code, `${ClientAuthErrorMessage.invalidClientCredential.desc}`);
1141
- }
1142
- /**
1143
- * Throws error if token cannot be retrieved from cache due to refresh being required.
1144
- */
1145
- static createRefreshRequiredError() {
1146
- return new ClientAuthError(ClientAuthErrorMessage.tokenRefreshRequired.code, ClientAuthErrorMessage.tokenRefreshRequired.desc);
1147
- }
1148
- /**
1149
- * Throws error if the user defined timeout is reached.
1150
- */
1151
- static createUserTimeoutReachedError() {
1152
- return new ClientAuthError(ClientAuthErrorMessage.userTimeoutReached.code, ClientAuthErrorMessage.userTimeoutReached.desc);
1153
- }
1154
- /*
1155
- * Throws error if token claims are not populated for a signed jwt generation
1156
- */
1157
- static createTokenClaimsRequiredError() {
1158
- return new ClientAuthError(ClientAuthErrorMessage.tokenClaimsRequired.code, ClientAuthErrorMessage.tokenClaimsRequired.desc);
1159
- }
1160
- /**
1161
- * Throws error when the authorization code is missing from the server response
1162
- */
1163
- static createNoAuthCodeInServerResponseError() {
1164
- return new ClientAuthError(ClientAuthErrorMessage.noAuthorizationCodeFromServer.code, ClientAuthErrorMessage.noAuthorizationCodeFromServer.desc);
1165
- }
1166
- static createBindingKeyNotRemovedError() {
1167
- return new ClientAuthError(ClientAuthErrorMessage.bindingKeyNotRemovedError.code, ClientAuthErrorMessage.bindingKeyNotRemovedError.desc);
1168
- }
1169
- /**
1170
- * Thrown when logout is attempted for an authority that doesnt have an end_session_endpoint
1171
- */
1172
- static createLogoutNotSupportedError() {
1173
- return new ClientAuthError(ClientAuthErrorMessage.logoutNotSupported.code, ClientAuthErrorMessage.logoutNotSupported.desc);
1174
- }
1175
- /**
1176
- * Create an error when kid attribute is missing from a PoP token's cache record
1177
- */
1178
- static createKeyIdMissingError() {
1179
- return new ClientAuthError(ClientAuthErrorMessage.keyIdMissing.code, ClientAuthErrorMessage.keyIdMissing.desc);
1180
- }
1181
- /**
1182
- * Create an error when the client does not have network connectivity
1183
- */
1184
- static createNoNetworkConnectivityError() {
1185
- return new ClientAuthError(ClientAuthErrorMessage.noNetworkConnectivity.code, ClientAuthErrorMessage.noNetworkConnectivity.desc);
1186
- }
1187
- /**
1188
- * Create an error when the user cancels the flow
1189
- */
1190
- static createUserCanceledError() {
1191
- return new ClientAuthError(ClientAuthErrorMessage.userCanceledError.code, ClientAuthErrorMessage.userCanceledError.desc);
1192
- }
1193
- /**
1194
- * Creates an error for during acquireTokenByClientCredential when TenantId is set to "common" or "organizations"
1195
- */
1196
- static createMissingTenantIdError() {
1197
- return new AuthError(ClientAuthErrorMessage.missingTenantIdError.code, ClientAuthErrorMessage.missingTenantIdError.desc);
1198
- }
1199
- }
1032
+ const redirectUriEmpty = "redirect_uri_empty";
1033
+ const claimsRequestParsingError = "claims_request_parsing_error";
1034
+ const authorityUriInsecure = "authority_uri_insecure";
1035
+ const urlParseError = "url_parse_error";
1036
+ const urlEmptyError = "empty_url_error";
1037
+ const emptyInputScopesError = "empty_input_scopes_error";
1038
+ const invalidPromptValue = "invalid_prompt_value";
1039
+ const invalidClaims = "invalid_claims";
1040
+ const tokenRequestEmpty = "token_request_empty";
1041
+ const logoutRequestEmpty = "logout_request_empty";
1042
+ const invalidCodeChallengeMethod = "invalid_code_challenge_method";
1043
+ const pkceParamsMissing = "pkce_params_missing";
1044
+ const invalidCloudDiscoveryMetadata = "invalid_cloud_discovery_metadata";
1045
+ const invalidAuthorityMetadata = "invalid_authority_metadata";
1046
+ const untrustedAuthority = "untrusted_authority";
1047
+ const missingSshJwk = "missing_ssh_jwk";
1048
+ const missingSshKid = "missing_ssh_kid";
1049
+ const missingNonceAuthenticationHeader = "missing_nonce_authentication_header";
1050
+ const invalidAuthenticationHeader = "invalid_authentication_header";
1051
+ const cannotSetOIDCOptions = "cannot_set_OIDCOptions";
1052
+ const cannotAllowNativeBroker = "cannot_allow_native_broker";
1053
+ const authorityMismatch = "authority_mismatch";
1054
+
1055
+ var ClientConfigurationErrorCodes = /*#__PURE__*/Object.freeze({
1056
+ __proto__: null,
1057
+ authorityMismatch: authorityMismatch,
1058
+ authorityUriInsecure: authorityUriInsecure,
1059
+ cannotAllowNativeBroker: cannotAllowNativeBroker,
1060
+ cannotSetOIDCOptions: cannotSetOIDCOptions,
1061
+ claimsRequestParsingError: claimsRequestParsingError,
1062
+ emptyInputScopesError: emptyInputScopesError,
1063
+ invalidAuthenticationHeader: invalidAuthenticationHeader,
1064
+ invalidAuthorityMetadata: invalidAuthorityMetadata,
1065
+ invalidClaims: invalidClaims,
1066
+ invalidCloudDiscoveryMetadata: invalidCloudDiscoveryMetadata,
1067
+ invalidCodeChallengeMethod: invalidCodeChallengeMethod,
1068
+ invalidPromptValue: invalidPromptValue,
1069
+ logoutRequestEmpty: logoutRequestEmpty,
1070
+ missingNonceAuthenticationHeader: missingNonceAuthenticationHeader,
1071
+ missingSshJwk: missingSshJwk,
1072
+ missingSshKid: missingSshKid,
1073
+ pkceParamsMissing: pkceParamsMissing,
1074
+ redirectUriEmpty: redirectUriEmpty,
1075
+ tokenRequestEmpty: tokenRequestEmpty,
1076
+ untrustedAuthority: untrustedAuthority,
1077
+ urlEmptyError: urlEmptyError,
1078
+ urlParseError: urlParseError
1079
+ });
1200
1080
 
1201
1081
  /*
1202
1082
  * Copyright (c) Microsoft Corporation. All rights reserved.
1203
1083
  * Licensed under the MIT License.
1204
1084
  */
1085
+ const ClientConfigurationErrorMessages = {
1086
+ [redirectUriEmpty]: "A redirect URI is required for all calls, and none has been set.",
1087
+ [claimsRequestParsingError]: "Could not parse the given claims request object.",
1088
+ [authorityUriInsecure]: "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",
1089
+ [urlParseError]: "URL could not be parsed into appropriate segments.",
1090
+ [urlEmptyError]: "URL was empty or null.",
1091
+ [emptyInputScopesError]: "Scopes cannot be passed as null, undefined or empty array because they are required to obtain an access token.",
1092
+ [invalidPromptValue]: "Please see here for valid configuration options: https://azuread.github.io/microsoft-authentication-library-for-js/ref/modules/_azure_msal_common.html#commonauthorizationurlrequest",
1093
+ [invalidClaims]: "Given claims parameter must be a stringified JSON object.",
1094
+ [tokenRequestEmpty]: "Token request was empty and not found in cache.",
1095
+ [logoutRequestEmpty]: "The logout request was null or undefined.",
1096
+ [invalidCodeChallengeMethod]: 'code_challenge_method passed is invalid. Valid values are "plain" and "S256".',
1097
+ [pkceParamsMissing]: "Both params: code_challenge and code_challenge_method are to be passed if to be sent in the request",
1098
+ [invalidCloudDiscoveryMetadata]: "Invalid cloudDiscoveryMetadata provided. Must be a stringified JSON object containing tenant_discovery_endpoint and metadata fields",
1099
+ [invalidAuthorityMetadata]: "Invalid authorityMetadata provided. Must by a stringified JSON object containing authorization_endpoint, token_endpoint, issuer fields.",
1100
+ [untrustedAuthority]: "The provided authority is not a trusted authority. Please include this authority in the knownAuthorities config parameter.",
1101
+ [missingSshJwk]: "Missing sshJwk in SSH certificate request. A stringified JSON Web Key is required when using the SSH authentication scheme.",
1102
+ [missingSshKid]: "Missing sshKid in SSH certificate request. A string that uniquely identifies the public SSH key is required when using the SSH authentication scheme.",
1103
+ [missingNonceAuthenticationHeader]: "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.",
1104
+ [invalidAuthenticationHeader]: "Invalid authentication header provided",
1105
+ [cannotSetOIDCOptions]: "Cannot set OIDCOptions parameter. Please change the protocol mode to OIDC or use a non-Microsoft authority.",
1106
+ [cannotAllowNativeBroker]: "Cannot set allowNativeBroker parameter to true when not in AAD protocol mode.",
1107
+ [authorityMismatch]: "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.",
1108
+ };
1205
1109
  /**
1206
1110
  * ClientConfigurationErrorMessage class containing string constants used by error codes and messages.
1111
+ * @deprecated Use ClientConfigurationErrorCodes instead
1207
1112
  */
1208
1113
  const ClientConfigurationErrorMessage = {
1209
1114
  redirectUriNotSet: {
1210
- code: "redirect_uri_empty",
1211
- desc: "A redirect URI is required for all calls, and none has been set.",
1212
- },
1213
- postLogoutUriNotSet: {
1214
- code: "post_logout_uri_empty",
1215
- desc: "A post logout redirect has not been set.",
1115
+ code: redirectUriEmpty,
1116
+ desc: ClientConfigurationErrorMessages[redirectUriEmpty],
1216
1117
  },
1217
1118
  claimsRequestParsingError: {
1218
- code: "claims_request_parsing_error",
1219
- desc: "Could not parse the given claims request object.",
1119
+ code: claimsRequestParsingError,
1120
+ desc: ClientConfigurationErrorMessages[claimsRequestParsingError],
1220
1121
  },
1221
1122
  authorityUriInsecure: {
1222
- code: "authority_uri_insecure",
1223
- 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",
1123
+ code: authorityUriInsecure,
1124
+ desc: ClientConfigurationErrorMessages[authorityUriInsecure],
1224
1125
  },
1225
1126
  urlParseError: {
1226
- code: "url_parse_error",
1227
- desc: "URL could not be parsed into appropriate segments.",
1127
+ code: urlParseError,
1128
+ desc: ClientConfigurationErrorMessages[urlParseError],
1228
1129
  },
1229
1130
  urlEmptyError: {
1230
- code: "empty_url_error",
1231
- desc: "URL was empty or null.",
1131
+ code: urlEmptyError,
1132
+ desc: ClientConfigurationErrorMessages[urlEmptyError],
1232
1133
  },
1233
1134
  emptyScopesError: {
1234
- code: "empty_input_scopes_error",
1235
- desc: "Scopes cannot be passed as null, undefined or empty array because they are required to obtain an access token.",
1236
- },
1237
- nonArrayScopesError: {
1238
- code: "nonarray_input_scopes_error",
1239
- desc: "Scopes cannot be passed as non-array.",
1240
- },
1241
- clientIdSingleScopeError: {
1242
- code: "clientid_input_scopes_error",
1243
- desc: "Client ID can only be provided as a single scope.",
1135
+ code: emptyInputScopesError,
1136
+ desc: ClientConfigurationErrorMessages[emptyInputScopesError],
1244
1137
  },
1245
1138
  invalidPrompt: {
1246
- code: "invalid_prompt_value",
1247
- desc: "Supported prompt values are 'login', 'select_account', 'consent', 'create', 'none' and 'no_session'. Please see here for valid configuration options: https://azuread.github.io/microsoft-authentication-library-for-js/ref/modules/_azure_msal_common.html#commonauthorizationurlrequest",
1139
+ code: invalidPromptValue,
1140
+ desc: ClientConfigurationErrorMessages[invalidPromptValue],
1248
1141
  },
1249
1142
  invalidClaimsRequest: {
1250
- code: "invalid_claims",
1251
- desc: "Given claims parameter must be a stringified JSON object.",
1143
+ code: invalidClaims,
1144
+ desc: ClientConfigurationErrorMessages[invalidClaims],
1252
1145
  },
1253
1146
  tokenRequestEmptyError: {
1254
- code: "token_request_empty",
1255
- desc: "Token request was empty and not found in cache.",
1147
+ code: tokenRequestEmpty,
1148
+ desc: ClientConfigurationErrorMessages[tokenRequestEmpty],
1256
1149
  },
1257
1150
  logoutRequestEmptyError: {
1258
- code: "logout_request_empty",
1259
- desc: "The logout request was null or undefined.",
1151
+ code: logoutRequestEmpty,
1152
+ desc: ClientConfigurationErrorMessages[logoutRequestEmpty],
1260
1153
  },
1261
1154
  invalidCodeChallengeMethod: {
1262
- code: "invalid_code_challenge_method",
1263
- desc: 'code_challenge_method passed is invalid. Valid values are "plain" and "S256".',
1155
+ code: invalidCodeChallengeMethod,
1156
+ desc: ClientConfigurationErrorMessages[invalidCodeChallengeMethod],
1264
1157
  },
1265
1158
  invalidCodeChallengeParams: {
1266
- code: "pkce_params_missing",
1267
- desc: "Both params: code_challenge and code_challenge_method are to be passed if to be sent in the request",
1159
+ code: pkceParamsMissing,
1160
+ desc: ClientConfigurationErrorMessages[pkceParamsMissing],
1268
1161
  },
1269
1162
  invalidCloudDiscoveryMetadata: {
1270
- code: "invalid_cloud_discovery_metadata",
1271
- desc: "Invalid cloudDiscoveryMetadata provided. Must be a stringified JSON object containing tenant_discovery_endpoint and metadata fields",
1163
+ code: invalidCloudDiscoveryMetadata,
1164
+ desc: ClientConfigurationErrorMessages[invalidCloudDiscoveryMetadata],
1272
1165
  },
1273
1166
  invalidAuthorityMetadata: {
1274
- code: "invalid_authority_metadata",
1275
- desc: "Invalid authorityMetadata provided. Must by a stringified JSON object containing authorization_endpoint, token_endpoint, issuer fields.",
1167
+ code: invalidAuthorityMetadata,
1168
+ desc: ClientConfigurationErrorMessages[invalidAuthorityMetadata],
1276
1169
  },
1277
1170
  untrustedAuthority: {
1278
- code: "untrusted_authority",
1279
- desc: "The provided authority is not a trusted authority. Please include this authority in the knownAuthorities config parameter.",
1280
- },
1281
- invalidAzureCloudInstance: {
1282
- code: "invalid_azure_cloud_instance",
1283
- desc: "Invalid AzureCloudInstance provided. Please refer MSAL JS docs: aks.ms/msaljs/azure_cloud_instance for valid values",
1171
+ code: untrustedAuthority,
1172
+ desc: ClientConfigurationErrorMessages[untrustedAuthority],
1284
1173
  },
1285
1174
  missingSshJwk: {
1286
- code: "missing_ssh_jwk",
1287
- desc: "Missing sshJwk in SSH certificate request. A stringified JSON Web Key is required when using the SSH authentication scheme.",
1175
+ code: missingSshJwk,
1176
+ desc: ClientConfigurationErrorMessages[missingSshJwk],
1288
1177
  },
1289
1178
  missingSshKid: {
1290
- code: "missing_ssh_kid",
1291
- desc: "Missing sshKid in SSH certificate request. A string that uniquely identifies the public SSH key is required when using the SSH authentication scheme.",
1179
+ code: missingSshKid,
1180
+ desc: ClientConfigurationErrorMessages[missingSshKid],
1292
1181
  },
1293
1182
  missingNonceAuthenticationHeader: {
1294
- code: "missing_nonce_authentication_header",
1295
- 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.",
1183
+ code: missingNonceAuthenticationHeader,
1184
+ desc: ClientConfigurationErrorMessages[missingNonceAuthenticationHeader],
1296
1185
  },
1297
1186
  invalidAuthenticationHeader: {
1298
- code: "invalid_authentication_header",
1299
- desc: "Invalid authentication header provided",
1187
+ code: invalidAuthenticationHeader,
1188
+ desc: ClientConfigurationErrorMessages[invalidAuthenticationHeader],
1300
1189
  },
1301
1190
  cannotSetOIDCOptions: {
1302
- code: "cannot_set_OIDCOptions",
1303
- desc: "Cannot set OIDCOptions parameter. Please change the protocol mode to OIDC or use a non-Microsoft authority.",
1191
+ code: cannotSetOIDCOptions,
1192
+ desc: ClientConfigurationErrorMessages[cannotSetOIDCOptions],
1304
1193
  },
1305
1194
  cannotAllowNativeBroker: {
1306
- code: "cannot_allow_native_broker",
1307
- desc: "Cannot set allowNativeBroker parameter to true when not in AAD protocol mode.",
1195
+ code: cannotAllowNativeBroker,
1196
+ desc: ClientConfigurationErrorMessages[cannotAllowNativeBroker],
1308
1197
  },
1309
1198
  authorityMismatch: {
1310
- code: "authority_mismatch",
1311
- 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.",
1199
+ code: authorityMismatch,
1200
+ desc: ClientConfigurationErrorMessages[authorityMismatch],
1312
1201
  },
1313
1202
  };
1314
1203
  /**
1315
1204
  * Error thrown when there is an error in configuration of the MSAL.js library.
1316
1205
  */
1317
- class ClientConfigurationError extends ClientAuthError {
1318
- constructor(errorCode, errorMessage) {
1319
- super(errorCode, errorMessage);
1206
+ class ClientConfigurationError extends AuthError {
1207
+ constructor(errorCode) {
1208
+ super(errorCode, ClientConfigurationErrorMessages[errorCode]);
1320
1209
  this.name = "ClientConfigurationError";
1321
1210
  Object.setPrototypeOf(this, ClientConfigurationError.prototype);
1322
1211
  }
1323
- /**
1324
- * Creates an error thrown when the redirect uri is empty (not set by caller)
1325
- */
1326
- static createRedirectUriEmptyError() {
1327
- return new ClientConfigurationError(ClientConfigurationErrorMessage.redirectUriNotSet.code, ClientConfigurationErrorMessage.redirectUriNotSet.desc);
1328
- }
1329
- /**
1330
- * Creates an error thrown when the post-logout redirect uri is empty (not set by caller)
1331
- */
1332
- static createPostLogoutRedirectUriEmptyError() {
1333
- return new ClientConfigurationError(ClientConfigurationErrorMessage.postLogoutUriNotSet.code, ClientConfigurationErrorMessage.postLogoutUriNotSet.desc);
1334
- }
1335
- /**
1336
- * Creates an error thrown when the claims request could not be successfully parsed
1337
- */
1338
- static createClaimsRequestParsingError(claimsRequestParseError) {
1339
- return new ClientConfigurationError(ClientConfigurationErrorMessage.claimsRequestParsingError.code, `${ClientConfigurationErrorMessage.claimsRequestParsingError.desc} Given value: ${claimsRequestParseError}`);
1340
- }
1341
- /**
1342
- * Creates an error thrown if authority uri is given an insecure protocol.
1343
- * @param urlString
1344
- */
1345
- static createInsecureAuthorityUriError(urlString) {
1346
- return new ClientConfigurationError(ClientConfigurationErrorMessage.authorityUriInsecure.code, `${ClientConfigurationErrorMessage.authorityUriInsecure.desc} Given URI: ${urlString}`);
1347
- }
1348
- /**
1349
- * Creates an error thrown if URL string does not parse into separate segments.
1350
- * @param urlString
1351
- */
1352
- static createUrlParseError(urlParseError) {
1353
- return new ClientConfigurationError(ClientConfigurationErrorMessage.urlParseError.code, `${ClientConfigurationErrorMessage.urlParseError.desc} Given Error: ${urlParseError}`);
1354
- }
1355
- /**
1356
- * Creates an error thrown if URL string is empty or null.
1357
- * @param urlString
1358
- */
1359
- static createUrlEmptyError() {
1360
- return new ClientConfigurationError(ClientConfigurationErrorMessage.urlEmptyError.code, ClientConfigurationErrorMessage.urlEmptyError.desc);
1361
- }
1362
- /**
1363
- * Error thrown when scopes are empty.
1364
- * @param scopesValue
1365
- */
1366
- static createEmptyScopesArrayError() {
1367
- return new ClientConfigurationError(ClientConfigurationErrorMessage.emptyScopesError.code, `${ClientConfigurationErrorMessage.emptyScopesError.desc}`);
1368
- }
1369
- /**
1370
- * Error thrown when client id scope is not provided as single scope.
1371
- * @param inputScopes
1372
- */
1373
- static createClientIdSingleScopeError(inputScopes) {
1374
- return new ClientConfigurationError(ClientConfigurationErrorMessage.clientIdSingleScopeError.code, `${ClientConfigurationErrorMessage.clientIdSingleScopeError.desc} Given Scopes: ${inputScopes}`);
1375
- }
1376
- /**
1377
- * Error thrown when prompt is not an allowed type.
1378
- * @param promptValue
1379
- */
1380
- static createInvalidPromptError(promptValue) {
1381
- return new ClientConfigurationError(ClientConfigurationErrorMessage.invalidPrompt.code, `${ClientConfigurationErrorMessage.invalidPrompt.desc} Given value: ${promptValue}`);
1382
- }
1383
- /**
1384
- * Creates error thrown when claims parameter is not a stringified JSON object
1385
- */
1386
- static createInvalidClaimsRequestError() {
1387
- return new ClientConfigurationError(ClientConfigurationErrorMessage.invalidClaimsRequest.code, ClientConfigurationErrorMessage.invalidClaimsRequest.desc);
1388
- }
1389
- /**
1390
- * Throws error when token request is empty and nothing cached in storage.
1391
- */
1392
- static createEmptyLogoutRequestError() {
1393
- return new ClientConfigurationError(ClientConfigurationErrorMessage.logoutRequestEmptyError.code, ClientConfigurationErrorMessage.logoutRequestEmptyError.desc);
1394
- }
1395
- /**
1396
- * Throws error when token request is empty and nothing cached in storage.
1397
- */
1398
- static createEmptyTokenRequestError() {
1399
- return new ClientConfigurationError(ClientConfigurationErrorMessage.tokenRequestEmptyError.code, ClientConfigurationErrorMessage.tokenRequestEmptyError.desc);
1400
- }
1401
- /**
1402
- * Throws error when an invalid code_challenge_method is passed by the user
1403
- */
1404
- static createInvalidCodeChallengeMethodError() {
1405
- return new ClientConfigurationError(ClientConfigurationErrorMessage.invalidCodeChallengeMethod.code, ClientConfigurationErrorMessage.invalidCodeChallengeMethod.desc);
1406
- }
1407
- /**
1408
- * Throws error when both params: code_challenge and code_challenge_method are not passed together
1409
- */
1410
- static createInvalidCodeChallengeParamsError() {
1411
- return new ClientConfigurationError(ClientConfigurationErrorMessage.invalidCodeChallengeParams.code, ClientConfigurationErrorMessage.invalidCodeChallengeParams.desc);
1412
- }
1413
- /**
1414
- * Throws an error when the user passes invalid cloudDiscoveryMetadata
1415
- */
1416
- static createInvalidCloudDiscoveryMetadataError() {
1417
- return new ClientConfigurationError(ClientConfigurationErrorMessage.invalidCloudDiscoveryMetadata.code, ClientConfigurationErrorMessage.invalidCloudDiscoveryMetadata.desc);
1418
- }
1419
- /**
1420
- * Throws an error when the user passes invalid cloudDiscoveryMetadata
1421
- */
1422
- static createInvalidAuthorityMetadataError() {
1423
- return new ClientConfigurationError(ClientConfigurationErrorMessage.invalidAuthorityMetadata.code, ClientConfigurationErrorMessage.invalidAuthorityMetadata.desc);
1424
- }
1425
- /**
1426
- * Throws error when provided authority is not a member of the trusted host list
1427
- */
1428
- static createUntrustedAuthorityError() {
1429
- return new ClientConfigurationError(ClientConfigurationErrorMessage.untrustedAuthority.code, ClientConfigurationErrorMessage.untrustedAuthority.desc);
1430
- }
1431
- /**
1432
- * Throws error when the AzureCloudInstance is set to an invalid value
1433
- */
1434
- static createInvalidAzureCloudInstanceError() {
1435
- return new ClientConfigurationError(ClientConfigurationErrorMessage.invalidAzureCloudInstance.code, ClientConfigurationErrorMessage.invalidAzureCloudInstance.desc);
1436
- }
1437
- /**
1438
- * Throws an error when the authentication scheme is set to SSH but the SSH public key is omitted from the request
1439
- */
1440
- static createMissingSshJwkError() {
1441
- return new ClientConfigurationError(ClientConfigurationErrorMessage.missingSshJwk.code, ClientConfigurationErrorMessage.missingSshJwk.desc);
1442
- }
1443
- /**
1444
- * Throws an error when the authentication scheme is set to SSH but the SSH public key ID is omitted from the request
1445
- */
1446
- static createMissingSshKidError() {
1447
- return new ClientConfigurationError(ClientConfigurationErrorMessage.missingSshKid.code, ClientConfigurationErrorMessage.missingSshKid.desc);
1448
- }
1449
- /**
1450
- * Throws error when provided headers don't contain a header that a server nonce can be extracted from
1451
- */
1452
- static createMissingNonceAuthenticationHeadersError() {
1453
- return new ClientConfigurationError(ClientConfigurationErrorMessage.missingNonceAuthenticationHeader.code, ClientConfigurationErrorMessage.missingNonceAuthenticationHeader.desc);
1454
- }
1455
- /**
1456
- * Throws error when a provided header is invalid in any way
1457
- */
1458
- static createInvalidAuthenticationHeaderError(invalidHeaderName, details) {
1459
- return new ClientConfigurationError(ClientConfigurationErrorMessage.invalidAuthenticationHeader.code, `${ClientConfigurationErrorMessage.invalidAuthenticationHeader.desc}. Invalid header: ${invalidHeaderName}. Details: ${details}`);
1460
- }
1461
- /**
1462
- * Throws error when provided non-default OIDCOptions when not in OIDC protocol mode
1463
- */
1464
- static createCannotSetOIDCOptionsError() {
1465
- return new ClientConfigurationError(ClientConfigurationErrorMessage.cannotSetOIDCOptions.code, ClientConfigurationErrorMessage.cannotSetOIDCOptions.desc);
1466
- }
1467
- /**
1468
- * Throws error when allowNativeBroker is set to true when not in AAD protocol mode
1469
- */
1470
- static createCannotAllowNativeBrokerError() {
1471
- return new ClientConfigurationError(ClientConfigurationErrorMessage.cannotAllowNativeBroker.code, ClientConfigurationErrorMessage.cannotAllowNativeBroker.desc);
1472
- }
1473
- /**
1474
- * Create an error when the authority provided in request does not match authority provided in account or MSAL.js configuration.
1475
- */
1476
- static createAuthorityMismatchError() {
1477
- return new ClientConfigurationError(ClientConfigurationErrorMessage.authorityMismatch.code, ClientConfigurationErrorMessage.authorityMismatch.desc);
1478
- }
1212
+ }
1213
+ function createClientConfigurationError(errorCode) {
1214
+ return new ClientConfigurationError(errorCode);
1479
1215
  }
1480
1216
 
1481
1217
  /*
@@ -1631,7 +1367,7 @@ class ScopeSet {
1631
1367
  validateInputScopes(inputScopes) {
1632
1368
  // Check if scopes are required but not given or is an empty array
1633
1369
  if (!inputScopes || inputScopes.length < 1) {
1634
- throw ClientConfigurationError.createEmptyScopesArrayError();
1370
+ throw createClientConfigurationError(emptyInputScopesError);
1635
1371
  }
1636
1372
  }
1637
1373
  /**
@@ -1687,7 +1423,7 @@ class ScopeSet {
1687
1423
  newScopes.forEach((newScope) => this.appendScope(newScope));
1688
1424
  }
1689
1425
  catch (e) {
1690
- throw ClientAuthError.createAppendScopeSetError(e);
1426
+ throw createClientAuthError(cannotAppendScopeSet);
1691
1427
  }
1692
1428
  }
1693
1429
  /**
@@ -1696,7 +1432,7 @@ class ScopeSet {
1696
1432
  */
1697
1433
  removeScope(scope) {
1698
1434
  if (!scope) {
1699
- throw ClientAuthError.createRemoveEmptyScopeFromSetError(scope);
1435
+ throw createClientAuthError(cannotRemoveEmptyScope);
1700
1436
  }
1701
1437
  this.scopes.delete(scope.trim());
1702
1438
  }
@@ -1715,7 +1451,7 @@ class ScopeSet {
1715
1451
  */
1716
1452
  unionScopeSets(otherScopes) {
1717
1453
  if (!otherScopes) {
1718
- throw ClientAuthError.createEmptyInputScopeSetError();
1454
+ throw createClientAuthError(emptyInputScopeSet);
1719
1455
  }
1720
1456
  const unionScopes = new Set(); // Iterator in constructor not supported in IE11
1721
1457
  otherScopes.scopes.forEach((scope) => unionScopes.add(scope.toLowerCase()));
@@ -1728,7 +1464,7 @@ class ScopeSet {
1728
1464
  */
1729
1465
  intersectingScopeSets(otherScopes) {
1730
1466
  if (!otherScopes) {
1731
- throw ClientAuthError.createEmptyInputScopeSetError();
1467
+ throw createClientAuthError(emptyInputScopeSet);
1732
1468
  }
1733
1469
  // Do not allow OIDC scopes to be the only intersecting scopes
1734
1470
  if (!otherScopes.containsOnlyOIDCScopes()) {
@@ -1783,14 +1519,14 @@ class ScopeSet {
1783
1519
  */
1784
1520
  function buildClientInfo(rawClientInfo, crypto) {
1785
1521
  if (!rawClientInfo) {
1786
- throw ClientAuthError.createClientInfoEmptyError();
1522
+ throw createClientAuthError(clientInfoEmptyError);
1787
1523
  }
1788
1524
  try {
1789
1525
  const decodedClientInfo = crypto.base64Decode(rawClientInfo);
1790
1526
  return JSON.parse(decodedClientInfo);
1791
1527
  }
1792
1528
  catch (e) {
1793
- throw ClientAuthError.createClientInfoDecodingError(e.message);
1529
+ throw createClientAuthError(clientInfoDecodingError);
1794
1530
  }
1795
1531
  }
1796
1532
  /**
@@ -1799,7 +1535,7 @@ function buildClientInfo(rawClientInfo, crypto) {
1799
1535
  */
1800
1536
  function buildClientInfoFromHomeAccountId(homeAccountId) {
1801
1537
  if (!homeAccountId) {
1802
- throw ClientAuthError.createClientInfoDecodingError("Home account ID was empty.");
1538
+ throw createClientAuthError(clientInfoDecodingError);
1803
1539
  }
1804
1540
  const clientInfoParts = homeAccountId.split(Separators.CLIENT_INFO_SEPARATOR, 2);
1805
1541
  return {
@@ -1932,7 +1668,7 @@ class AccountEntity {
1932
1668
  const env = accountDetails.environment ||
1933
1669
  (authority && authority.getPreferredCache());
1934
1670
  if (!env) {
1935
- throw ClientAuthError.createInvalidCacheEnvironmentError();
1671
+ throw createClientAuthError(invalidCacheEnvironment);
1936
1672
  }
1937
1673
  account.environment = env;
1938
1674
  // non AAD scenarios can have empty realm
@@ -2075,7 +1811,7 @@ function extractTokenClaims(encodedToken, base64Decode) {
2075
1811
  return JSON.parse(base64Decoded);
2076
1812
  }
2077
1813
  catch (err) {
2078
- throw ClientAuthError.createTokenParsingError(err);
1814
+ throw createClientAuthError(tokenParsingError);
2079
1815
  }
2080
1816
  }
2081
1817
  /**
@@ -2085,12 +1821,12 @@ function extractTokenClaims(encodedToken, base64Decode) {
2085
1821
  */
2086
1822
  function getJWSPayload(authToken) {
2087
1823
  if (!authToken) {
2088
- throw ClientAuthError.createTokenNullOrEmptyError(authToken);
1824
+ throw createClientAuthError(nullOrEmptyToken);
2089
1825
  }
2090
1826
  const tokenPartsRegex = /^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/;
2091
1827
  const matches = tokenPartsRegex.exec(authToken);
2092
1828
  if (!matches || matches.length < 4) {
2093
- throw ClientAuthError.createTokenParsingError(`Given token is malformed: ${JSON.stringify(authToken)}`);
1829
+ throw createClientAuthError(tokenParsingError);
2094
1830
  }
2095
1831
  /**
2096
1832
  * const crackedToken = {
@@ -2112,7 +1848,7 @@ function checkMaxAge(authTime, maxAge) {
2112
1848
  */
2113
1849
  const fiveMinuteSkew = 300000; // five minutes in milliseconds
2114
1850
  if (maxAge === 0 || Date.now() - fiveMinuteSkew > authTime + maxAge) {
2115
- throw ClientAuthError.createMaxAgeTranspiredError();
1851
+ throw createClientAuthError(maxAgeTranspired);
2116
1852
  }
2117
1853
  }
2118
1854
 
@@ -2138,9 +1874,16 @@ class CacheManager {
2138
1874
  this.commonLogger = logger.clone(name, version);
2139
1875
  }
2140
1876
  /**
2141
- * Returns all accounts in cache
1877
+ * Returns all the accounts in the cache that match the optional filter. If no filter is provided, all accounts are returned.
1878
+ * @param accountFilter - (Optional) filter to narrow down the accounts returned
1879
+ * @returns Array of AccountInfo objects in cache
2142
1880
  */
2143
- getAllAccounts() {
1881
+ getAllAccounts(accountFilter) {
1882
+ if (accountFilter) {
1883
+ return this.getAccountsFilteredBy(accountFilter).map((accountEntity) => {
1884
+ return accountEntity.getAccountInfo();
1885
+ });
1886
+ }
2144
1887
  const allAccountKeys = this.getAccountKeys();
2145
1888
  if (allAccountKeys.length < 1) {
2146
1889
  return [];
@@ -2153,15 +1896,10 @@ class CacheManager {
2153
1896
  accounts.push(entity);
2154
1897
  return accounts;
2155
1898
  }, []);
2156
- if (accountEntities.length < 1) {
2157
- return [];
2158
- }
2159
- else {
2160
- const allAccounts = accountEntities.map((accountEntity) => {
2161
- return this.getAccountInfoFromEntity(accountEntity);
2162
- });
2163
- return allAccounts;
2164
- }
1899
+ const allAccounts = accountEntities.map((accountEntity) => {
1900
+ return this.getAccountInfoFromEntity(accountEntity);
1901
+ });
1902
+ return allAccounts;
2165
1903
  }
2166
1904
  /**
2167
1905
  * Gets accountInfo object based on provided filters
@@ -2190,7 +1928,7 @@ class CacheManager {
2190
1928
  */
2191
1929
  async saveCacheRecord(cacheRecord, storeInCache) {
2192
1930
  if (!cacheRecord) {
2193
- throw ClientAuthError.createNullOrUndefinedCacheRecord();
1931
+ throw createClientAuthError(invalidCacheRecord);
2194
1932
  }
2195
1933
  if (!!cacheRecord.account) {
2196
1934
  this.setAccount(cacheRecord.account);
@@ -2243,17 +1981,15 @@ class CacheManager {
2243
1981
  this.setAccessTokenCredential(credential);
2244
1982
  }
2245
1983
  /**
2246
- * retrieve accounts matching all provided filters; if no filter is set, get all accounts
2247
- * not checking for casing as keys are all generated in lower case, remember to convert to lower case if object properties are compared
2248
- * @param homeAccountId
2249
- * @param environment
2250
- * @param realm
1984
+ * Retrieve accounts matching all provided filters; if no filter is set, get all accounts
1985
+ * Not checking for casing as keys are all generated in lower case, remember to convert to lower case if object properties are compared
1986
+ * @param accountFilter - An object containing Account properties to filter by
2251
1987
  */
2252
1988
  getAccountsFilteredBy(accountFilter) {
2253
1989
  const allAccountKeys = this.getAccountKeys();
2254
1990
  const matchingAccounts = [];
2255
1991
  allAccountKeys.forEach((cacheKey) => {
2256
- if (!this.isAccountKey(cacheKey, accountFilter.homeAccountId, accountFilter.realm)) {
1992
+ if (!this.isAccountKey(cacheKey, accountFilter.homeAccountId, accountFilter.tenantId)) {
2257
1993
  // Don't parse value if the key doesn't match the account filters
2258
1994
  return;
2259
1995
  }
@@ -2281,10 +2017,27 @@ class CacheManager {
2281
2017
  !this.matchRealm(entity, accountFilter.realm)) {
2282
2018
  return;
2283
2019
  }
2020
+ // tenantId is another name for realm
2021
+ if (!!accountFilter.tenantId &&
2022
+ !this.matchRealm(entity, accountFilter.tenantId)) {
2023
+ return;
2024
+ }
2284
2025
  if (!!accountFilter.nativeAccountId &&
2285
2026
  !this.matchNativeAccountId(entity, accountFilter.nativeAccountId)) {
2286
2027
  return;
2287
2028
  }
2029
+ if (!!accountFilter.loginHint &&
2030
+ !this.matchLoginHint(entity, accountFilter.loginHint)) {
2031
+ return;
2032
+ }
2033
+ if (!!accountFilter.authorityType &&
2034
+ !this.matchAuthorityType(entity, accountFilter.authorityType)) {
2035
+ return;
2036
+ }
2037
+ if (!!accountFilter.name &&
2038
+ !this.matchName(entity, accountFilter.name)) {
2039
+ return;
2040
+ }
2288
2041
  matchingAccounts.push(entity);
2289
2042
  });
2290
2043
  return matchingAccounts;
@@ -2541,7 +2294,7 @@ class CacheManager {
2541
2294
  await this.cryptoImpl.removeTokenBindingKey(kid);
2542
2295
  }
2543
2296
  catch (error) {
2544
- throw ClientAuthError.createBindingKeyNotRemovedError();
2297
+ throw createClientAuthError(bindingKeyNotRemoved);
2545
2298
  }
2546
2299
  }
2547
2300
  }
@@ -2877,7 +2630,7 @@ class CacheManager {
2877
2630
  return null;
2878
2631
  }
2879
2632
  else if (numAppMetadata > 1) {
2880
- throw ClientAuthError.createMultipleMatchingAppMetadataInCacheError();
2633
+ throw createClientAuthError(multipleMatchingAppMetadata);
2881
2634
  }
2882
2635
  return appMetadataEntries[0];
2883
2636
  }
@@ -2919,6 +2672,15 @@ class CacheManager {
2919
2672
  return !!(typeof entity.username === "string" &&
2920
2673
  username.toLowerCase() === entity.username.toLowerCase());
2921
2674
  }
2675
+ /**
2676
+ * helper to match names
2677
+ * @param entity
2678
+ * @param name
2679
+ * @returns true if the downcased name properties are present and match in the filter and the entity
2680
+ */
2681
+ matchName(entity, name) {
2682
+ return !!(name.toLowerCase() === entity.name?.toLowerCase());
2683
+ }
2922
2684
  /**
2923
2685
  * helper to match assertion
2924
2686
  * @param value
@@ -2983,6 +2745,31 @@ class CacheManager {
2983
2745
  matchNativeAccountId(entity, nativeAccountId) {
2984
2746
  return !!(entity.nativeAccountId && nativeAccountId === entity.nativeAccountId);
2985
2747
  }
2748
+ /**
2749
+ * helper to match loginHint which can be either:
2750
+ * 1. login_hint ID token claim
2751
+ * 2. username in cached account object
2752
+ * 3. upn in ID token claims
2753
+ * @param entity
2754
+ * @param loginHint
2755
+ * @returns
2756
+ */
2757
+ matchLoginHint(entity, loginHint) {
2758
+ if (entity.idTokenClaims?.login_hint === loginHint) {
2759
+ return true;
2760
+ }
2761
+ if (entity.username === loginHint) {
2762
+ return true;
2763
+ }
2764
+ if (entity.idTokenClaims?.upn === loginHint) {
2765
+ return true;
2766
+ }
2767
+ return false;
2768
+ }
2769
+ matchAuthorityType(entity, authorityType) {
2770
+ return !!(entity.authorityType &&
2771
+ authorityType.toLowerCase() === entity.authorityType.toLowerCase());
2772
+ }
2986
2773
  /**
2987
2774
  * Returns true if the target scopes are a subset of the current entity's scopes, false otherwise.
2988
2775
  * @param entity
@@ -3049,100 +2836,76 @@ class CacheManager {
3049
2836
  /** @internal */
3050
2837
  class DefaultStorageClass extends CacheManager {
3051
2838
  setAccount() {
3052
- const notImplErr = "Storage interface - setAccount() has not been implemented for the cacheStorage interface.";
3053
- throw AuthError.createUnexpectedError(notImplErr);
2839
+ throw createClientAuthError(methodNotImplemented);
3054
2840
  }
3055
2841
  getAccount() {
3056
- const notImplErr = "Storage interface - getAccount() has not been implemented for the cacheStorage interface.";
3057
- throw AuthError.createUnexpectedError(notImplErr);
2842
+ throw createClientAuthError(methodNotImplemented);
3058
2843
  }
3059
2844
  setIdTokenCredential() {
3060
- const notImplErr = "Storage interface - setIdTokenCredential() has not been implemented for the cacheStorage interface.";
3061
- throw AuthError.createUnexpectedError(notImplErr);
2845
+ throw createClientAuthError(methodNotImplemented);
3062
2846
  }
3063
2847
  getIdTokenCredential() {
3064
- const notImplErr = "Storage interface - getIdTokenCredential() has not been implemented for the cacheStorage interface.";
3065
- throw AuthError.createUnexpectedError(notImplErr);
2848
+ throw createClientAuthError(methodNotImplemented);
3066
2849
  }
3067
2850
  setAccessTokenCredential() {
3068
- const notImplErr = "Storage interface - setAccessTokenCredential() has not been implemented for the cacheStorage interface.";
3069
- throw AuthError.createUnexpectedError(notImplErr);
2851
+ throw createClientAuthError(methodNotImplemented);
3070
2852
  }
3071
2853
  getAccessTokenCredential() {
3072
- const notImplErr = "Storage interface - getAccessTokenCredential() has not been implemented for the cacheStorage interface.";
3073
- throw AuthError.createUnexpectedError(notImplErr);
2854
+ throw createClientAuthError(methodNotImplemented);
3074
2855
  }
3075
2856
  setRefreshTokenCredential() {
3076
- const notImplErr = "Storage interface - setRefreshTokenCredential() has not been implemented for the cacheStorage interface.";
3077
- throw AuthError.createUnexpectedError(notImplErr);
2857
+ throw createClientAuthError(methodNotImplemented);
3078
2858
  }
3079
2859
  getRefreshTokenCredential() {
3080
- const notImplErr = "Storage interface - getRefreshTokenCredential() has not been implemented for the cacheStorage interface.";
3081
- throw AuthError.createUnexpectedError(notImplErr);
2860
+ throw createClientAuthError(methodNotImplemented);
3082
2861
  }
3083
2862
  setAppMetadata() {
3084
- const notImplErr = "Storage interface - setAppMetadata() has not been implemented for the cacheStorage interface.";
3085
- throw AuthError.createUnexpectedError(notImplErr);
2863
+ throw createClientAuthError(methodNotImplemented);
3086
2864
  }
3087
2865
  getAppMetadata() {
3088
- const notImplErr = "Storage interface - getAppMetadata() has not been implemented for the cacheStorage interface.";
3089
- throw AuthError.createUnexpectedError(notImplErr);
2866
+ throw createClientAuthError(methodNotImplemented);
3090
2867
  }
3091
2868
  setServerTelemetry() {
3092
- const notImplErr = "Storage interface - setServerTelemetry() has not been implemented for the cacheStorage interface.";
3093
- throw AuthError.createUnexpectedError(notImplErr);
2869
+ throw createClientAuthError(methodNotImplemented);
3094
2870
  }
3095
2871
  getServerTelemetry() {
3096
- const notImplErr = "Storage interface - getServerTelemetry() has not been implemented for the cacheStorage interface.";
3097
- throw AuthError.createUnexpectedError(notImplErr);
2872
+ throw createClientAuthError(methodNotImplemented);
3098
2873
  }
3099
2874
  setAuthorityMetadata() {
3100
- const notImplErr = "Storage interface - setAuthorityMetadata() has not been implemented for the cacheStorage interface.";
3101
- throw AuthError.createUnexpectedError(notImplErr);
2875
+ throw createClientAuthError(methodNotImplemented);
3102
2876
  }
3103
2877
  getAuthorityMetadata() {
3104
- const notImplErr = "Storage interface - getAuthorityMetadata() has not been implemented for the cacheStorage interface.";
3105
- throw AuthError.createUnexpectedError(notImplErr);
2878
+ throw createClientAuthError(methodNotImplemented);
3106
2879
  }
3107
2880
  getAuthorityMetadataKeys() {
3108
- const notImplErr = "Storage interface - getAuthorityMetadataKeys() has not been implemented for the cacheStorage interface.";
3109
- throw AuthError.createUnexpectedError(notImplErr);
2881
+ throw createClientAuthError(methodNotImplemented);
3110
2882
  }
3111
2883
  setThrottlingCache() {
3112
- const notImplErr = "Storage interface - setThrottlingCache() has not been implemented for the cacheStorage interface.";
3113
- throw AuthError.createUnexpectedError(notImplErr);
2884
+ throw createClientAuthError(methodNotImplemented);
3114
2885
  }
3115
2886
  getThrottlingCache() {
3116
- const notImplErr = "Storage interface - getThrottlingCache() has not been implemented for the cacheStorage interface.";
3117
- throw AuthError.createUnexpectedError(notImplErr);
2887
+ throw createClientAuthError(methodNotImplemented);
3118
2888
  }
3119
2889
  removeItem() {
3120
- const notImplErr = "Storage interface - removeItem() has not been implemented for the cacheStorage interface.";
3121
- throw AuthError.createUnexpectedError(notImplErr);
2890
+ throw createClientAuthError(methodNotImplemented);
3122
2891
  }
3123
2892
  containsKey() {
3124
- const notImplErr = "Storage interface - containsKey() has not been implemented for the cacheStorage interface.";
3125
- throw AuthError.createUnexpectedError(notImplErr);
2893
+ throw createClientAuthError(methodNotImplemented);
3126
2894
  }
3127
2895
  getKeys() {
3128
- const notImplErr = "Storage interface - getKeys() has not been implemented for the cacheStorage interface.";
3129
- throw AuthError.createUnexpectedError(notImplErr);
2896
+ throw createClientAuthError(methodNotImplemented);
3130
2897
  }
3131
2898
  getAccountKeys() {
3132
- const notImplErr = "Storage interface - getAccountKeys() has not been implemented for the cacheStorage interface.";
3133
- throw AuthError.createUnexpectedError(notImplErr);
2899
+ throw createClientAuthError(methodNotImplemented);
3134
2900
  }
3135
2901
  getTokenKeys() {
3136
- const notImplErr = "Storage interface - getTokenKeys() has not been implemented for the cacheStorage interface.";
3137
- throw AuthError.createUnexpectedError(notImplErr);
2902
+ throw createClientAuthError(methodNotImplemented);
3138
2903
  }
3139
2904
  async clear() {
3140
- const notImplErr = "Storage interface - clear() has not been implemented for the cacheStorage interface.";
3141
- throw AuthError.createUnexpectedError(notImplErr);
2905
+ throw createClientAuthError(methodNotImplemented);
3142
2906
  }
3143
2907
  updateCredentialCacheKey() {
3144
- const notImplErr = "Storage interface - updateCredentialCacheKey() has not been implemented for the cacheStorage interface.";
3145
- throw AuthError.createUnexpectedError(notImplErr);
2908
+ throw createClientAuthError(methodNotImplemented);
3146
2909
  }
3147
2910
  }
3148
2911
 
@@ -3169,12 +2932,10 @@ const DEFAULT_CACHE_OPTIONS = {
3169
2932
  };
3170
2933
  const DEFAULT_NETWORK_IMPLEMENTATION = {
3171
2934
  async sendGetRequestAsync() {
3172
- const notImplErr = "Network interface - sendGetRequestAsync() has not been implemented";
3173
- throw AuthError.createUnexpectedError(notImplErr);
2935
+ throw createClientAuthError(methodNotImplemented);
3174
2936
  },
3175
2937
  async sendPostRequestAsync() {
3176
- const notImplErr = "Network interface - sendPostRequestAsync() has not been implemented";
3177
- throw AuthError.createUnexpectedError(notImplErr);
2938
+ throw createClientAuthError(methodNotImplemented);
3178
2939
  },
3179
2940
  };
3180
2941
  const DEFAULT_LIBRARY_INFO = {
@@ -3384,7 +3145,7 @@ class NetworkManager {
3384
3145
  throw e;
3385
3146
  }
3386
3147
  else {
3387
- throw ClientAuthError.createNetworkError(tokenEndpoint, e);
3148
+ throw createClientAuthError(networkError);
3388
3149
  }
3389
3150
  }
3390
3151
  ThrottlingUtils.postProcess(this.cacheManager, thumbprint, response);
@@ -3415,7 +3176,7 @@ class RequestValidator {
3415
3176
  */
3416
3177
  static validateRedirectUri(redirectUri) {
3417
3178
  if (!redirectUri) {
3418
- throw ClientConfigurationError.createRedirectUriEmptyError();
3179
+ throw createClientConfigurationError(redirectUriEmpty);
3419
3180
  }
3420
3181
  }
3421
3182
  /**
@@ -3428,7 +3189,7 @@ class RequestValidator {
3428
3189
  promptValues.push(PromptValue[value]);
3429
3190
  }
3430
3191
  if (promptValues.indexOf(prompt) < 0) {
3431
- throw ClientConfigurationError.createInvalidPromptError(prompt);
3192
+ throw createClientConfigurationError(invalidPromptValue);
3432
3193
  }
3433
3194
  }
3434
3195
  static validateClaims(claims) {
@@ -3436,7 +3197,7 @@ class RequestValidator {
3436
3197
  JSON.parse(claims);
3437
3198
  }
3438
3199
  catch (e) {
3439
- throw ClientConfigurationError.createInvalidClaimsRequestError();
3200
+ throw createClientConfigurationError(invalidClaims);
3440
3201
  }
3441
3202
  }
3442
3203
  /**
@@ -3446,7 +3207,7 @@ class RequestValidator {
3446
3207
  */
3447
3208
  static validateCodeChallengeParams(codeChallenge, codeChallengeMethod) {
3448
3209
  if (!codeChallenge || !codeChallengeMethod) {
3449
- throw ClientConfigurationError.createInvalidCodeChallengeParamsError();
3210
+ throw createClientConfigurationError(pkceParamsMissing);
3450
3211
  }
3451
3212
  else {
3452
3213
  this.validateCodeChallengeMethod(codeChallengeMethod);
@@ -3461,7 +3222,7 @@ class RequestValidator {
3461
3222
  CodeChallengeMethodValues.PLAIN,
3462
3223
  CodeChallengeMethodValues.S256,
3463
3224
  ].indexOf(codeChallengeMethod) < 0) {
3464
- throw ClientConfigurationError.createInvalidCodeChallengeMethodError();
3225
+ throw createClientConfigurationError(invalidCodeChallengeMethod);
3465
3226
  }
3466
3227
  }
3467
3228
  /**
@@ -3680,7 +3441,7 @@ class RequestParameterBuilder {
3680
3441
  this.parameters.set(AADServerParamKeys.CODE_CHALLENGE_METHOD, encodeURIComponent(codeChallengeMethod));
3681
3442
  }
3682
3443
  else {
3683
- throw ClientConfigurationError.createInvalidCodeChallengeParamsError();
3444
+ throw createClientConfigurationError(pkceParamsMissing);
3684
3445
  }
3685
3446
  }
3686
3447
  /**
@@ -3785,7 +3546,7 @@ class RequestParameterBuilder {
3785
3546
  mergedClaims = JSON.parse(claims);
3786
3547
  }
3787
3548
  catch (e) {
3788
- throw ClientConfigurationError.createInvalidClaimsRequestError();
3549
+ throw createClientConfigurationError(invalidClaims);
3789
3550
  }
3790
3551
  }
3791
3552
  if (clientCapabilities && clientCapabilities.length > 0) {
@@ -4076,6 +3837,14 @@ const PerformanceEvents = {
4076
3837
  * Cache operations
4077
3838
  */
4078
3839
  ClearTokensAndKeysWithClaims: "clearTokensAndKeysWithClaims",
3840
+ /**
3841
+ * Crypto Operations
3842
+ */
3843
+ GeneratePkceCodes: "generatePkceCodes",
3844
+ GenerateCodeVerifier: "generateCodeVerifier",
3845
+ GenerateCodeChallengeFromVerifier: "generateCodeChallengeFromVerifier",
3846
+ Sha256Digest: "sha256Digest",
3847
+ GetRandomValues: "getRandomValues",
4079
3848
  };
4080
3849
  /**
4081
3850
  * State of the performance event.
@@ -4162,7 +3931,7 @@ class BaseClient {
4162
3931
  * @param thumbprint
4163
3932
  */
4164
3933
  async executePostToTokenEndpoint(tokenEndpoint, queryString, headers, thumbprint, correlationId) {
4165
- this.performanceClient?.addQueueMeasurement(PerformanceEvents.BaseClientCreateTokenRequestHeaders, correlationId);
3934
+ this.performanceClient?.addQueueMeasurement(PerformanceEvents.BaseClientExecutePostToTokenEndpoint, correlationId);
4166
3935
  const response = await this.networkManager.sendPostRequest(thumbprint, tokenEndpoint, { body: queryString, headers: headers });
4167
3936
  this.performanceClient?.addFields({
4168
3937
  refreshTokenSize: response.body.refresh_token?.length || 0,
@@ -4182,7 +3951,7 @@ class BaseClient {
4182
3951
  */
4183
3952
  updateAuthority(updatedAuthority) {
4184
3953
  if (!updatedAuthority.discoveryComplete()) {
4185
- throw ClientAuthError.createEndpointDiscoveryIncompleteError("Updated authority has not completed endpoint discovery.");
3954
+ throw createClientAuthError(endpointResolutionError);
4186
3955
  }
4187
3956
  this.authority = updatedAuthority;
4188
3957
  }
@@ -4263,7 +4032,7 @@ class CredentialEntity {
4263
4032
  case CredentialType.REFRESH_TOKEN:
4264
4033
  return CacheType.REFRESH_TOKEN;
4265
4034
  default: {
4266
- throw ClientAuthError.createUnexpectedCredentialTypeError();
4035
+ throw createClientAuthError(unexpectedCredentialType);
4267
4036
  }
4268
4037
  }
4269
4038
  }
@@ -4518,7 +4287,7 @@ class AccessTokenEntity extends CredentialEntity {
4518
4287
  // Make sure keyId is present and add it to credential
4519
4288
  const tokenClaims = extractTokenClaims(accessToken, cryptoUtils.base64Decode);
4520
4289
  if (!tokenClaims?.cnf?.kid) {
4521
- throw ClientAuthError.createTokenClaimsRequiredError();
4290
+ throw createClientAuthError(tokenClaimsCnfRequiredForSignedJwt);
4522
4291
  }
4523
4292
  atEntity.keyId = tokenClaims.cnf.kid;
4524
4293
  break;
@@ -4609,6 +4378,27 @@ class RefreshTokenEntity extends CredentialEntity {
4609
4378
  }
4610
4379
  }
4611
4380
 
4381
+ /*
4382
+ * Copyright (c) Microsoft Corporation. All rights reserved.
4383
+ * Licensed under the MIT License.
4384
+ */
4385
+ // Codes defined by MSAL
4386
+ const noTokensFound = "no_tokens_found";
4387
+ const nativeAccountUnavailable = "native_account_unavailable";
4388
+ // Codes potentially returned by server
4389
+ const interactionRequired = "interaction_required";
4390
+ const consentRequired = "consent_required";
4391
+ const loginRequired = "login_required";
4392
+
4393
+ var InteractionRequiredAuthErrorCodes = /*#__PURE__*/Object.freeze({
4394
+ __proto__: null,
4395
+ consentRequired: consentRequired,
4396
+ interactionRequired: interactionRequired,
4397
+ loginRequired: loginRequired,
4398
+ nativeAccountUnavailable: nativeAccountUnavailable,
4399
+ noTokensFound: noTokensFound
4400
+ });
4401
+
4612
4402
  /*
4613
4403
  * Copyright (c) Microsoft Corporation. All rights reserved.
4614
4404
  * Licensed under the MIT License.
@@ -4617,9 +4407,9 @@ class RefreshTokenEntity extends CredentialEntity {
4617
4407
  * InteractionRequiredServerErrorMessage contains string constants used by error codes and messages returned by the server indicating interaction is required
4618
4408
  */
4619
4409
  const InteractionRequiredServerErrorMessage = [
4620
- "interaction_required",
4621
- "consent_required",
4622
- "login_required",
4410
+ interactionRequired,
4411
+ consentRequired,
4412
+ loginRequired,
4623
4413
  ];
4624
4414
  const InteractionRequiredAuthSubErrorMessage = [
4625
4415
  "message_only",
@@ -4628,17 +4418,22 @@ const InteractionRequiredAuthSubErrorMessage = [
4628
4418
  "user_password_expired",
4629
4419
  "consent_required",
4630
4420
  ];
4421
+ const InteractionRequiredAuthErrorMessages = {
4422
+ [noTokensFound]: "No refresh token found in the cache. Please sign-in.",
4423
+ [nativeAccountUnavailable]: "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.",
4424
+ };
4631
4425
  /**
4632
4426
  * Interaction required errors defined by the SDK
4427
+ * @deprecated Use InteractionRequiredAuthErrorCodes instead
4633
4428
  */
4634
4429
  const InteractionRequiredAuthErrorMessage = {
4635
4430
  noTokensFoundError: {
4636
- code: "no_tokens_found",
4637
- desc: "No refresh token found in the cache. Please sign-in.",
4431
+ code: noTokensFound,
4432
+ desc: InteractionRequiredAuthErrorMessages[noTokensFound],
4638
4433
  },
4639
4434
  native_account_unavailable: {
4640
- code: "native_account_unavailable",
4641
- 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.",
4435
+ code: nativeAccountUnavailable,
4436
+ desc: InteractionRequiredAuthErrorMessages[nativeAccountUnavailable],
4642
4437
  },
4643
4438
  };
4644
4439
  /**
@@ -4654,38 +4449,31 @@ class InteractionRequiredAuthError extends AuthError {
4654
4449
  this.claims = claims || Constants.EMPTY_STRING;
4655
4450
  this.name = "InteractionRequiredAuthError";
4656
4451
  }
4657
- /**
4658
- * Helper function used to determine if an error thrown by the server requires interaction to resolve
4659
- * @param errorCode
4660
- * @param errorString
4661
- * @param subError
4662
- */
4663
- static isInteractionRequiredError(errorCode, errorString, subError) {
4664
- const isInteractionRequiredErrorCode = !!errorCode &&
4665
- InteractionRequiredServerErrorMessage.indexOf(errorCode) > -1;
4666
- const isInteractionRequiredSubError = !!subError &&
4667
- InteractionRequiredAuthSubErrorMessage.indexOf(subError) > -1;
4668
- const isInteractionRequiredErrorDesc = !!errorString &&
4669
- InteractionRequiredServerErrorMessage.some((irErrorCode) => {
4670
- return errorString.indexOf(irErrorCode) > -1;
4671
- });
4672
- return (isInteractionRequiredErrorCode ||
4673
- isInteractionRequiredErrorDesc ||
4674
- isInteractionRequiredSubError);
4675
- }
4676
- /**
4677
- * Creates an error thrown when the authorization code required for a token request is null or empty.
4678
- */
4679
- static createNoTokensFoundError() {
4680
- return new InteractionRequiredAuthError(InteractionRequiredAuthErrorMessage.noTokensFoundError.code, InteractionRequiredAuthErrorMessage.noTokensFoundError.desc);
4681
- }
4682
- /**
4683
- * Creates an error thrown when the native broker returns ACCOUNT_UNAVAILABLE status, indicating that the account was removed and interactive sign-in is required
4684
- * @returns
4685
- */
4686
- static createNativeAccountUnavailableError() {
4687
- return new InteractionRequiredAuthError(InteractionRequiredAuthErrorMessage.native_account_unavailable.code, InteractionRequiredAuthErrorMessage.native_account_unavailable.desc);
4688
- }
4452
+ }
4453
+ /**
4454
+ * Helper function used to determine if an error thrown by the server requires interaction to resolve
4455
+ * @param errorCode
4456
+ * @param errorString
4457
+ * @param subError
4458
+ */
4459
+ function isInteractionRequiredError(errorCode, errorString, subError) {
4460
+ const isInteractionRequiredErrorCode = !!errorCode &&
4461
+ InteractionRequiredServerErrorMessage.indexOf(errorCode) > -1;
4462
+ const isInteractionRequiredSubError = !!subError &&
4463
+ InteractionRequiredAuthSubErrorMessage.indexOf(subError) > -1;
4464
+ const isInteractionRequiredErrorDesc = !!errorString &&
4465
+ InteractionRequiredServerErrorMessage.some((irErrorCode) => {
4466
+ return errorString.indexOf(irErrorCode) > -1;
4467
+ });
4468
+ return (isInteractionRequiredErrorCode ||
4469
+ isInteractionRequiredErrorDesc ||
4470
+ isInteractionRequiredSubError);
4471
+ }
4472
+ /**
4473
+ * Creates an InteractionRequiredAuthError
4474
+ */
4475
+ function createInteractionRequiredAuthError(errorCode) {
4476
+ return new InteractionRequiredAuthError(errorCode, InteractionRequiredAuthErrorMessages[errorCode]);
4689
4477
  }
4690
4478
 
4691
4479
  /*
@@ -4729,7 +4517,7 @@ class ProtocolUtils {
4729
4517
  */
4730
4518
  static generateLibraryState(cryptoObj, meta) {
4731
4519
  if (!cryptoObj) {
4732
- throw ClientAuthError.createNoCryptoObjectError("generateLibraryState");
4520
+ throw createClientAuthError(noCryptoObject);
4733
4521
  }
4734
4522
  // Create a state object containing a unique id and the timestamp of the request creation
4735
4523
  const stateObj = {
@@ -4748,10 +4536,10 @@ class ProtocolUtils {
4748
4536
  */
4749
4537
  static parseRequestState(cryptoObj, state) {
4750
4538
  if (!cryptoObj) {
4751
- throw ClientAuthError.createNoCryptoObjectError("parseRequestState");
4539
+ throw createClientAuthError(noCryptoObject);
4752
4540
  }
4753
4541
  if (!state) {
4754
- throw ClientAuthError.createInvalidStateError(state, "Null, undefined or empty state");
4542
+ throw createClientAuthError(invalidState);
4755
4543
  }
4756
4544
  try {
4757
4545
  // Split the state between library state and user passed state and decode them separately
@@ -4768,7 +4556,7 @@ class ProtocolUtils {
4768
4556
  };
4769
4557
  }
4770
4558
  catch (e) {
4771
- throw ClientAuthError.createInvalidStateError(state, e);
4559
+ throw createClientAuthError(invalidState);
4772
4560
  }
4773
4561
  }
4774
4562
  }
@@ -4788,7 +4576,7 @@ class UrlString {
4788
4576
  this._urlString = url;
4789
4577
  if (!this._urlString) {
4790
4578
  // Throws error if url is empty
4791
- throw ClientConfigurationError.createUrlEmptyError();
4579
+ throw createClientConfigurationError(urlEmptyError);
4792
4580
  }
4793
4581
  if (!this.getHash()) {
4794
4582
  this._urlString = UrlString.canonicalizeUri(url);
@@ -4824,16 +4612,16 @@ class UrlString {
4824
4612
  components = this.getUrlComponents();
4825
4613
  }
4826
4614
  catch (e) {
4827
- throw ClientConfigurationError.createUrlParseError(e);
4615
+ throw createClientConfigurationError(urlParseError);
4828
4616
  }
4829
4617
  // Throw error if URI or path segments are not parseable.
4830
4618
  if (!components.HostNameAndPort || !components.PathSegments) {
4831
- throw ClientConfigurationError.createUrlParseError(`Given url string: ${this.urlString}`);
4619
+ throw createClientConfigurationError(urlParseError);
4832
4620
  }
4833
4621
  // Throw error if uri is insecure.
4834
4622
  if (!components.Protocol ||
4835
4623
  components.Protocol.toLowerCase() !== "https:") {
4836
- throw ClientConfigurationError.createInsecureAuthorityUriError(this.urlString);
4624
+ throw createClientConfigurationError(authorityUriInsecure);
4837
4625
  }
4838
4626
  }
4839
4627
  /**
@@ -4888,7 +4676,7 @@ class UrlString {
4888
4676
  // If url string does not match regEx, we throw an error
4889
4677
  const match = this.urlString.match(regEx);
4890
4678
  if (!match) {
4891
- throw ClientConfigurationError.createUrlParseError(`Given url string: ${this.urlString}`);
4679
+ throw createClientConfigurationError(urlParseError);
4892
4680
  }
4893
4681
  // Url component object
4894
4682
  const urlComponents = {
@@ -4910,7 +4698,7 @@ class UrlString {
4910
4698
  const regEx = RegExp("^([^:/?#]+://)?([^/?#]*)");
4911
4699
  const match = url.match(regEx);
4912
4700
  if (!match) {
4913
- throw ClientConfigurationError.createUrlParseError(`Given url string: ${url}`);
4701
+ throw createClientConfigurationError(urlParseError);
4914
4702
  }
4915
4703
  return match[2];
4916
4704
  }
@@ -5000,7 +4788,7 @@ class UrlString {
5000
4788
  const deserializedHash = StringUtils.queryStringToObject(parsedHash || hash);
5001
4789
  // Check if deserialization didn't work
5002
4790
  if (!deserializedHash) {
5003
- throw ClientAuthError.createHashNotDeserializedError(JSON.stringify(deserializedHash));
4791
+ throw createClientAuthError(hashNotDeserialized);
5004
4792
  }
5005
4793
  return deserializedHash;
5006
4794
  }
@@ -5018,7 +4806,7 @@ class UrlString {
5018
4806
  const deserializedQueryString = StringUtils.queryStringToObject(parsedQueryString || query);
5019
4807
  // Check if deserialization didn't work
5020
4808
  if (!deserializedQueryString) {
5021
- throw ClientAuthError.createHashNotDeserializedError(JSON.stringify(deserializedQueryString));
4809
+ throw createClientAuthError(hashNotDeserialized);
5022
4810
  }
5023
4811
  return deserializedQueryString;
5024
4812
  }
@@ -5053,6 +4841,91 @@ class UrlString {
5053
4841
  }
5054
4842
  }
5055
4843
 
4844
+ /*
4845
+ * Copyright (c) Microsoft Corporation. All rights reserved.
4846
+ * Licensed under the MIT License.
4847
+ */
4848
+ /**
4849
+ * Wraps a function with a performance measurement.
4850
+ * Usage: invoke(functionToCall, performanceClient, "EventName", "correlationId")(...argsToPassToFunction)
4851
+ * @param callback
4852
+ * @param eventName
4853
+ * @param logger
4854
+ * @param telemetryClient
4855
+ * @param correlationId
4856
+ * @returns
4857
+ * @internal
4858
+ */
4859
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
4860
+ const invoke = (callback, eventName, logger, telemetryClient, correlationId) => {
4861
+ return (...args) => {
4862
+ logger.trace(`Executing function ${eventName}`);
4863
+ const inProgressEvent = telemetryClient?.startMeasurement(eventName, correlationId);
4864
+ try {
4865
+ const result = callback(...args);
4866
+ inProgressEvent?.end({
4867
+ success: true,
4868
+ });
4869
+ logger.trace(`Returning result from ${eventName}`);
4870
+ return result;
4871
+ }
4872
+ catch (e) {
4873
+ logger.trace(`Error occurred in ${eventName}`);
4874
+ try {
4875
+ logger.trace(JSON.stringify(e));
4876
+ }
4877
+ catch (e) {
4878
+ logger.trace("Unable to print error message.");
4879
+ }
4880
+ inProgressEvent?.end({
4881
+ success: false,
4882
+ });
4883
+ throw e;
4884
+ }
4885
+ };
4886
+ };
4887
+ /**
4888
+ * Wraps an async function with a performance measurement.
4889
+ * Usage: invokeAsync(functionToCall, performanceClient, "EventName", "correlationId")(...argsToPassToFunction)
4890
+ * @param callback
4891
+ * @param eventName
4892
+ * @param logger
4893
+ * @param telemetryClient
4894
+ * @param correlationId
4895
+ * @returns
4896
+ * @internal
4897
+ *
4898
+ */
4899
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
4900
+ const invokeAsync = (callback, eventName, logger, telemetryClient, correlationId) => {
4901
+ return (...args) => {
4902
+ logger.trace(`Executing function ${eventName}`);
4903
+ const inProgressEvent = telemetryClient?.startMeasurement(eventName, correlationId);
4904
+ telemetryClient?.setPreQueueTime(eventName, correlationId);
4905
+ return callback(...args)
4906
+ .then((response) => {
4907
+ logger.trace(`Returning result from ${eventName}`);
4908
+ inProgressEvent?.end({
4909
+ success: true,
4910
+ });
4911
+ return response;
4912
+ })
4913
+ .catch((e) => {
4914
+ logger.trace(`Error occurred in ${eventName}`);
4915
+ try {
4916
+ logger.trace(JSON.stringify(e));
4917
+ }
4918
+ catch (e) {
4919
+ logger.trace("Unable to print error message.");
4920
+ }
4921
+ inProgressEvent?.end({
4922
+ success: false,
4923
+ });
4924
+ throw e;
4925
+ });
4926
+ };
4927
+ };
4928
+
5056
4929
  /*
5057
4930
  * Copyright (c) Microsoft Corporation. All rights reserved.
5058
4931
  * Licensed under the MIT License.
@@ -5073,10 +4946,9 @@ class PopTokenGenerator {
5073
4946
  * @param request
5074
4947
  * @returns
5075
4948
  */
5076
- async generateCnf(request) {
4949
+ async generateCnf(request, logger) {
5077
4950
  this.performanceClient?.addQueueMeasurement(PerformanceEvents.PopTokenGenerateCnf, request.correlationId);
5078
- this.performanceClient?.setPreQueueTime(PerformanceEvents.PopTokenGenerateKid, request.correlationId);
5079
- const reqCnf = await this.generateKid(request);
4951
+ const reqCnf = await invokeAsync(this.generateKid.bind(this), PerformanceEvents.PopTokenGenerateCnf, logger, this.performanceClient, request.correlationId)(request);
5080
4952
  const reqCnfString = this.cryptoUtils.base64Encode(JSON.stringify(reqCnf));
5081
4953
  return {
5082
4954
  kid: reqCnf.kid,
@@ -5257,8 +5129,8 @@ class ResponseHandler {
5257
5129
  validateServerAuthorizationCodeResponse(serverResponseHash, cachedState, cryptoObj) {
5258
5130
  if (!serverResponseHash.state || !cachedState) {
5259
5131
  throw serverResponseHash.state
5260
- ? ClientAuthError.createStateNotFoundError("Cached State")
5261
- : ClientAuthError.createStateNotFoundError("Server State");
5132
+ ? createClientAuthError(stateNotFound, "Cached State")
5133
+ : createClientAuthError(stateNotFound, "Server State");
5262
5134
  }
5263
5135
  let decodedServerResponseHash;
5264
5136
  let decodedCachedState;
@@ -5266,22 +5138,22 @@ class ResponseHandler {
5266
5138
  decodedServerResponseHash = decodeURIComponent(serverResponseHash.state);
5267
5139
  }
5268
5140
  catch (e) {
5269
- throw ClientAuthError.createInvalidStateError(serverResponseHash.state, `Server response hash URI could not be decoded`);
5141
+ throw createClientAuthError(invalidState, serverResponseHash.state);
5270
5142
  }
5271
5143
  try {
5272
5144
  decodedCachedState = decodeURIComponent(cachedState);
5273
5145
  }
5274
5146
  catch (e) {
5275
- throw ClientAuthError.createInvalidStateError(serverResponseHash.state, `Cached state URI could not be decoded`);
5147
+ throw createClientAuthError(invalidState, serverResponseHash.state);
5276
5148
  }
5277
5149
  if (decodedServerResponseHash !== decodedCachedState) {
5278
- throw ClientAuthError.createStateMismatchError();
5150
+ throw createClientAuthError(stateMismatch);
5279
5151
  }
5280
5152
  // Check for error
5281
5153
  if (serverResponseHash.error ||
5282
5154
  serverResponseHash.error_description ||
5283
5155
  serverResponseHash.suberror) {
5284
- if (InteractionRequiredAuthError.isInteractionRequiredError(serverResponseHash.error, serverResponseHash.error_description, serverResponseHash.suberror)) {
5156
+ if (isInteractionRequiredError(serverResponseHash.error, serverResponseHash.error_description, serverResponseHash.suberror)) {
5285
5157
  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);
5286
5158
  }
5287
5159
  throw new ServerError(serverResponseHash.error || Constants.EMPTY_STRING, serverResponseHash.error_description, serverResponseHash.suberror);
@@ -5320,7 +5192,7 @@ class ResponseHandler {
5320
5192
  // don't throw an exception, but alert the user via a log that the token was unable to be refreshed
5321
5193
  return;
5322
5194
  }
5323
- if (InteractionRequiredAuthError.isInteractionRequiredError(serverResponse.error, serverResponse.error_description, serverResponse.suberror)) {
5195
+ if (isInteractionRequiredError(serverResponse.error, serverResponse.error_description, serverResponse.suberror)) {
5324
5196
  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);
5325
5197
  }
5326
5198
  throw serverError;
@@ -5340,14 +5212,14 @@ class ResponseHandler {
5340
5212
  // token nonce check (TODO: Add a warning if no nonce is given?)
5341
5213
  if (authCodePayload && authCodePayload.nonce) {
5342
5214
  if (idTokenClaims.nonce !== authCodePayload.nonce) {
5343
- throw ClientAuthError.createNonceMismatchError();
5215
+ throw createClientAuthError(nonceMismatch);
5344
5216
  }
5345
5217
  }
5346
5218
  // token max_age check
5347
5219
  if (request.maxAge || request.maxAge === 0) {
5348
5220
  const authTime = idTokenClaims.auth_time;
5349
5221
  if (!authTime) {
5350
- throw ClientAuthError.createAuthTimeNotFoundError();
5222
+ throw createClientAuthError(authTimeNotFound);
5351
5223
  }
5352
5224
  checkMaxAge(authTime, request.maxAge);
5353
5225
  }
@@ -5407,7 +5279,7 @@ class ResponseHandler {
5407
5279
  generateCacheRecord(serverTokenResponse, authority, reqTimestamp, request, idTokenClaims, userAssertionHash, authCodePayload) {
5408
5280
  const env = authority.getPreferredCache();
5409
5281
  if (!env) {
5410
- throw ClientAuthError.createInvalidCacheEnvironmentError();
5282
+ throw createClientAuthError(invalidCacheEnvironment);
5411
5283
  }
5412
5284
  // IdToken: non AAD scenarios can have empty realm
5413
5285
  let cachedIdToken;
@@ -5484,7 +5356,7 @@ class ResponseHandler {
5484
5356
  const popTokenGenerator = new PopTokenGenerator(cryptoObj);
5485
5357
  const { secret, keyId } = cacheRecord.accessToken;
5486
5358
  if (!keyId) {
5487
- throw ClientAuthError.createKeyIdMissingError();
5359
+ throw createClientAuthError(keyIdMissing);
5488
5360
  }
5489
5361
  accessToken = await popTokenGenerator.signPopToken(secret, keyId, request);
5490
5362
  }
@@ -5542,92 +5414,6 @@ class ResponseHandler {
5542
5414
  }
5543
5415
  }
5544
5416
 
5545
- /*
5546
- * Copyright (c) Microsoft Corporation. All rights reserved.
5547
- * Licensed under the MIT License.
5548
- */
5549
- /**
5550
- * Wraps a function with a performance measurement.
5551
- * Usage: invoke(functionToCall, performanceClient, "EventName", "correlationId")(...argsToPassToFunction)
5552
- * @param callback
5553
- * @param eventName
5554
- * @param logger
5555
- * @param telemetryClient
5556
- * @param correlationId
5557
- * @returns
5558
- * @internal
5559
- */
5560
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
5561
- const invoke = (callback, eventName, logger, telemetryClient, correlationId) => {
5562
- return (...args) => {
5563
- logger.trace(`Executing function ${eventName}`);
5564
- const inProgressEvent = telemetryClient?.startMeasurement(eventName, correlationId);
5565
- telemetryClient?.setPreQueueTime(eventName, correlationId);
5566
- try {
5567
- const result = callback(...args);
5568
- inProgressEvent?.end({
5569
- success: true,
5570
- });
5571
- logger.trace(`Returning result from ${eventName}`);
5572
- return result;
5573
- }
5574
- catch (e) {
5575
- logger.trace(`Error occurred in ${eventName}`);
5576
- try {
5577
- logger.trace(JSON.stringify(e));
5578
- }
5579
- catch (e) {
5580
- logger.trace("Unable to print error message.");
5581
- }
5582
- inProgressEvent?.end({
5583
- success: false,
5584
- });
5585
- throw e;
5586
- }
5587
- };
5588
- };
5589
- /**
5590
- * Wraps an async function with a performance measurement.
5591
- * Usage: invokeAsync(functionToCall, performanceClient, "EventName", "correlationId")(...argsToPassToFunction)
5592
- * @param callback
5593
- * @param eventName
5594
- * @param logger
5595
- * @param telemetryClient
5596
- * @param correlationId
5597
- * @returns
5598
- * @internal
5599
- *
5600
- */
5601
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
5602
- const invokeAsync = (callback, eventName, logger, telemetryClient, correlationId) => {
5603
- return (...args) => {
5604
- logger.trace(`Executing function ${eventName}`);
5605
- const inProgressEvent = telemetryClient?.startMeasurement(eventName, correlationId);
5606
- telemetryClient?.setPreQueueTime(eventName, correlationId);
5607
- return callback(...args)
5608
- .then((response) => {
5609
- logger.trace(`Returning result from ${eventName}`);
5610
- inProgressEvent?.end({
5611
- success: true,
5612
- });
5613
- return response;
5614
- })
5615
- .catch((e) => {
5616
- logger.trace(`Error occurred in ${eventName}`);
5617
- try {
5618
- logger.trace(JSON.stringify(e));
5619
- }
5620
- catch (e) {
5621
- logger.trace("Unable to print error message.");
5622
- }
5623
- inProgressEvent?.end({
5624
- success: false,
5625
- });
5626
- throw e;
5627
- });
5628
- };
5629
- };
5630
-
5631
5417
  /*
5632
5418
  * Copyright (c) Microsoft Corporation. All rights reserved.
5633
5419
  * Licensed under the MIT License.
@@ -5667,7 +5453,7 @@ class AuthorizationCodeClient extends BaseClient {
5667
5453
  async acquireToken(request, authCodePayload) {
5668
5454
  this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthClientAcquireToken, request.correlationId);
5669
5455
  if (!request.code) {
5670
- throw ClientAuthError.createTokenRequestCannotBeMadeError();
5456
+ throw createClientAuthError(requestCannotBeMade);
5671
5457
  }
5672
5458
  const reqTimestamp = TimeUtils.nowSeconds();
5673
5459
  const response = await invokeAsync(this.executeTokenRequest.bind(this), PerformanceEvents.AuthClientExecuteTokenRequest, this.logger, this.performanceClient, request.correlationId)(this.authority, request);
@@ -5692,7 +5478,7 @@ class AuthorizationCodeClient extends BaseClient {
5692
5478
  responseHandler.validateServerAuthorizationCodeResponse(serverParams, cachedState, this.cryptoUtils);
5693
5479
  // throw when there is no auth code in the response
5694
5480
  if (!serverParams.code) {
5695
- throw ClientAuthError.createNoAuthCodeInServerResponseError();
5481
+ throw createClientAuthError(authorizationCodeMissingFromServerResponse);
5696
5482
  }
5697
5483
  return {
5698
5484
  ...serverParams,
@@ -5708,7 +5494,7 @@ class AuthorizationCodeClient extends BaseClient {
5708
5494
  getLogoutUri(logoutRequest) {
5709
5495
  // Throw error if logoutRequest is null/undefined
5710
5496
  if (!logoutRequest) {
5711
- throw ClientConfigurationError.createEmptyLogoutRequestError();
5497
+ throw createClientConfigurationError(logoutRequestEmpty);
5712
5498
  }
5713
5499
  const queryString = this.createLogoutUrlQueryString(logoutRequest);
5714
5500
  // Construct logout URI
@@ -5739,7 +5525,8 @@ class AuthorizationCodeClient extends BaseClient {
5739
5525
  }
5740
5526
  const headers = this.createTokenRequestHeaders(ccsCredential || request.ccsCredential);
5741
5527
  const thumbprint = {
5742
- clientId: this.config.authOptions.clientId,
5528
+ clientId: request.tokenBodyParameters?.clientId ||
5529
+ this.config.authOptions.clientId,
5743
5530
  authority: authority.canonicalAuthority,
5744
5531
  scopes: request.scopes,
5745
5532
  claims: request.claims,
@@ -5799,8 +5586,7 @@ class AuthorizationCodeClient extends BaseClient {
5799
5586
  parameterBuilder.addClientInfo();
5800
5587
  if (request.authenticationScheme === AuthenticationScheme.POP) {
5801
5588
  const popTokenGenerator = new PopTokenGenerator(this.cryptoUtils, this.performanceClient);
5802
- this.performanceClient?.setPreQueueTime(PerformanceEvents.PopTokenGenerateCnf, request.correlationId);
5803
- const reqCnfData = await popTokenGenerator.generateCnf(request);
5589
+ const reqCnfData = await invokeAsync(popTokenGenerator.generateCnf.bind(popTokenGenerator), PerformanceEvents.PopTokenGenerateCnf, this.logger, this.performanceClient, request.correlationId)(request, this.logger);
5804
5590
  // SPA PoP requires full Base64Url encoded req_cnf string (unhashed)
5805
5591
  parameterBuilder.addPopToken(reqCnfData.reqCnfString);
5806
5592
  }
@@ -5809,7 +5595,7 @@ class AuthorizationCodeClient extends BaseClient {
5809
5595
  parameterBuilder.addSshJwk(request.sshJwk);
5810
5596
  }
5811
5597
  else {
5812
- throw ClientConfigurationError.createMissingSshJwkError();
5598
+ throw createClientConfigurationError(missingSshJwk);
5813
5599
  }
5814
5600
  }
5815
5601
  const correlationId = request.correlationId ||
@@ -5993,7 +5779,7 @@ class AuthorizationCodeClient extends BaseClient {
5993
5779
  if (request.authenticationScheme === AuthenticationScheme.POP) {
5994
5780
  const popTokenGenerator = new PopTokenGenerator(this.cryptoUtils);
5995
5781
  // to reduce the URL length, it is recommended to send the hash of the req_cnf instead of the whole string
5996
- const reqCnfData = await popTokenGenerator.generateCnf(request);
5782
+ const reqCnfData = await invokeAsync(popTokenGenerator.generateCnf.bind(popTokenGenerator), PerformanceEvents.PopTokenGenerateCnf, this.logger, this.performanceClient, request.correlationId)(request, this.logger);
5997
5783
  parameterBuilder.addPopToken(reqCnfData.reqCnfHash);
5998
5784
  }
5999
5785
  }
@@ -6051,33 +5837,13 @@ class RefreshTokenClient extends BaseClient {
6051
5837
  }
6052
5838
  async acquireToken(request) {
6053
5839
  this.performanceClient?.addQueueMeasurement(PerformanceEvents.RefreshTokenClientAcquireToken, request.correlationId);
6054
- const atsMeasurement = this.performanceClient?.startMeasurement(PerformanceEvents.RefreshTokenClientAcquireToken, request.correlationId);
6055
- this.logger.verbose("RefreshTokenClientAcquireToken called", request.correlationId);
6056
5840
  const reqTimestamp = TimeUtils.nowSeconds();
6057
- this.performanceClient?.setPreQueueTime(PerformanceEvents.RefreshTokenClientExecuteTokenRequest, request.correlationId);
6058
- const response = await this.executeTokenRequest(request, this.authority);
5841
+ const response = await invokeAsync(this.executeTokenRequest.bind(this), PerformanceEvents.RefreshTokenClientExecuteTokenRequest, this.logger, this.performanceClient, request.correlationId)(request, this.authority);
6059
5842
  // Retrieve requestId from response headers
6060
5843
  const requestId = response.headers?.[HeaderNames.X_MS_REQUEST_ID];
6061
5844
  const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.config.serializableCache, this.config.persistencePlugin);
6062
5845
  responseHandler.validateTokenResponse(response.body);
6063
- this.performanceClient?.setPreQueueTime(PerformanceEvents.HandleServerTokenResponse, request.correlationId);
6064
- return responseHandler
6065
- .handleServerTokenResponse(response.body, this.authority, reqTimestamp, request, undefined, undefined, true, request.forceCache, requestId)
6066
- .then((result) => {
6067
- atsMeasurement?.end({
6068
- success: true,
6069
- });
6070
- return result;
6071
- })
6072
- .catch((error) => {
6073
- this.logger.verbose("Error in fetching refresh token", request.correlationId);
6074
- atsMeasurement?.end({
6075
- errorCode: error.errorCode,
6076
- subErrorCode: error.subError,
6077
- success: false,
6078
- });
6079
- throw error;
6080
- });
5846
+ return invokeAsync(responseHandler.handleServerTokenResponse.bind(responseHandler), PerformanceEvents.HandleServerTokenResponse, this.logger, this.performanceClient, request.correlationId)(response.body, this.authority, reqTimestamp, request, undefined, undefined, true, request.forceCache, requestId);
6081
5847
  }
6082
5848
  /**
6083
5849
  * Gets cached refresh token and attaches to request, then calls acquireToken API
@@ -6086,33 +5852,30 @@ class RefreshTokenClient extends BaseClient {
6086
5852
  async acquireTokenByRefreshToken(request) {
6087
5853
  // Cannot renew token if no request object is given.
6088
5854
  if (!request) {
6089
- throw ClientConfigurationError.createEmptyTokenRequestError();
5855
+ throw createClientConfigurationError(tokenRequestEmpty);
6090
5856
  }
6091
5857
  this.performanceClient?.addQueueMeasurement(PerformanceEvents.RefreshTokenClientAcquireTokenByRefreshToken, request.correlationId);
6092
5858
  // We currently do not support silent flow for account === null use cases; This will be revisited for confidential flow usecases
6093
5859
  if (!request.account) {
6094
- throw ClientAuthError.createNoAccountInSilentRequestError();
5860
+ throw createClientAuthError(noAccountInSilentRequest);
6095
5861
  }
6096
5862
  // try checking if FOCI is enabled for the given application
6097
5863
  const isFOCI = this.cacheManager.isAppMetadataFOCI(request.account.environment);
6098
5864
  // if the app is part of the family, retrive a Family refresh token if present and make a refreshTokenRequest
6099
5865
  if (isFOCI) {
6100
5866
  try {
6101
- this.performanceClient?.setPreQueueTime(PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken, request.correlationId);
6102
- return this.acquireTokenWithCachedRefreshToken(request, true);
5867
+ return invokeAsync(this.acquireTokenWithCachedRefreshToken.bind(this), PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken, this.logger, this.performanceClient, request.correlationId)(request, true);
6103
5868
  }
6104
5869
  catch (e) {
6105
5870
  const noFamilyRTInCache = e instanceof InteractionRequiredAuthError &&
6106
5871
  e.errorCode ===
6107
- InteractionRequiredAuthErrorMessage.noTokensFoundError
6108
- .code;
5872
+ noTokensFound;
6109
5873
  const clientMismatchErrorWithFamilyRT = e instanceof ServerError &&
6110
5874
  e.errorCode === Errors.INVALID_GRANT_ERROR &&
6111
5875
  e.subError === Errors.CLIENT_MISMATCH_ERROR;
6112
5876
  // if family Refresh Token (FRT) cache acquisition fails or if client_mismatch error is seen with FRT, reattempt with application Refresh Token (ART)
6113
5877
  if (noFamilyRTInCache || clientMismatchErrorWithFamilyRT) {
6114
- this.performanceClient?.setPreQueueTime(PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken, request.correlationId);
6115
- return this.acquireTokenWithCachedRefreshToken(request, false);
5878
+ return invokeAsync(this.acquireTokenWithCachedRefreshToken.bind(this), PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken, this.logger, this.performanceClient, request.correlationId)(request, false);
6116
5879
  // throw in all other cases
6117
5880
  }
6118
5881
  else {
@@ -6121,8 +5884,7 @@ class RefreshTokenClient extends BaseClient {
6121
5884
  }
6122
5885
  }
6123
5886
  // fall back to application refresh token acquisition
6124
- this.performanceClient?.setPreQueueTime(PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken, request.correlationId);
6125
- return this.acquireTokenWithCachedRefreshToken(request, false);
5887
+ return invokeAsync(this.acquireTokenWithCachedRefreshToken.bind(this), PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken, this.logger, this.performanceClient, request.correlationId)(request, false);
6126
5888
  }
6127
5889
  /**
6128
5890
  * makes a network call to acquire tokens by exchanging RefreshToken available in userCache; throws if refresh token is not cached
@@ -6131,17 +5893,11 @@ class RefreshTokenClient extends BaseClient {
6131
5893
  async acquireTokenWithCachedRefreshToken(request, foci) {
6132
5894
  this.performanceClient?.addQueueMeasurement(PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken, request.correlationId);
6133
5895
  // fetches family RT or application RT based on FOCI value
6134
- const atsMeasurement = this.performanceClient?.startMeasurement(PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken, request.correlationId);
6135
- this.logger.verbose("RefreshTokenClientAcquireTokenWithCachedRefreshToken called", request.correlationId);
6136
5896
  const refreshToken = this.cacheManager.getRefreshToken(request.account, foci);
6137
5897
  if (!refreshToken) {
6138
- atsMeasurement?.discard();
6139
- throw InteractionRequiredAuthError.createNoTokensFoundError();
5898
+ throw createInteractionRequiredAuthError(noTokensFound);
6140
5899
  }
6141
5900
  // attach cached RT size to the current measurement
6142
- atsMeasurement?.end({
6143
- success: true,
6144
- });
6145
5901
  const refreshTokenRequest = {
6146
5902
  ...request,
6147
5903
  refreshToken: refreshToken.secret,
@@ -6151,8 +5907,7 @@ class RefreshTokenClient extends BaseClient {
6151
5907
  type: CcsCredentialType.HOME_ACCOUNT_ID,
6152
5908
  },
6153
5909
  };
6154
- this.performanceClient?.setPreQueueTime(PerformanceEvents.RefreshTokenClientAcquireToken, request.correlationId);
6155
- return this.acquireToken(refreshTokenRequest);
5910
+ return invokeAsync(this.acquireToken.bind(this), PerformanceEvents.RefreshTokenClientAcquireToken, this.logger, this.performanceClient, request.correlationId)(refreshTokenRequest);
6156
5911
  }
6157
5912
  /**
6158
5913
  * Constructs the network message and makes a NW call to the underlying secure token service
@@ -6161,14 +5916,13 @@ class RefreshTokenClient extends BaseClient {
6161
5916
  */
6162
5917
  async executeTokenRequest(request, authority) {
6163
5918
  this.performanceClient?.addQueueMeasurement(PerformanceEvents.RefreshTokenClientExecuteTokenRequest, request.correlationId);
6164
- const acquireTokenMeasurement = this.performanceClient?.startMeasurement(PerformanceEvents.RefreshTokenClientExecuteTokenRequest, request.correlationId);
6165
- this.performanceClient?.setPreQueueTime(PerformanceEvents.RefreshTokenClientCreateTokenRequestBody, request.correlationId);
6166
5919
  const queryParametersString = this.createTokenQueryParameters(request);
6167
5920
  const endpoint = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString);
6168
- const requestBody = await this.createTokenRequestBody(request);
5921
+ const requestBody = await invokeAsync(this.createTokenRequestBody.bind(this), PerformanceEvents.RefreshTokenClientCreateTokenRequestBody, this.logger, this.performanceClient, request.correlationId)(request);
6169
5922
  const headers = this.createTokenRequestHeaders(request.ccsCredential);
6170
5923
  const thumbprint = {
6171
- clientId: this.config.authOptions.clientId,
5924
+ clientId: request.tokenBodyParameters?.clientId ||
5925
+ this.config.authOptions.clientId,
6172
5926
  authority: authority.canonicalAuthority,
6173
5927
  scopes: request.scopes,
6174
5928
  claims: request.claims,
@@ -6178,19 +5932,7 @@ class RefreshTokenClient extends BaseClient {
6178
5932
  shrClaims: request.shrClaims,
6179
5933
  sshKid: request.sshKid,
6180
5934
  };
6181
- return this.executePostToTokenEndpoint(endpoint, requestBody, headers, thumbprint, request.correlationId)
6182
- .then((result) => {
6183
- acquireTokenMeasurement?.end({
6184
- success: true,
6185
- });
6186
- return result;
6187
- })
6188
- .catch((error) => {
6189
- acquireTokenMeasurement?.end({
6190
- success: false,
6191
- });
6192
- throw error;
6193
- });
5935
+ return invokeAsync(this.executePostToTokenEndpoint.bind(this), PerformanceEvents.BaseClientExecutePostToTokenEndpoint, this.logger, this.performanceClient, request.correlationId)(endpoint, requestBody, headers, thumbprint, request.correlationId);
6194
5936
  }
6195
5937
  /**
6196
5938
  * Helper function to create the token request body
@@ -6199,9 +5941,12 @@ class RefreshTokenClient extends BaseClient {
6199
5941
  async createTokenRequestBody(request) {
6200
5942
  this.performanceClient?.addQueueMeasurement(PerformanceEvents.RefreshTokenClientCreateTokenRequestBody, request.correlationId);
6201
5943
  const correlationId = request.correlationId;
6202
- const acquireTokenMeasurement = this.performanceClient?.startMeasurement(PerformanceEvents.BaseClientCreateTokenRequestHeaders, correlationId);
6203
5944
  const parameterBuilder = new RequestParameterBuilder();
6204
- parameterBuilder.addClientId(this.config.authOptions.clientId);
5945
+ parameterBuilder.addClientId(request.tokenBodyParameters?.[AADServerParamKeys.CLIENT_ID] ||
5946
+ this.config.authOptions.clientId);
5947
+ if (request.redirectUri) {
5948
+ parameterBuilder.addRedirectUri(request.redirectUri);
5949
+ }
6205
5950
  parameterBuilder.addScopes(request.scopes, true, this.config.authOptions.authority.options.OIDCOptions?.defaultScopes);
6206
5951
  parameterBuilder.addGrantType(GrantType.REFRESH_TOKEN_GRANT);
6207
5952
  parameterBuilder.addClientInfo();
@@ -6223,8 +5968,7 @@ class RefreshTokenClient extends BaseClient {
6223
5968
  }
6224
5969
  if (request.authenticationScheme === AuthenticationScheme.POP) {
6225
5970
  const popTokenGenerator = new PopTokenGenerator(this.cryptoUtils, this.performanceClient);
6226
- this.performanceClient?.setPreQueueTime(PerformanceEvents.PopTokenGenerateCnf, request.correlationId);
6227
- const reqCnfData = await popTokenGenerator.generateCnf(request);
5971
+ const reqCnfData = await invokeAsync(popTokenGenerator.generateCnf.bind(popTokenGenerator), PerformanceEvents.PopTokenGenerateCnf, this.logger, this.performanceClient, request.correlationId)(request, this.logger);
6228
5972
  // SPA PoP requires full Base64Url encoded req_cnf string (unhashed)
6229
5973
  parameterBuilder.addPopToken(reqCnfData.reqCnfString);
6230
5974
  }
@@ -6233,10 +5977,7 @@ class RefreshTokenClient extends BaseClient {
6233
5977
  parameterBuilder.addSshJwk(request.sshJwk);
6234
5978
  }
6235
5979
  else {
6236
- acquireTokenMeasurement?.end({
6237
- success: false,
6238
- });
6239
- throw ClientConfigurationError.createMissingSshJwkError();
5980
+ throw createClientConfigurationError(missingSshJwk);
6240
5981
  }
6241
5982
  }
6242
5983
  if (!StringUtils.isEmptyObj(request.claims) ||
@@ -6262,9 +6003,9 @@ class RefreshTokenClient extends BaseClient {
6262
6003
  break;
6263
6004
  }
6264
6005
  }
6265
- acquireTokenMeasurement?.end({
6266
- success: true,
6267
- });
6006
+ if (request.tokenBodyParameters) {
6007
+ parameterBuilder.addExtraQueryParameters(request.tokenBodyParameters);
6008
+ }
6268
6009
  return parameterBuilder.createQueryString();
6269
6010
  }
6270
6011
  }
@@ -6285,11 +6026,24 @@ class SilentFlowClient extends BaseClient {
6285
6026
  */
6286
6027
  async acquireToken(request) {
6287
6028
  try {
6288
- return await this.acquireCachedToken(request);
6029
+ const [authResponse, cacheOutcome] = await this.acquireCachedToken(request);
6030
+ // if the token is not expired but must be refreshed; get a new one in the background
6031
+ if (cacheOutcome === CacheOutcome.PROACTIVELY_REFRESHED) {
6032
+ this.logger.info("SilentFlowClient:acquireCachedToken - Cached access token's refreshOn property has been exceeded'. It's not expired, but must be refreshed.");
6033
+ // refresh the access token in the background
6034
+ const refreshTokenClient = new RefreshTokenClient(this.config, this.performanceClient);
6035
+ refreshTokenClient
6036
+ .acquireTokenByRefreshToken(request)
6037
+ .catch(() => {
6038
+ // do nothing, this is running in the background and no action is to be taken upon success or failure
6039
+ });
6040
+ }
6041
+ // return the cached token
6042
+ return authResponse;
6289
6043
  }
6290
6044
  catch (e) {
6291
6045
  if (e instanceof ClientAuthError &&
6292
- e.errorCode === ClientAuthErrorMessage.tokenRefreshRequired.code) {
6046
+ e.errorCode === tokenRefreshRequired) {
6293
6047
  const refreshTokenClient = new RefreshTokenClient(this.config, this.performanceClient);
6294
6048
  return refreshTokenClient.acquireTokenByRefreshToken(request);
6295
6049
  }
@@ -6303,52 +6057,61 @@ class SilentFlowClient extends BaseClient {
6303
6057
  * @param request
6304
6058
  */
6305
6059
  async acquireCachedToken(request) {
6060
+ let lastCacheOutcome = CacheOutcome.NOT_APPLICABLE;
6306
6061
  // Cannot renew token if no request object is given.
6307
6062
  if (!request) {
6308
- throw ClientConfigurationError.createEmptyTokenRequestError();
6063
+ throw createClientConfigurationError(tokenRequestEmpty);
6309
6064
  }
6310
6065
  if (request.forceRefresh) {
6311
6066
  // Must refresh due to present force_refresh flag.
6312
- this.serverTelemetryManager?.setCacheOutcome(CacheOutcome.FORCE_REFRESH);
6067
+ lastCacheOutcome = CacheOutcome.FORCE_REFRESH_OR_CLAIMS;
6068
+ this.serverTelemetryManager?.setCacheOutcome(CacheOutcome.FORCE_REFRESH_OR_CLAIMS);
6313
6069
  this.logger.info("SilentFlowClient:acquireCachedToken - Skipping cache because forceRefresh is true.");
6314
- throw ClientAuthError.createRefreshRequiredError();
6070
+ throw createClientAuthError(tokenRefreshRequired);
6315
6071
  }
6316
6072
  else if (!this.config.cacheOptions.claimsBasedCachingEnabled &&
6317
6073
  !StringUtils.isEmptyObj(request.claims)) {
6074
+ lastCacheOutcome = CacheOutcome.FORCE_REFRESH_OR_CLAIMS;
6318
6075
  // Must refresh due to request parameters.
6319
6076
  this.logger.info("SilentFlowClient:acquireCachedToken - Skipping cache because claims-based caching is disabled and claims were requested.");
6320
- throw ClientAuthError.createRefreshRequiredError();
6077
+ throw createClientAuthError(tokenRefreshRequired);
6321
6078
  }
6322
6079
  // We currently do not support silent flow for account === null use cases; This will be revisited for confidential flow usecases
6323
6080
  if (!request.account) {
6324
- throw ClientAuthError.createNoAccountInSilentRequestError();
6081
+ throw createClientAuthError(noAccountInSilentRequest);
6325
6082
  }
6326
6083
  const environment = request.authority || this.authority.getPreferredCache();
6327
6084
  const cacheRecord = this.cacheManager.readCacheRecord(request.account, request, environment);
6328
6085
  if (!cacheRecord.accessToken) {
6329
- // Must refresh due to non-existent access_token.
6086
+ // must refresh due to non-existent access_token
6087
+ lastCacheOutcome = CacheOutcome.NO_CACHED_ACCESS_TOKEN;
6330
6088
  this.serverTelemetryManager?.setCacheOutcome(CacheOutcome.NO_CACHED_ACCESS_TOKEN);
6331
6089
  this.logger.info("SilentFlowClient:acquireCachedToken - No access token found in cache for the given properties.");
6332
- throw ClientAuthError.createRefreshRequiredError();
6090
+ throw createClientAuthError(tokenRefreshRequired);
6333
6091
  }
6334
6092
  else if (TimeUtils.wasClockTurnedBack(cacheRecord.accessToken.cachedAt) ||
6335
6093
  TimeUtils.isTokenExpired(cacheRecord.accessToken.expiresOn, this.config.systemOptions.tokenRenewalOffsetSeconds)) {
6336
- // Must refresh due to expired access_token.
6094
+ // must refresh due to the expires_in value
6095
+ lastCacheOutcome = CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED;
6337
6096
  this.serverTelemetryManager?.setCacheOutcome(CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED);
6338
6097
  this.logger.info(`SilentFlowClient:acquireCachedToken - Cached access token is expired or will expire within ${this.config.systemOptions.tokenRenewalOffsetSeconds} seconds.`);
6339
- throw ClientAuthError.createRefreshRequiredError();
6098
+ throw createClientAuthError(tokenRefreshRequired);
6340
6099
  }
6341
6100
  else if (cacheRecord.accessToken.refreshOn &&
6342
6101
  TimeUtils.isTokenExpired(cacheRecord.accessToken.refreshOn, 0)) {
6343
- // Must refresh due to the refresh_in value.
6344
- this.serverTelemetryManager?.setCacheOutcome(CacheOutcome.REFRESH_CACHED_ACCESS_TOKEN);
6102
+ // must refresh (in the background) due to the refresh_in value
6103
+ lastCacheOutcome = CacheOutcome.PROACTIVELY_REFRESHED;
6104
+ this.serverTelemetryManager?.setCacheOutcome(CacheOutcome.PROACTIVELY_REFRESHED);
6345
6105
  this.logger.info("SilentFlowClient:acquireCachedToken - Cached access token's refreshOn property has been exceeded'.");
6346
- throw ClientAuthError.createRefreshRequiredError();
6106
+ // don't throw ClientAuthError.createRefreshRequiredError(), return cached token instead
6347
6107
  }
6348
6108
  if (this.config.serverTelemetryManager) {
6349
6109
  this.config.serverTelemetryManager.incrementCacheHits();
6350
6110
  }
6351
- return await this.generateResultFromCacheRecord(cacheRecord, request);
6111
+ return [
6112
+ await this.generateResultFromCacheRecord(cacheRecord, request),
6113
+ lastCacheOutcome,
6114
+ ];
6352
6115
  }
6353
6116
  /**
6354
6117
  * Helper function to build response object from the CacheRecord
@@ -6363,7 +6126,7 @@ class SilentFlowClient extends BaseClient {
6363
6126
  if (request.maxAge || request.maxAge === 0) {
6364
6127
  const authTime = idTokenClaims?.auth_time;
6365
6128
  if (!authTime) {
6366
- throw ClientAuthError.createAuthTimeNotFoundError();
6129
+ throw createClientAuthError(authTimeNotFound);
6367
6130
  }
6368
6131
  checkMaxAge(authTime, request.maxAge);
6369
6132
  }
@@ -7369,8 +7132,9 @@ function isCloudInstanceDiscoveryErrorResponse(response) {
7369
7132
  * Licensed under the MIT License.
7370
7133
  */
7371
7134
  class RegionDiscovery {
7372
- constructor(networkInterface, performanceClient, correlationId) {
7135
+ constructor(networkInterface, logger, performanceClient, correlationId) {
7373
7136
  this.networkInterface = networkInterface;
7137
+ this.logger = logger;
7374
7138
  this.performanceClient = performanceClient;
7375
7139
  this.correlationId = correlationId;
7376
7140
  }
@@ -7387,8 +7151,7 @@ class RegionDiscovery {
7387
7151
  if (!autodetectedRegionName) {
7388
7152
  const options = RegionDiscovery.IMDS_OPTIONS;
7389
7153
  try {
7390
- this.performanceClient?.setPreQueueTime(PerformanceEvents.RegionDiscoveryGetRegionFromIMDS, this.correlationId);
7391
- const localIMDSVersionResponse = await this.getRegionFromIMDS(Constants.IMDS_VERSION, options);
7154
+ const localIMDSVersionResponse = await invokeAsync(this.getRegionFromIMDS.bind(this), PerformanceEvents.RegionDiscoveryGetRegionFromIMDS, this.logger, this.performanceClient, this.correlationId)(Constants.IMDS_VERSION, options);
7392
7155
  if (localIMDSVersionResponse.status ===
7393
7156
  ResponseCodes.httpSuccess) {
7394
7157
  autodetectedRegionName = localIMDSVersionResponse.body;
@@ -7398,15 +7161,13 @@ class RegionDiscovery {
7398
7161
  // If the response using the local IMDS version failed, try to fetch the current version of IMDS and retry.
7399
7162
  if (localIMDSVersionResponse.status ===
7400
7163
  ResponseCodes.httpBadRequest) {
7401
- this.performanceClient?.setPreQueueTime(PerformanceEvents.RegionDiscoveryGetCurrentVersion, this.correlationId);
7402
- const currentIMDSVersion = await this.getCurrentVersion(options);
7164
+ const currentIMDSVersion = await invokeAsync(this.getCurrentVersion.bind(this), PerformanceEvents.RegionDiscoveryGetCurrentVersion, this.logger, this.performanceClient, this.correlationId)(options);
7403
7165
  if (!currentIMDSVersion) {
7404
7166
  regionDiscoveryMetadata.region_source =
7405
7167
  RegionDiscoverySources.FAILED_AUTO_DETECTION;
7406
7168
  return null;
7407
7169
  }
7408
- this.performanceClient?.setPreQueueTime(PerformanceEvents.RegionDiscoveryGetRegionFromIMDS, this.correlationId);
7409
- const currentIMDSVersionResponse = await this.getRegionFromIMDS(currentIMDSVersion, options);
7170
+ const currentIMDSVersionResponse = await invokeAsync(this.getRegionFromIMDS.bind(this), PerformanceEvents.RegionDiscoveryGetRegionFromIMDS, this.logger, this.performanceClient, this.correlationId)(currentIMDSVersion, options);
7410
7171
  if (currentIMDSVersionResponse.status ===
7411
7172
  ResponseCodes.httpSuccess) {
7412
7173
  autodetectedRegionName =
@@ -7497,7 +7258,7 @@ class Authority {
7497
7258
  this.logger = logger;
7498
7259
  this.performanceClient = performanceClient;
7499
7260
  this.correlationId = correlationId;
7500
- this.regionDiscovery = new RegionDiscovery(networkInterface, this.performanceClient, this.correlationId);
7261
+ this.regionDiscovery = new RegionDiscovery(networkInterface, this.logger, this.performanceClient, this.correlationId);
7501
7262
  }
7502
7263
  /**
7503
7264
  * Get {@link AuthorityType}
@@ -7580,7 +7341,7 @@ class Authority {
7580
7341
  return this.replacePath(this.metadata.authorization_endpoint);
7581
7342
  }
7582
7343
  else {
7583
- throw ClientAuthError.createEndpointDiscoveryIncompleteError("Discovery incomplete.");
7344
+ throw createClientAuthError(endpointResolutionError);
7584
7345
  }
7585
7346
  }
7586
7347
  /**
@@ -7591,7 +7352,7 @@ class Authority {
7591
7352
  return this.replacePath(this.metadata.token_endpoint);
7592
7353
  }
7593
7354
  else {
7594
- throw ClientAuthError.createEndpointDiscoveryIncompleteError("Discovery incomplete.");
7355
+ throw createClientAuthError(endpointResolutionError);
7595
7356
  }
7596
7357
  }
7597
7358
  get deviceCodeEndpoint() {
@@ -7599,7 +7360,7 @@ class Authority {
7599
7360
  return this.replacePath(this.metadata.token_endpoint.replace("/token", "/devicecode"));
7600
7361
  }
7601
7362
  else {
7602
- throw ClientAuthError.createEndpointDiscoveryIncompleteError("Discovery incomplete.");
7363
+ throw createClientAuthError(endpointResolutionError);
7603
7364
  }
7604
7365
  }
7605
7366
  /**
@@ -7609,12 +7370,12 @@ class Authority {
7609
7370
  if (this.discoveryComplete()) {
7610
7371
  // ROPC policies may not have end_session_endpoint set
7611
7372
  if (!this.metadata.end_session_endpoint) {
7612
- throw ClientAuthError.createLogoutNotSupportedError();
7373
+ throw createClientAuthError(endSessionEndpointNotSupported);
7613
7374
  }
7614
7375
  return this.replacePath(this.metadata.end_session_endpoint);
7615
7376
  }
7616
7377
  else {
7617
- throw ClientAuthError.createEndpointDiscoveryIncompleteError("Discovery incomplete.");
7378
+ throw createClientAuthError(endpointResolutionError);
7618
7379
  }
7619
7380
  }
7620
7381
  /**
@@ -7625,7 +7386,7 @@ class Authority {
7625
7386
  return this.replacePath(this.metadata.issuer);
7626
7387
  }
7627
7388
  else {
7628
- throw ClientAuthError.createEndpointDiscoveryIncompleteError("Discovery incomplete.");
7389
+ throw createClientAuthError(endpointResolutionError);
7629
7390
  }
7630
7391
  }
7631
7392
  /**
@@ -7636,7 +7397,7 @@ class Authority {
7636
7397
  return this.replacePath(this.metadata.jwks_uri);
7637
7398
  }
7638
7399
  else {
7639
- throw ClientAuthError.createEndpointDiscoveryIncompleteError("Discovery incomplete.");
7400
+ throw createClientAuthError(endpointResolutionError);
7640
7401
  }
7641
7402
  }
7642
7403
  /**
@@ -7693,7 +7454,8 @@ class Authority {
7693
7454
  */
7694
7455
  get defaultOpenIdConfigurationEndpoint() {
7695
7456
  const canonicalAuthorityHost = this.hostnameAndPort;
7696
- if (this.authorityType === AuthorityType.Adfs ||
7457
+ if (this.canonicalAuthority.endsWith("v2.0/") ||
7458
+ this.authorityType === AuthorityType.Adfs ||
7697
7459
  (this.protocolMode !== ProtocolMode.AAD &&
7698
7460
  !this.isAliasOfKnownMicrosoftAuthority(canonicalAuthorityHost))) {
7699
7461
  return `${this.canonicalAuthority}.well-known/openid-configuration`;
@@ -7717,11 +7479,9 @@ class Authority {
7717
7479
  metadataEntity = new AuthorityMetadataEntity();
7718
7480
  metadataEntity.updateCanonicalAuthority(this.canonicalAuthority);
7719
7481
  }
7720
- this.performanceClient?.setPreQueueTime(PerformanceEvents.AuthorityUpdateCloudDiscoveryMetadata, this.correlationId);
7721
- const cloudDiscoverySource = await this.updateCloudDiscoveryMetadata(metadataEntity);
7482
+ const cloudDiscoverySource = await invokeAsync(this.updateCloudDiscoveryMetadata.bind(this), PerformanceEvents.AuthorityUpdateCloudDiscoveryMetadata, this.logger, this.performanceClient, this.correlationId)(metadataEntity);
7722
7483
  this.canonicalAuthority = this.canonicalAuthority.replace(this.hostnameAndPort, metadataEntity.preferred_network);
7723
- this.performanceClient?.setPreQueueTime(PerformanceEvents.AuthorityUpdateEndpointMetadata, this.correlationId);
7724
- const endpointSource = await this.updateEndpointMetadata(metadataEntity);
7484
+ const endpointSource = await invokeAsync(this.updateEndpointMetadata.bind(this), PerformanceEvents.AuthorityUpdateEndpointMetadata, this.logger, this.performanceClient, this.correlationId)(metadataEntity);
7725
7485
  if (cloudDiscoverySource !== AuthorityMetadataSource.CACHE &&
7726
7486
  endpointSource !== AuthorityMetadataSource.CACHE) {
7727
7487
  // Reset the expiration time unless both values came from a successful cache lookup
@@ -7756,10 +7516,7 @@ class Authority {
7756
7516
  this.logger.verbose("Found endpoint metadata from hardcoded values.");
7757
7517
  // If the user prefers to use an azure region replace the global endpoints with regional information.
7758
7518
  if (this.authorityOptions.azureRegionConfiguration?.azureRegion) {
7759
- this.performanceClient?.setPreQueueTime(PerformanceEvents.AuthorityUpdateMetadataWithRegionalInformation, this.correlationId);
7760
- this.logger.verbose("Found azure region configuration. Updating endpoints with regional information.");
7761
- hardcodedMetadata =
7762
- await this.updateMetadataWithRegionalInformation(hardcodedMetadata);
7519
+ hardcodedMetadata = await invokeAsync(this.updateMetadataWithRegionalInformation.bind(this), PerformanceEvents.AuthorityUpdateMetadataWithRegionalInformation, this.logger, this.performanceClient, this.correlationId)(hardcodedMetadata);
7763
7520
  }
7764
7521
  metadataEntity.updateEndpointMetadata(hardcodedMetadata, false);
7765
7522
  return AuthorityMetadataSource.HARDCODED_VALUES;
@@ -7780,24 +7537,18 @@ class Authority {
7780
7537
  else if (metadataEntityExpired) {
7781
7538
  this.logger.verbose("The metadata entity is expired.");
7782
7539
  }
7783
- this.logger.verbose("Did not find cached endpoint metadata... Attempting to get endpoint metadata from the network.");
7784
- this.performanceClient?.setPreQueueTime(PerformanceEvents.AuthorityGetEndpointMetadataFromNetwork, this.correlationId);
7785
- metadata = await this.getEndpointMetadataFromNetwork();
7540
+ metadata = await invokeAsync(this.getEndpointMetadataFromNetwork.bind(this), PerformanceEvents.AuthorityGetEndpointMetadataFromNetwork, this.logger, this.performanceClient, this.correlationId)();
7786
7541
  if (metadata) {
7787
- this.logger.verbose("Endpoint metadata was successfully returned from getEndpointMetadataFromNetwork()");
7788
7542
  // If the user prefers to use an azure region replace the global endpoints with regional information.
7789
7543
  if (this.authorityOptions.azureRegionConfiguration?.azureRegion) {
7790
- this.performanceClient?.setPreQueueTime(PerformanceEvents.AuthorityUpdateMetadataWithRegionalInformation, this.correlationId);
7791
- this.logger.verbose("Found azure region configuration. Updating endpoints with regional information.");
7792
- metadata = await this.updateMetadataWithRegionalInformation(metadata);
7544
+ metadata = await invokeAsync(this.updateMetadataWithRegionalInformation.bind(this), PerformanceEvents.AuthorityUpdateMetadataWithRegionalInformation, this.logger, this.performanceClient, this.correlationId)(metadata);
7793
7545
  }
7794
7546
  metadataEntity.updateEndpointMetadata(metadata, true);
7795
7547
  return AuthorityMetadataSource.NETWORK;
7796
7548
  }
7797
7549
  else {
7798
7550
  // Metadata could not be obtained from the config, cache, network or hardcoded values
7799
- 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.");
7800
- throw ClientAuthError.createUnableToGetOpenidConfigError(this.defaultOpenIdConfigurationEndpoint);
7551
+ throw createClientAuthError(openIdConfigError, this.defaultOpenIdConfigurationEndpoint);
7801
7552
  }
7802
7553
  }
7803
7554
  /**
@@ -7821,7 +7572,7 @@ class Authority {
7821
7572
  return JSON.parse(this.authorityOptions.authorityMetadata);
7822
7573
  }
7823
7574
  catch (e) {
7824
- throw ClientConfigurationError.createInvalidAuthorityMetadataError();
7575
+ throw createClientConfigurationError(invalidAuthorityMetadata);
7825
7576
  }
7826
7577
  }
7827
7578
  return null;
@@ -7833,7 +7584,6 @@ class Authority {
7833
7584
  */
7834
7585
  async getEndpointMetadataFromNetwork() {
7835
7586
  this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityGetEndpointMetadataFromNetwork, this.correlationId);
7836
- const perfEvent = this.performanceClient?.startMeasurement(PerformanceEvents.AuthorityGetEndpointMetadataFromNetwork, this.correlationId);
7837
7587
  const options = {};
7838
7588
  /*
7839
7589
  * TODO: Add a timeout if the authority exists in our library's
@@ -7845,23 +7595,14 @@ class Authority {
7845
7595
  const response = await this.networkInterface.sendGetRequestAsync(openIdConfigurationEndpoint, options);
7846
7596
  const isValidResponse = isOpenIdConfigResponse(response.body);
7847
7597
  if (isValidResponse) {
7848
- perfEvent?.end({ success: true });
7849
7598
  return response.body;
7850
7599
  }
7851
7600
  else {
7852
- perfEvent?.end({
7853
- success: false,
7854
- errorCode: "invalid_response",
7855
- });
7856
7601
  this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: could not parse response as OpenID configuration`);
7857
7602
  return null;
7858
7603
  }
7859
7604
  }
7860
7605
  catch (e) {
7861
- perfEvent?.end({
7862
- success: false,
7863
- errorCode: "request_failure",
7864
- });
7865
7606
  this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: ${e}`);
7866
7607
  return null;
7867
7608
  }
@@ -7891,8 +7632,7 @@ class Authority {
7891
7632
  userConfiguredAzureRegion;
7892
7633
  return Authority.replaceWithRegionalInformation(metadata, userConfiguredAzureRegion);
7893
7634
  }
7894
- this.performanceClient?.setPreQueueTime(PerformanceEvents.RegionDiscoveryDetectRegion, this.correlationId);
7895
- const autodetectedRegionName = await this.regionDiscovery.detectRegion(this.authorityOptions.azureRegionConfiguration
7635
+ const autodetectedRegionName = await invokeAsync(this.regionDiscovery.detectRegion.bind(this.regionDiscovery), PerformanceEvents.RegionDiscoveryDetectRegion, this.logger, this.performanceClient, this.correlationId)(this.authorityOptions.azureRegionConfiguration
7896
7636
  ?.environmentRegion, this.regionDiscoveryMetadata);
7897
7637
  if (autodetectedRegionName) {
7898
7638
  this.regionDiscoveryMetadata.region_outcome =
@@ -7951,17 +7691,13 @@ class Authority {
7951
7691
  else if (metadataEntityExpired) {
7952
7692
  this.logger.verbose("The metadata entity is expired.");
7953
7693
  }
7954
- this.logger.verbose("Did not find cloud discovery metadata in the cache... Attempting to get cloud discovery metadata from the network.");
7955
- this.performanceClient?.setPreQueueTime(PerformanceEvents.AuthorityGetCloudDiscoveryMetadataFromNetwork, this.correlationId);
7956
- metadata = await this.getCloudDiscoveryMetadataFromNetwork();
7694
+ metadata = await invokeAsync(this.getCloudDiscoveryMetadataFromNetwork.bind(this), PerformanceEvents.AuthorityGetCloudDiscoveryMetadataFromNetwork, this.logger, this.performanceClient, this.correlationId)();
7957
7695
  if (metadata) {
7958
- this.logger.verbose("cloud discovery metadata was successfully returned from getCloudDiscoveryMetadataFromNetwork()");
7959
7696
  metadataEntity.updateCloudDiscoveryMetadata(metadata, true);
7960
7697
  return AuthorityMetadataSource.NETWORK;
7961
7698
  }
7962
7699
  // Metadata could not be obtained from the config, cache, network or hardcoded values
7963
- 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.");
7964
- throw ClientConfigurationError.createUntrustedAuthorityError();
7700
+ throw createClientConfigurationError(untrustedAuthority);
7965
7701
  }
7966
7702
  /**
7967
7703
  * Parse cloudDiscoveryMetadata config or check knownAuthorities
@@ -7990,7 +7726,7 @@ class Authority {
7990
7726
  }
7991
7727
  catch (e) {
7992
7728
  this.logger.verbose("Unable to parse the cloud discovery metadata. Throwing Invalid Cloud Discovery Metadata Error.");
7993
- throw ClientConfigurationError.createInvalidCloudDiscoveryMetadataError();
7729
+ throw createClientConfigurationError(invalidCloudDiscoveryMetadata);
7994
7730
  }
7995
7731
  }
7996
7732
  // If cloudDiscoveryMetadata is empty or does not contain the host, check knownAuthorities
@@ -8134,7 +7870,7 @@ class Authority {
8134
7870
  return this.metadata.preferred_cache;
8135
7871
  }
8136
7872
  else {
8137
- throw ClientAuthError.createEndpointDiscoveryIncompleteError("Discovery incomplete.");
7873
+ throw createClientAuthError(endpointResolutionError);
8138
7874
  }
8139
7875
  }
8140
7876
  /**
@@ -8259,12 +7995,11 @@ class AuthorityFactory {
8259
7995
  // Initialize authority and perform discovery endpoint check.
8260
7996
  const acquireTokenAuthority = AuthorityFactory.createInstance(authorityUriFinal, networkClient, cacheManager, authorityOptions, logger, performanceClient, correlationId);
8261
7997
  try {
8262
- performanceClient?.setPreQueueTime(PerformanceEvents.AuthorityResolveEndpointsAsync, correlationId);
8263
- await acquireTokenAuthority.resolveEndpointsAsync();
7998
+ await invokeAsync(acquireTokenAuthority.resolveEndpointsAsync.bind(acquireTokenAuthority), PerformanceEvents.AuthorityResolveEndpointsAsync, logger, performanceClient, correlationId)();
8264
7999
  return acquireTokenAuthority;
8265
8000
  }
8266
8001
  catch (e) {
8267
- throw ClientAuthError.createEndpointDiscoveryIncompleteError(e);
8002
+ throw createClientAuthError(endpointResolutionError);
8268
8003
  }
8269
8004
  }
8270
8005
  /**
@@ -8280,7 +8015,7 @@ class AuthorityFactory {
8280
8015
  static createInstance(authorityUrl, networkInterface, cacheManager, authorityOptions, logger, performanceClient, correlationId) {
8281
8016
  // Throw error if authority url is empty
8282
8017
  if (!authorityUrl) {
8283
- throw ClientConfigurationError.createUrlEmptyError();
8018
+ throw createClientConfigurationError(urlEmptyError);
8284
8019
  }
8285
8020
  return new Authority(authorityUrl, networkInterface, cacheManager, authorityOptions, logger, performanceClient, correlationId);
8286
8021
  }
@@ -8344,12 +8079,10 @@ class ThrottlingEntity {
8344
8079
  */
8345
8080
  const StubbedNetworkModule = {
8346
8081
  sendGetRequestAsync: () => {
8347
- const notImplErr = "Network interface - sendGetRequestAsync() has not been implemented for the Network interface.";
8348
- return Promise.reject(AuthError.createUnexpectedError(notImplErr));
8082
+ return Promise.reject(createClientAuthError(methodNotImplemented));
8349
8083
  },
8350
8084
  sendPostRequestAsync: () => {
8351
- const notImplErr = "Network interface - sendPostRequestAsync() has not been implemented for the Network interface.";
8352
- return Promise.reject(AuthError.createUnexpectedError(notImplErr));
8085
+ return Promise.reject(createClientAuthError(methodNotImplemented));
8353
8086
  },
8354
8087
  };
8355
8088
 
@@ -8357,18 +8090,16 @@ const StubbedNetworkModule = {
8357
8090
  * Copyright (c) Microsoft Corporation. All rights reserved.
8358
8091
  * Licensed under the MIT License.
8359
8092
  */
8360
- /**
8361
- * ClientAuthErrorMessage class containing string constants used by error codes and messages.
8093
+ const missingKidError = "missing_kid_error";
8094
+ const missingAlgError = "missing_alg_error";
8095
+
8096
+ /*
8097
+ * Copyright (c) Microsoft Corporation. All rights reserved.
8098
+ * Licensed under the MIT License.
8362
8099
  */
8363
- const JoseHeaderErrorMessage = {
8364
- missingKidError: {
8365
- code: "missing_kid_error",
8366
- 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.",
8367
- },
8368
- missingAlgError: {
8369
- code: "missing_alg_error",
8370
- 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.",
8371
- },
8100
+ const JoseHeaderErrorMessages = {
8101
+ [missingKidError]: "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.",
8102
+ [missingAlgError]: "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.",
8372
8103
  };
8373
8104
  /**
8374
8105
  * Error thrown when there is an error in the client code running on the browser.
@@ -8379,18 +8110,10 @@ class JoseHeaderError extends AuthError {
8379
8110
  this.name = "JoseHeaderError";
8380
8111
  Object.setPrototypeOf(this, JoseHeaderError.prototype);
8381
8112
  }
8382
- /**
8383
- * Creates an error thrown when keyId isn't set on JOSE header.
8384
- */
8385
- static createMissingKidError() {
8386
- return new JoseHeaderError(JoseHeaderErrorMessage.missingKidError.code, JoseHeaderErrorMessage.missingKidError.desc);
8387
- }
8388
- /**
8389
- * Creates an error thrown when algorithm isn't set on JOSE header.
8390
- */
8391
- static createMissingAlgError() {
8392
- return new JoseHeaderError(JoseHeaderErrorMessage.missingAlgError.code, JoseHeaderErrorMessage.missingAlgError.desc);
8393
- }
8113
+ }
8114
+ /** Returns JoseHeaderError object */
8115
+ function createJoseHeaderError(code) {
8116
+ return new JoseHeaderError(code, JoseHeaderErrorMessages[code]);
8394
8117
  }
8395
8118
 
8396
8119
  /*
@@ -8415,11 +8138,11 @@ class JoseHeader {
8415
8138
  static getShrHeaderString(shrHeaderOptions) {
8416
8139
  // KeyID is required on the SHR header
8417
8140
  if (!shrHeaderOptions.kid) {
8418
- throw JoseHeaderError.createMissingKidError();
8141
+ throw createJoseHeaderError(missingKidError);
8419
8142
  }
8420
8143
  // Alg is required on the SHR header
8421
8144
  if (!shrHeaderOptions.alg) {
8422
- throw JoseHeaderError.createMissingAlgError();
8145
+ throw createJoseHeaderError(missingAlgError);
8423
8146
  }
8424
8147
  const shrHeader = new JoseHeader({
8425
8148
  // Access Token PoP headers must have type pop, but the type header can be overriden for special cases
@@ -8455,7 +8178,7 @@ class AuthenticationHeaderParser {
8455
8178
  if (authenticationInfoChallenges.nextnonce) {
8456
8179
  return authenticationInfoChallenges.nextnonce;
8457
8180
  }
8458
- throw ClientConfigurationError.createInvalidAuthenticationHeaderError(HeaderNames.AuthenticationInfo, "nextnonce challenge is missing.");
8181
+ throw createClientConfigurationError(invalidAuthenticationHeader);
8459
8182
  }
8460
8183
  // Attempt to parse nonce from WWW-Authenticate
8461
8184
  const wwwAuthenticate = this.headers[HeaderNames.WWWAuthenticate];
@@ -8464,10 +8187,10 @@ class AuthenticationHeaderParser {
8464
8187
  if (wwwAuthenticateChallenges.nonce) {
8465
8188
  return wwwAuthenticateChallenges.nonce;
8466
8189
  }
8467
- throw ClientConfigurationError.createInvalidAuthenticationHeaderError(HeaderNames.WWWAuthenticate, "nonce challenge is missing.");
8190
+ throw createClientConfigurationError(invalidAuthenticationHeader);
8468
8191
  }
8469
8192
  // If neither header is present, throw missing headers error
8470
- throw ClientConfigurationError.createMissingNonceAuthenticationHeadersError();
8193
+ throw createClientConfigurationError(missingNonceAuthenticationHeader);
8471
8194
  }
8472
8195
  /**
8473
8196
  * Parses an HTTP header's challenge set into a key/value map.
@@ -8494,7 +8217,7 @@ class AuthenticationHeaderParser {
8494
8217
  /** @internal */
8495
8218
  class ServerTelemetryManager {
8496
8219
  constructor(telemetryRequest, cacheManager) {
8497
- this.cacheOutcome = CacheOutcome.NO_CACHE_HIT;
8220
+ this.cacheOutcome = CacheOutcome.NOT_APPLICABLE;
8498
8221
  this.cacheManager = cacheManager;
8499
8222
  this.apiId = telemetryRequest.apiId;
8500
8223
  this.correlationId = telemetryRequest.correlationId;
@@ -8798,7 +8521,8 @@ class PerformanceClient {
8798
8521
  }
8799
8522
  const queueMeasurement = {
8800
8523
  eventName,
8801
- queueTime,
8524
+ // Always default queue time to 0 for manually completed (improperly instrumented)
8525
+ queueTime: manuallyCompleted ? 0 : queueTime,
8802
8526
  manuallyCompleted,
8803
8527
  };
8804
8528
  // Adds to existing correlation Id if present in queueMeasurements
@@ -9177,6 +8901,7 @@ exports.AccessTokenEntity = AccessTokenEntity;
9177
8901
  exports.AccountEntity = AccountEntity;
9178
8902
  exports.AppMetadataEntity = AppMetadataEntity;
9179
8903
  exports.AuthError = AuthError;
8904
+ exports.AuthErrorCodes = AuthErrorCodes;
9180
8905
  exports.AuthErrorMessage = AuthErrorMessage;
9181
8906
  exports.AuthToken = AuthToken;
9182
8907
  exports.AuthenticationHeaderParser = AuthenticationHeaderParser;
@@ -9196,8 +8921,10 @@ exports.CacheType = CacheType;
9196
8921
  exports.CcsCredentialType = CcsCredentialType;
9197
8922
  exports.ClaimsRequestKeys = ClaimsRequestKeys;
9198
8923
  exports.ClientAuthError = ClientAuthError;
8924
+ exports.ClientAuthErrorCodes = ClientAuthErrorCodes;
9199
8925
  exports.ClientAuthErrorMessage = ClientAuthErrorMessage;
9200
8926
  exports.ClientConfigurationError = ClientConfigurationError;
8927
+ exports.ClientConfigurationErrorCodes = ClientConfigurationErrorCodes;
9201
8928
  exports.ClientConfigurationErrorMessage = ClientConfigurationErrorMessage;
9202
8929
  exports.CodeChallengeMethodValues = CodeChallengeMethodValues;
9203
8930
  exports.Constants = Constants;
@@ -9213,6 +8940,7 @@ exports.HttpStatus = HttpStatus;
9213
8940
  exports.IdTokenEntity = IdTokenEntity;
9214
8941
  exports.IntFields = IntFields;
9215
8942
  exports.InteractionRequiredAuthError = InteractionRequiredAuthError;
8943
+ exports.InteractionRequiredAuthErrorCodes = InteractionRequiredAuthErrorCodes;
9216
8944
  exports.InteractionRequiredAuthErrorMessage = InteractionRequiredAuthErrorMessage;
9217
8945
  exports.JoseHeader = JoseHeader;
9218
8946
  exports.Logger = Logger;
@@ -9252,6 +8980,10 @@ exports.TokenCacheContext = TokenCacheContext;
9252
8980
  exports.UrlString = UrlString;
9253
8981
  exports.buildClientInfo = buildClientInfo;
9254
8982
  exports.buildClientInfoFromHomeAccountId = buildClientInfoFromHomeAccountId;
8983
+ exports.createAuthError = createAuthError;
8984
+ exports.createClientAuthError = createClientAuthError;
8985
+ exports.createClientConfigurationError = createClientConfigurationError;
8986
+ exports.createInteractionRequiredAuthError = createInteractionRequiredAuthError;
9255
8987
  exports.invoke = invoke;
9256
8988
  exports.invokeAsync = invokeAsync;
9257
8989
  exports.version = version;