daftari 3.13.1 → 3.14.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 (250) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/distill/propose.d.ts.map +1 -1
  3. package/dist/distill/propose.js +10 -3
  4. package/dist/distill/propose.js.map +1 -1
  5. package/dist/extract/index.d.ts +16 -0
  6. package/dist/extract/index.d.ts.map +1 -0
  7. package/dist/extract/index.js +95 -0
  8. package/dist/extract/index.js.map +1 -0
  9. package/dist/extract/normalize.d.ts +7 -0
  10. package/dist/extract/normalize.d.ts.map +1 -0
  11. package/dist/extract/normalize.js +52 -0
  12. package/dist/extract/normalize.js.map +1 -0
  13. package/dist/extract/office.d.ts +63 -0
  14. package/dist/extract/office.d.ts.map +1 -0
  15. package/dist/extract/office.js +763 -0
  16. package/dist/extract/office.js.map +1 -0
  17. package/dist/extract/pdf.d.ts +16 -0
  18. package/dist/extract/pdf.d.ts.map +1 -0
  19. package/dist/extract/pdf.js +196 -0
  20. package/dist/extract/pdf.js.map +1 -0
  21. package/dist/extract/types.d.ts +55 -0
  22. package/dist/extract/types.d.ts.map +1 -0
  23. package/dist/extract/types.js +47 -0
  24. package/dist/extract/types.js.map +1 -0
  25. package/dist/extract/worker.d.ts +2 -0
  26. package/dist/extract/worker.d.ts.map +1 -0
  27. package/dist/extract/worker.js +57 -0
  28. package/dist/extract/worker.js.map +1 -0
  29. package/dist/integrations/engine.d.ts +174 -3
  30. package/dist/integrations/engine.d.ts.map +1 -1
  31. package/dist/integrations/engine.js +184 -16
  32. package/dist/integrations/engine.js.map +1 -1
  33. package/dist/integrations/google.d.ts +2 -1
  34. package/dist/integrations/google.d.ts.map +1 -1
  35. package/dist/integrations/google.js +12 -117
  36. package/dist/integrations/google.js.map +1 -1
  37. package/dist/integrations/http-json.d.ts +27 -0
  38. package/dist/integrations/http-json.d.ts.map +1 -0
  39. package/dist/integrations/http-json.js +148 -0
  40. package/dist/integrations/http-json.js.map +1 -0
  41. package/dist/integrations/microsoft.d.ts +22 -0
  42. package/dist/integrations/microsoft.d.ts.map +1 -0
  43. package/dist/integrations/microsoft.js +1780 -0
  44. package/dist/integrations/microsoft.js.map +1 -0
  45. package/dist/integrations/microsoft.ui.d.ts +18 -0
  46. package/dist/integrations/microsoft.ui.d.ts.map +1 -0
  47. package/dist/integrations/microsoft.ui.js +131 -0
  48. package/dist/integrations/microsoft.ui.js.map +1 -0
  49. package/dist/integrations/oauth.d.ts.map +1 -1
  50. package/dist/integrations/oauth.js +10 -2
  51. package/dist/integrations/oauth.js.map +1 -1
  52. package/dist/integrations/queue.d.ts +1 -1
  53. package/dist/integrations/queue.d.ts.map +1 -1
  54. package/dist/integrations/queue.js +23 -1
  55. package/dist/integrations/queue.js.map +1 -1
  56. package/dist/integrations/routes.d.ts +26 -0
  57. package/dist/integrations/routes.d.ts.map +1 -1
  58. package/dist/integrations/routes.js +502 -8
  59. package/dist/integrations/routes.js.map +1 -1
  60. package/dist/integrations/runtime.d.ts +14 -2
  61. package/dist/integrations/runtime.d.ts.map +1 -1
  62. package/dist/integrations/runtime.js +39 -7
  63. package/dist/integrations/runtime.js.map +1 -1
  64. package/dist/integrations/state.d.ts +1 -1
  65. package/dist/integrations/state.d.ts.map +1 -1
  66. package/dist/integrations/state.js +48 -8
  67. package/dist/integrations/state.js.map +1 -1
  68. package/dist/integrations/types.d.ts +54 -3
  69. package/dist/integrations/types.d.ts.map +1 -1
  70. package/dist/integrations/types.js +21 -1
  71. package/dist/integrations/types.js.map +1 -1
  72. package/dist/search/watcher.d.ts.map +1 -1
  73. package/dist/search/watcher.js +3 -22
  74. package/dist/search/watcher.js.map +1 -1
  75. package/dist/serve/index.d.ts.map +1 -1
  76. package/dist/serve/index.js +7 -0
  77. package/dist/serve/index.js.map +1 -1
  78. package/dist/sleep/index.js +2 -2
  79. package/dist/sleep/report.js +1 -1
  80. package/dist/sleep/report.js.map +1 -1
  81. package/dist/sleep/tension-scan.d.ts.map +1 -1
  82. package/dist/sleep/tension-scan.js +0 -0
  83. package/dist/sleep/tension-scan.js.map +1 -1
  84. package/dist/storage/local.d.ts +1 -0
  85. package/dist/storage/local.d.ts.map +1 -1
  86. package/dist/storage/local.js +8 -1
  87. package/dist/storage/local.js.map +1 -1
  88. package/dist/utils/config.d.ts +8 -1
  89. package/dist/utils/config.d.ts.map +1 -1
  90. package/dist/utils/config.js +143 -19
  91. package/dist/utils/config.js.map +1 -1
  92. package/dist/view/pages.d.ts.map +1 -1
  93. package/dist/view/pages.js +11 -0
  94. package/dist/view/pages.js.map +1 -1
  95. package/dist/view/render.d.ts.map +1 -1
  96. package/dist/view/render.js +37 -2
  97. package/dist/view/render.js.map +1 -1
  98. package/package.json +8 -3
  99. package/src/integrations/microsoft/assets/VENDORING.md +109 -0
  100. package/src/integrations/microsoft/assets/glue.js +244 -0
  101. package/src/integrations/microsoft/assets/picker-serializer.js +99 -0
  102. package/src/integrations/microsoft/assets/vendor/msal-browser/app/IPublicClientApplication.mjs +91 -0
  103. package/src/integrations/microsoft/assets/vendor/msal-browser/app/PublicClientApplication.mjs +355 -0
  104. package/src/integrations/microsoft/assets/vendor/msal-browser/broker/nativeBroker/NativeStatusCodes.mjs +15 -0
  105. package/src/integrations/microsoft/assets/vendor/msal-browser/broker/nativeBroker/PlatformAuthDOMHandler.mjs +153 -0
  106. package/src/integrations/microsoft/assets/vendor/msal-browser/broker/nativeBroker/PlatformAuthExtensionHandler.mjs +271 -0
  107. package/src/integrations/microsoft/assets/vendor/msal-browser/broker/nativeBroker/PlatformAuthProvider.mjs +95 -0
  108. package/src/integrations/microsoft/assets/vendor/msal-browser/cache/AccountManager.mjs +49 -0
  109. package/src/integrations/microsoft/assets/vendor/msal-browser/cache/AsyncMemoryStorage.mjs +144 -0
  110. package/src/integrations/microsoft/assets/vendor/msal-browser/cache/BrowserCacheManager.mjs +1465 -0
  111. package/src/integrations/microsoft/assets/vendor/msal-browser/cache/CacheHelpers.mjs +45 -0
  112. package/src/integrations/microsoft/assets/vendor/msal-browser/cache/CacheKeys.mjs +32 -0
  113. package/src/integrations/microsoft/assets/vendor/msal-browser/cache/CookieStorage.mjs +94 -0
  114. package/src/integrations/microsoft/assets/vendor/msal-browser/cache/DatabaseStorage.mjs +208 -0
  115. package/src/integrations/microsoft/assets/vendor/msal-browser/cache/EncryptedData.mjs +13 -0
  116. package/src/integrations/microsoft/assets/vendor/msal-browser/cache/LocalStorage.mjs +319 -0
  117. package/src/integrations/microsoft/assets/vendor/msal-browser/cache/MemoryStorage.mjs +48 -0
  118. package/src/integrations/microsoft/assets/vendor/msal-browser/cache/SessionStorage.mjs +46 -0
  119. package/src/integrations/microsoft/assets/vendor/msal-browser/cache/TokenCache.mjs +220 -0
  120. package/src/integrations/microsoft/assets/vendor/msal-browser/config/Configuration.mjs +138 -0
  121. package/src/integrations/microsoft/assets/vendor/msal-browser/controllers/NestedAppAuthController.mjs +483 -0
  122. package/src/integrations/microsoft/assets/vendor/msal-browser/controllers/StandardController.mjs +1532 -0
  123. package/src/integrations/microsoft/assets/vendor/msal-browser/crypto/BrowserCrypto.mjs +354 -0
  124. package/src/integrations/microsoft/assets/vendor/msal-browser/crypto/CryptoOps.mjs +146 -0
  125. package/src/integrations/microsoft/assets/vendor/msal-browser/crypto/PkceGenerator.mjs +63 -0
  126. package/src/integrations/microsoft/assets/vendor/msal-browser/crypto/SignedHttpRequest.mjs +50 -0
  127. package/src/integrations/microsoft/assets/vendor/msal-browser/crypto/TokenBindingKeyManager.mjs +156 -0
  128. package/src/integrations/microsoft/assets/vendor/msal-browser/encode/Base64Decode.mjs +43 -0
  129. package/src/integrations/microsoft/assets/vendor/msal-browser/encode/Base64Encode.mjs +47 -0
  130. package/src/integrations/microsoft/assets/vendor/msal-browser/error/BrowserAuthError.mjs +26 -0
  131. package/src/integrations/microsoft/assets/vendor/msal-browser/error/BrowserAuthErrorCodes.mjs +65 -0
  132. package/src/integrations/microsoft/assets/vendor/msal-browser/error/BrowserConfigurationAuthError.mjs +24 -0
  133. package/src/integrations/microsoft/assets/vendor/msal-browser/error/BrowserConfigurationAuthErrorCodes.mjs +11 -0
  134. package/src/integrations/microsoft/assets/vendor/msal-browser/error/NativeAuthError.mjs +79 -0
  135. package/src/integrations/microsoft/assets/vendor/msal-browser/error/NativeAuthErrorCodes.mjs +12 -0
  136. package/src/integrations/microsoft/assets/vendor/msal-browser/error/NestedAppAuthError.mjs +25 -0
  137. package/src/integrations/microsoft/assets/vendor/msal-browser/event/EventHandler.mjs +110 -0
  138. package/src/integrations/microsoft/assets/vendor/msal-browser/event/EventMessage.mjs +60 -0
  139. package/src/integrations/microsoft/assets/vendor/msal-browser/event/EventType.mjs +30 -0
  140. package/src/integrations/microsoft/assets/vendor/msal-browser/index.mjs +48 -0
  141. package/src/integrations/microsoft/assets/vendor/msal-browser/interaction_client/BaseInteractionClient.mjs +150 -0
  142. package/src/integrations/microsoft/assets/vendor/msal-browser/interaction_client/HybridSpaAuthorizationCodeClient.mjs +16 -0
  143. package/src/integrations/microsoft/assets/vendor/msal-browser/interaction_client/PlatformAuthInteractionClient.mjs +734 -0
  144. package/src/integrations/microsoft/assets/vendor/msal-browser/interaction_client/PopupClient.mjs +528 -0
  145. package/src/integrations/microsoft/assets/vendor/msal-browser/interaction_client/RedirectClient.mjs +464 -0
  146. package/src/integrations/microsoft/assets/vendor/msal-browser/interaction_client/SilentAuthCodeClient.mjs +85 -0
  147. package/src/integrations/microsoft/assets/vendor/msal-browser/interaction_client/SilentCacheClient.mjs +58 -0
  148. package/src/integrations/microsoft/assets/vendor/msal-browser/interaction_client/SilentIframeClient.mjs +255 -0
  149. package/src/integrations/microsoft/assets/vendor/msal-browser/interaction_client/SilentRefreshClient.mjs +77 -0
  150. package/src/integrations/microsoft/assets/vendor/msal-browser/interaction_client/StandardInteractionClient.mjs +217 -0
  151. package/src/integrations/microsoft/assets/vendor/msal-browser/interaction_handler/InteractionHandler.mjs +95 -0
  152. package/src/integrations/microsoft/assets/vendor/msal-browser/interaction_handler/SilentHandler.mjs +71 -0
  153. package/src/integrations/microsoft/assets/vendor/msal-browser/naa/BridgeError.mjs +11 -0
  154. package/src/integrations/microsoft/assets/vendor/msal-browser/naa/BridgeProxy.mjs +152 -0
  155. package/src/integrations/microsoft/assets/vendor/msal-browser/naa/BridgeStatusCode.mjs +18 -0
  156. package/src/integrations/microsoft/assets/vendor/msal-browser/naa/mapping/NestedAppAuthAdapter.mjs +239 -0
  157. package/src/integrations/microsoft/assets/vendor/msal-browser/navigation/NavigationClient.mjs +47 -0
  158. package/src/integrations/microsoft/assets/vendor/msal-browser/network/FetchClient.mjs +153 -0
  159. package/src/integrations/microsoft/assets/vendor/msal-browser/operatingcontext/BaseOperatingContext.mjs +112 -0
  160. package/src/integrations/microsoft/assets/vendor/msal-browser/operatingcontext/NestedAppOperatingContext.mjs +79 -0
  161. package/src/integrations/microsoft/assets/vendor/msal-browser/operatingcontext/StandardOperatingContext.mjs +50 -0
  162. package/src/integrations/microsoft/assets/vendor/msal-browser/packageMetadata.mjs +7 -0
  163. package/src/integrations/microsoft/assets/vendor/msal-browser/popup_relay/constants.mjs +20 -0
  164. package/src/integrations/microsoft/assets/vendor/msal-browser/popup_relay/relayClient.mjs +113 -0
  165. package/src/integrations/microsoft/assets/vendor/msal-browser/protocol/Authorize.mjs +326 -0
  166. package/src/integrations/microsoft/assets/vendor/msal-browser/request/RequestHelpers.mjs +143 -0
  167. package/src/integrations/microsoft/assets/vendor/msal-browser/response/ResponseHandler.mjs +45 -0
  168. package/src/integrations/microsoft/assets/vendor/msal-browser/telemetry/BrowserPerformanceClient.mjs +126 -0
  169. package/src/integrations/microsoft/assets/vendor/msal-browser/telemetry/BrowserPerformanceEvents.mjs +133 -0
  170. package/src/integrations/microsoft/assets/vendor/msal-browser/telemetry/BrowserPerformanceMeasurement.mjs +96 -0
  171. package/src/integrations/microsoft/assets/vendor/msal-browser/telemetry/BrowserRootPerformanceEvents.mjs +53 -0
  172. package/src/integrations/microsoft/assets/vendor/msal-browser/utils/BrowserConstants.mjs +220 -0
  173. package/src/integrations/microsoft/assets/vendor/msal-browser/utils/BrowserProtocolUtils.mjs +27 -0
  174. package/src/integrations/microsoft/assets/vendor/msal-browser/utils/BrowserUtils.mjs +364 -0
  175. package/src/integrations/microsoft/assets/vendor/msal-browser/utils/Helpers.mjs +19 -0
  176. package/src/integrations/microsoft/assets/vendor/msal-browser/utils/MsalFrameStatsUtils.mjs +38 -0
  177. package/src/integrations/microsoft/assets/vendor/msal-browser/webBrokerBridge/PendingRequestRegistry.mjs +63 -0
  178. package/src/integrations/microsoft/assets/vendor/msal-browser/webBrokerBridge/WebBrokerBridgeError.mjs +38 -0
  179. package/src/integrations/microsoft/assets/vendor/msal-browser/webBrokerBridge/WebBrokerBridgeErrorMap.mjs +57 -0
  180. package/src/integrations/microsoft/assets/vendor/msal-common/account/AccountInfo.mjs +91 -0
  181. package/src/integrations/microsoft/assets/vendor/msal-common/account/AuthToken.mjs +70 -0
  182. package/src/integrations/microsoft/assets/vendor/msal-common/account/CcsCredential.mjs +12 -0
  183. package/src/integrations/microsoft/assets/vendor/msal-common/account/ClientInfo.mjs +43 -0
  184. package/src/integrations/microsoft/assets/vendor/msal-common/account/TokenClaims.mjs +24 -0
  185. package/src/integrations/microsoft/assets/vendor/msal-common/authority/Authority.mjs +988 -0
  186. package/src/integrations/microsoft/assets/vendor/msal-common/authority/AuthorityFactory.mjs +41 -0
  187. package/src/integrations/microsoft/assets/vendor/msal-common/authority/AuthorityMetadata.mjs +158 -0
  188. package/src/integrations/microsoft/assets/vendor/msal-common/authority/AuthorityOptions.mjs +20 -0
  189. package/src/integrations/microsoft/assets/vendor/msal-common/authority/AuthorityType.mjs +16 -0
  190. package/src/integrations/microsoft/assets/vendor/msal-common/authority/CloudInstanceDiscoveryErrorResponse.mjs +12 -0
  191. package/src/integrations/microsoft/assets/vendor/msal-common/authority/CloudInstanceDiscoveryResponse.mjs +12 -0
  192. package/src/integrations/microsoft/assets/vendor/msal-common/authority/OpenIdConfigResponse.mjs +14 -0
  193. package/src/integrations/microsoft/assets/vendor/msal-common/authority/ProtocolMode.mjs +26 -0
  194. package/src/integrations/microsoft/assets/vendor/msal-common/authority/RegionDiscovery.mjs +116 -0
  195. package/src/integrations/microsoft/assets/vendor/msal-common/cache/CacheManager.mjs +1202 -0
  196. package/src/integrations/microsoft/assets/vendor/msal-common/cache/persistence/TokenCacheContext.mjs +29 -0
  197. package/src/integrations/microsoft/assets/vendor/msal-common/cache/utils/AccountEntityUtils.mjs +222 -0
  198. package/src/integrations/microsoft/assets/vendor/msal-common/cache/utils/CacheHelpers.mjs +294 -0
  199. package/src/integrations/microsoft/assets/vendor/msal-common/client/AuthorizationCodeClient.mjs +289 -0
  200. package/src/integrations/microsoft/assets/vendor/msal-common/client/RefreshTokenClient.mjs +262 -0
  201. package/src/integrations/microsoft/assets/vendor/msal-common/client/SilentFlowClient.mjs +142 -0
  202. package/src/integrations/microsoft/assets/vendor/msal-common/config/ClientConfiguration.mjs +111 -0
  203. package/src/integrations/microsoft/assets/vendor/msal-common/constants/AADServerParamKeys.mjs +74 -0
  204. package/src/integrations/microsoft/assets/vendor/msal-common/crypto/DpopProofGenerator.mjs +152 -0
  205. package/src/integrations/microsoft/assets/vendor/msal-common/crypto/ICrypto.mjs +52 -0
  206. package/src/integrations/microsoft/assets/vendor/msal-common/crypto/ITokenBindingKeyManager.mjs +27 -0
  207. package/src/integrations/microsoft/assets/vendor/msal-common/crypto/JoseHeader.mjs +72 -0
  208. package/src/integrations/microsoft/assets/vendor/msal-common/crypto/PopTokenGenerator.mjs +109 -0
  209. package/src/integrations/microsoft/assets/vendor/msal-common/error/AuthError.mjs +31 -0
  210. package/src/integrations/microsoft/assets/vendor/msal-common/error/AuthErrorCodes.mjs +13 -0
  211. package/src/integrations/microsoft/assets/vendor/msal-common/error/CacheError.mjs +44 -0
  212. package/src/integrations/microsoft/assets/vendor/msal-common/error/CacheErrorCodes.mjs +10 -0
  213. package/src/integrations/microsoft/assets/vendor/msal-common/error/ClientAuthError.mjs +26 -0
  214. package/src/integrations/microsoft/assets/vendor/msal-common/error/ClientAuthErrorCodes.mjs +46 -0
  215. package/src/integrations/microsoft/assets/vendor/msal-common/error/ClientConfigurationError.mjs +23 -0
  216. package/src/integrations/microsoft/assets/vendor/msal-common/error/ClientConfigurationErrorCodes.mjs +38 -0
  217. package/src/integrations/microsoft/assets/vendor/msal-common/error/InteractionRequiredAuthError.mjs +73 -0
  218. package/src/integrations/microsoft/assets/vendor/msal-common/error/InteractionRequiredAuthErrorCodes.mjs +53 -0
  219. package/src/integrations/microsoft/assets/vendor/msal-common/error/JoseHeaderError.mjs +24 -0
  220. package/src/integrations/microsoft/assets/vendor/msal-common/error/JoseHeaderErrorCodes.mjs +12 -0
  221. package/src/integrations/microsoft/assets/vendor/msal-common/error/NetworkError.mjs +34 -0
  222. package/src/integrations/microsoft/assets/vendor/msal-common/error/PlatformBrokerError.mjs +48 -0
  223. package/src/integrations/microsoft/assets/vendor/msal-common/error/ServerError.mjs +22 -0
  224. package/src/integrations/microsoft/assets/vendor/msal-common/index-browser.mjs +79 -0
  225. package/src/integrations/microsoft/assets/vendor/msal-common/logger/Logger.mjs +291 -0
  226. package/src/integrations/microsoft/assets/vendor/msal-common/network/INetworkModule.mjs +20 -0
  227. package/src/integrations/microsoft/assets/vendor/msal-common/network/RequestThumbprint.mjs +27 -0
  228. package/src/integrations/microsoft/assets/vendor/msal-common/network/ThrottlingUtils.mjs +91 -0
  229. package/src/integrations/microsoft/assets/vendor/msal-common/packageMetadata.mjs +7 -0
  230. package/src/integrations/microsoft/assets/vendor/msal-common/protocol/Authorize.mjs +239 -0
  231. package/src/integrations/microsoft/assets/vendor/msal-common/protocol/Token.mjs +148 -0
  232. package/src/integrations/microsoft/assets/vendor/msal-common/request/AuthenticationHeaderParser.mjs +63 -0
  233. package/src/integrations/microsoft/assets/vendor/msal-common/request/BaseAuthRequest.mjs +37 -0
  234. package/src/integrations/microsoft/assets/vendor/msal-common/request/RequestParameterBuilder.mjs +529 -0
  235. package/src/integrations/microsoft/assets/vendor/msal-common/request/ScopeSet.mjs +204 -0
  236. package/src/integrations/microsoft/assets/vendor/msal-common/response/ResponseHandler.mjs +432 -0
  237. package/src/integrations/microsoft/assets/vendor/msal-common/telemetry/performance/PerformanceClient.mjs +557 -0
  238. package/src/integrations/microsoft/assets/vendor/msal-common/telemetry/performance/PerformanceEvent.mjs +68 -0
  239. package/src/integrations/microsoft/assets/vendor/msal-common/telemetry/performance/PerformanceEvents.mjs +73 -0
  240. package/src/integrations/microsoft/assets/vendor/msal-common/telemetry/performance/StubPerformanceClient.mjs +61 -0
  241. package/src/integrations/microsoft/assets/vendor/msal-common/telemetry/server/ServerTelemetryManager.mjs +297 -0
  242. package/src/integrations/microsoft/assets/vendor/msal-common/url/UrlString.mjs +164 -0
  243. package/src/integrations/microsoft/assets/vendor/msal-common/utils/ClientAssertionUtils.mjs +21 -0
  244. package/src/integrations/microsoft/assets/vendor/msal-common/utils/Constants.mjs +304 -0
  245. package/src/integrations/microsoft/assets/vendor/msal-common/utils/FunctionWrappers.mjs +95 -0
  246. package/src/integrations/microsoft/assets/vendor/msal-common/utils/ObjectUtils.mjs +27 -0
  247. package/src/integrations/microsoft/assets/vendor/msal-common/utils/ProtocolUtils.mjs +76 -0
  248. package/src/integrations/microsoft/assets/vendor/msal-common/utils/StringUtils.mjs +82 -0
  249. package/src/integrations/microsoft/assets/vendor/msal-common/utils/TimeUtils.mjs +75 -0
  250. package/src/integrations/microsoft/assets/vendor/msal-common/utils/UrlUtils.mjs +128 -0
@@ -0,0 +1,1532 @@
1
+ /*! @azure/msal-browser v5.20.0 2026-08-28 */
2
+ 'use strict';
3
+ import { CryptoOps } from '../crypto/CryptoOps.mjs';
4
+ import { DEFAULT_CRYPTO_IMPLEMENTATION, DEFAULT_TOKEN_BINDING_KEY_MANAGER, buildStaticAuthorityOptions, invokeAsync, enforceResourceParameter, InteractionRequiredAuthError, createClientAuthError, ClientAuthErrorCodes, AccountEntityUtils, AuthToken, CacheHelpers, TimeUtils, Constants, AuthError, getRequestThumbprint, InteractionRequiredAuthErrorCodes } from '../../msal-common/index-browser.mjs';
5
+ import { InitializeCache, HandleNativeRedirectPromiseMeasurement, HandleRedirectPromiseMeasurement, NativeInteractionClientAcquireTokenRedirect, AcquireTokenByCodeAsync, SilentCacheClientAcquireToken, SilentRefreshClientAcquireToken, SilentIframeClientAcquireToken, NativeInteractionClientAcquireToken, AcquireTokenSilentAsync, InitializeSilentRequest, AcquireTokenBySilentIframe, AwaitConcurrentIframe, AcquireTokenFromCache, AcquireTokenByRefreshToken, GeneratePkceCodes } from '../telemetry/BrowserPerformanceEvents.mjs';
6
+ import { InitializeClientApplication, AcquireTokenRedirect, AcquireTokenPreRedirect, AcquireTokenPopup, SsoCapable, SsoSilent, AcquireTokenByCode, AcquireTokenSilent } from '../telemetry/BrowserRootPerformanceEvents.mjs';
7
+ import { BrowserCacheManager, DEFAULT_BROWSER_CACHE_MANAGER } from '../cache/BrowserCacheManager.mjs';
8
+ import { SSO_CAPABLE } from '../cache/CacheKeys.mjs';
9
+ import { getAllAccounts, getAccount, setActiveAccount, getActiveAccount } from '../cache/AccountManager.mjs';
10
+ import { BrowserCacheLocation, INTERACTION_TYPE, InteractionType, ApiId, CacheLookupPolicy, DEFAULT_REQUEST, BrowserConstants, iFrameRenewalPolicies } from '../utils/BrowserConstants.mjs';
11
+ import { blockAPICallsBeforeInitialize, redirectPreflightCheck, preflightCheck as preflightCheck$1, blockNonBrowserEnvironment } from '../utils/BrowserUtils.mjs';
12
+ import { EventType } from '../event/EventType.mjs';
13
+ import { EventHandler } from '../event/EventHandler.mjs';
14
+ import { base64Decode } from '../encode/Base64Decode.mjs';
15
+ import { PopupClient } from '../interaction_client/PopupClient.mjs';
16
+ import { RedirectClient } from '../interaction_client/RedirectClient.mjs';
17
+ import { SilentIframeClient } from '../interaction_client/SilentIframeClient.mjs';
18
+ import { SilentRefreshClient } from '../interaction_client/SilentRefreshClient.mjs';
19
+ import { PlatformAuthInteractionClient } from '../interaction_client/PlatformAuthInteractionClient.mjs';
20
+ import { NativeAuthError, isFatalNativeAuthError } from '../error/NativeAuthError.mjs';
21
+ import { SilentCacheClient } from '../interaction_client/SilentCacheClient.mjs';
22
+ import { SilentAuthCodeClient } from '../interaction_client/SilentAuthCodeClient.mjs';
23
+ import { createBrowserAuthError } from '../error/BrowserAuthError.mjs';
24
+ import { createNewGuid } from '../crypto/BrowserCrypto.mjs';
25
+ import { initializeSilentRequest } from '../request/RequestHelpers.mjs';
26
+ import { generatePkceCodes } from '../crypto/PkceGenerator.mjs';
27
+ import { getPlatformAuthProvider, isPlatformAuthAllowed } from '../broker/nativeBroker/PlatformAuthProvider.mjs';
28
+ import { collectInstanceStats } from '../utils/MsalFrameStatsUtils.mjs';
29
+ import { TokenBindingKeyManager } from '../crypto/TokenBindingKeyManager.mjs';
30
+ import { spaCodeAndNativeAccountIdPresent, unableToAcquireTokenFromNativePlatform, authCodeOrNativeAccountIdRequired, nativeConnectionNotEstablished, noAccountError } from '../error/BrowserAuthErrorCodes.mjs';
31
+
32
+ /*
33
+ * Copyright (c) Microsoft Corporation. All rights reserved.
34
+ * Licensed under the MIT License.
35
+ */
36
+ function preflightCheck(initialized, performanceEvent, config, request) {
37
+ try {
38
+ preflightCheck$1(initialized);
39
+ enforceResourceParameter(config.auth.isMcp, request);
40
+ }
41
+ catch (e) {
42
+ performanceEvent.end({ success: false }, e, request.account);
43
+ throw e;
44
+ }
45
+ }
46
+ class StandardController {
47
+ /**
48
+ * @constructor
49
+ * Constructor for the PublicClientApplication used to instantiate the PublicClientApplication object
50
+ *
51
+ * Important attributes in the Configuration object for auth are:
52
+ * - clientID: the application ID of your application. You can obtain one by registering your application with our Application registration portal : https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredAppsPreview
53
+ * - authority: the authority URL for your application.
54
+ * - redirect_uri: the uri of your application registered in the portal.
55
+ *
56
+ * In Azure AD, authority is a URL indicating the Azure active directory that MSAL uses to obtain tokens.
57
+ * It is of the form https://login.microsoftonline.com/{Enter_the_Tenant_Info_Here}
58
+ * If your application supports Accounts in one organizational directory, replace "Enter_the_Tenant_Info_Here" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com).
59
+ * If your application supports Accounts in any organizational directory, replace "Enter_the_Tenant_Info_Here" value with organizations.
60
+ * If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace "Enter_the_Tenant_Info_Here" value with common.
61
+ * To restrict support to Personal Microsoft accounts only, replace "Enter_the_Tenant_Info_Here" value with consumers.
62
+ *
63
+ * In Azure B2C, authority is of the form https://{instance}/tfp/{tenant}/{policyName}/
64
+ * Full B2C functionality will be available in this library in future versions.
65
+ *
66
+ * @param configuration Object for the MSAL PublicClientApplication instance
67
+ */
68
+ constructor(operatingContext) {
69
+ this.operatingContext = operatingContext;
70
+ this.isBrowserEnvironment =
71
+ this.operatingContext.isBrowserEnvironment();
72
+ // Set the configuration.
73
+ this.config = operatingContext.getConfig();
74
+ this.initialized = false;
75
+ // Initialize logger
76
+ this.logger = this.operatingContext.getLogger();
77
+ // Initialize the network module class.
78
+ this.networkClient = this.config.system.networkClient;
79
+ // Initialize the navigation client class.
80
+ this.navigationClient = this.config.system.navigationClient;
81
+ // Initialize redirectResponse Map
82
+ this.redirectResponse = new Map();
83
+ // Initial hybrid spa map
84
+ this.hybridAuthCodeResponses = new Map();
85
+ // Initialize performance client
86
+ this.performanceClient = this.config.telemetry.client;
87
+ // Initialize environment-specific crypto and token-binding services.
88
+ if (this.isBrowserEnvironment) {
89
+ this.browserCrypto = new CryptoOps(this.logger, this.performanceClient);
90
+ this.tokenBindingKeyManager = new TokenBindingKeyManager(this.logger, this.performanceClient);
91
+ }
92
+ else {
93
+ this.browserCrypto = DEFAULT_CRYPTO_IMPLEMENTATION;
94
+ this.tokenBindingKeyManager = DEFAULT_TOKEN_BINDING_KEY_MANAGER;
95
+ }
96
+ this.eventHandler = new EventHandler(this.logger);
97
+ // Initialize the browser storage class.
98
+ this.browserStorage = this.isBrowserEnvironment
99
+ ? new BrowserCacheManager(this.config.auth.clientId, this.config.cache, this.browserCrypto, this.logger, this.performanceClient, this.eventHandler, buildStaticAuthorityOptions(this.config.auth), this.tokenBindingKeyManager)
100
+ : DEFAULT_BROWSER_CACHE_MANAGER(this.config.auth.clientId, this.logger, this.performanceClient, this.eventHandler, undefined, this.tokenBindingKeyManager);
101
+ // initialize in memory storage for native flows
102
+ const nativeCacheOptions = {
103
+ cacheLocation: BrowserCacheLocation.MemoryStorage,
104
+ cacheRetentionDays: 5,
105
+ };
106
+ this.nativeInternalStorage = new BrowserCacheManager(this.config.auth.clientId, nativeCacheOptions, this.browserCrypto, this.logger, this.performanceClient, this.eventHandler, undefined, this.tokenBindingKeyManager);
107
+ this.activeSilentTokenRequests = new Map();
108
+ // Register listener functions
109
+ this.trackStateChange = this.trackStateChange.bind(this);
110
+ // Register listener functions
111
+ this.trackStateChangeWithMeasurement =
112
+ this.trackStateChangeWithMeasurement.bind(this);
113
+ }
114
+ static async createController(operatingContext, request) {
115
+ const controller = new StandardController(operatingContext);
116
+ await controller.initialize(request);
117
+ return controller;
118
+ }
119
+ trackStateChange(correlationId, event) {
120
+ if (!correlationId) {
121
+ return;
122
+ }
123
+ if (event.type === "visibilitychange") {
124
+ this.logger.info("16v6hv", correlationId);
125
+ this.performanceClient.incrementFields({ visibilityChangeCount: 1 }, correlationId);
126
+ }
127
+ else if (event.type === "online") {
128
+ this.logger.info("0zirfd", correlationId);
129
+ this.performanceClient.incrementFields({ onlineStatusChangeCount: 1 }, correlationId);
130
+ }
131
+ else if (event.type === "offline") {
132
+ this.logger.info("1xk9ef", correlationId);
133
+ this.performanceClient.incrementFields({ onlineStatusChangeCount: 1 }, correlationId);
134
+ }
135
+ }
136
+ /**
137
+ * Initializer function to perform async startup tasks such as connecting to WAM extension
138
+ * @param request {?InitializeApplicationRequest} correlation id
139
+ */
140
+ async initialize(request) {
141
+ const correlationId = this.getRequestCorrelationId(request);
142
+ this.logger.trace("1f7joy", correlationId);
143
+ if (this.initialized) {
144
+ this.logger.info("061m5x", correlationId);
145
+ return;
146
+ }
147
+ if (!this.isBrowserEnvironment) {
148
+ this.logger.info("19fvpi", correlationId);
149
+ this.initialized = true;
150
+ this.eventHandler.emitEvent(EventType.INITIALIZE_END, correlationId);
151
+ return;
152
+ }
153
+ const allowPlatformBroker = this.config.system.allowPlatformBroker;
154
+ const initMeasurement = this.performanceClient.startMeasurement(InitializeClientApplication, correlationId);
155
+ this.eventHandler.emitEvent(EventType.INITIALIZE_START, correlationId);
156
+ // Broker applications are initialized twice, so we avoid double-counting it
157
+ this.logMultipleInstances(initMeasurement, correlationId);
158
+ initMeasurement.add({ isMcp: this.config.auth.isMcp });
159
+ await invokeAsync(this.browserStorage.initialize.bind(this.browserStorage), InitializeCache, this.logger, this.performanceClient, correlationId)(correlationId);
160
+ if (allowPlatformBroker) {
161
+ try {
162
+ // check if platform authentication is available via DOM or browser extension and create relevant handlers
163
+ this.platformAuthProvider = await getPlatformAuthProvider(this.logger, this.performanceClient, correlationId, this.config.system.nativeBrokerHandshakeTimeout, this.config.experimental.allowPlatformBrokerWithDOM);
164
+ }
165
+ catch (e) {
166
+ this.logger.verbose(e, correlationId);
167
+ }
168
+ }
169
+ if (this.config.cache.cacheLocation ===
170
+ BrowserCacheLocation.LocalStorage) {
171
+ this.eventHandler.subscribeCrossTab();
172
+ }
173
+ !this.config.system.navigatePopups &&
174
+ (await this.preGeneratePkceCodes(correlationId));
175
+ this.initialized = true;
176
+ this.eventHandler.emitEvent(EventType.INITIALIZE_END, correlationId);
177
+ initMeasurement.end({
178
+ allowPlatformBroker: allowPlatformBroker,
179
+ success: true,
180
+ });
181
+ }
182
+ // #region Redirect Flow
183
+ /**
184
+ * Event handler function which allows users to fire events after the PublicClientApplication object
185
+ * has loaded during redirect flows. This should be invoked on all page loads involved in redirect
186
+ * auth flows.
187
+ * @param hash Hash to process. Defaults to the current value of window.location.hash. Only needs to be provided explicitly if the response to be handled is not contained in the current value.
188
+ * @param options Object containing optional configuration for redirect promise handling.
189
+ * @returns Token response or null. If the return value is null, then no auth redirect was detected.
190
+ */
191
+ async handleRedirectPromise(options) {
192
+ this.logger.verbose("02l8bm", "");
193
+ // Block token acquisition before initialize has been called
194
+ blockAPICallsBeforeInitialize(this.initialized);
195
+ if (this.isBrowserEnvironment) {
196
+ /**
197
+ * Store the promise on the PublicClientApplication instance if this is the first invocation of handleRedirectPromise,
198
+ * otherwise return the promise from the first invocation. Prevents race conditions when handleRedirectPromise is called
199
+ * several times concurrently.
200
+ */
201
+ const redirectResponseKey = options?.hash || "";
202
+ let response = this.redirectResponse.get(redirectResponseKey);
203
+ if (typeof response === "undefined") {
204
+ response = this.handleRedirectPromiseInternal(options);
205
+ this.redirectResponse.set(redirectResponseKey, response);
206
+ this.logger.verbose("1wn9kp", "");
207
+ }
208
+ else {
209
+ this.logger.verbose("0w0gm3", "");
210
+ }
211
+ return response;
212
+ }
213
+ this.logger.verbose("12xi63", "");
214
+ return null;
215
+ }
216
+ /**
217
+ * The internal details of handleRedirectPromise. This is separated out to a helper to allow handleRedirectPromise to memoize requests
218
+ * @param hash
219
+ * @returns
220
+ */
221
+ async handleRedirectPromiseInternal(options) {
222
+ if (!this.browserStorage.isInteractionInProgress(true)) {
223
+ this.logger.info("0le6uv", "");
224
+ return null;
225
+ }
226
+ const interactionType = this.browserStorage.getInteractionInProgress()?.type;
227
+ if (interactionType === INTERACTION_TYPE.SIGNOUT) {
228
+ this.logger.verbose("1ywcv2", "");
229
+ this.browserStorage.setInteractionInProgress(false);
230
+ return Promise.resolve(null);
231
+ }
232
+ const loggedInAccounts = this.getAllAccounts();
233
+ const platformBrokerRequest = this.browserStorage.getCachedNativeRequest();
234
+ const useNative = platformBrokerRequest && !options?.hash;
235
+ let rootMeasurement;
236
+ let redirectResponse;
237
+ let cachedRedirectRequest;
238
+ try {
239
+ if (useNative && this.platformAuthProvider) {
240
+ const correlationId = platformBrokerRequest?.correlationId || "";
241
+ this.eventHandler.emitEvent(EventType.HANDLE_REDIRECT_START, correlationId, InteractionType.Redirect);
242
+ rootMeasurement = this.performanceClient.startMeasurement(AcquireTokenRedirect, correlationId);
243
+ this.logger.trace("12v7is", correlationId);
244
+ // Cached nativeAccountId routes directly to the broker (no /authorize call)
245
+ rootMeasurement.add({
246
+ isPlatformBrokerRequest: true,
247
+ });
248
+ const nativeClient = new PlatformAuthInteractionClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, ApiId.handleRedirectPromise, this.performanceClient, this.platformAuthProvider, platformBrokerRequest.accountId, this.nativeInternalStorage, platformBrokerRequest.correlationId, this.tokenBindingKeyManager);
249
+ redirectResponse = invokeAsync(nativeClient.handleRedirectPromise.bind(nativeClient), HandleNativeRedirectPromiseMeasurement, this.logger, this.performanceClient, rootMeasurement.event.correlationId)();
250
+ }
251
+ else {
252
+ const [standardRequest, codeVerifier] = this.browserStorage.getCachedRequest("");
253
+ cachedRedirectRequest = standardRequest;
254
+ const correlationId = standardRequest.correlationId;
255
+ this.eventHandler.emitEvent(EventType.HANDLE_REDIRECT_START, correlationId, InteractionType.Redirect);
256
+ // Reset rootMeasurement now that we have correlationId
257
+ rootMeasurement = this.performanceClient.startMeasurement(AcquireTokenRedirect, correlationId);
258
+ this.logger.trace("0znzs5", correlationId);
259
+ const redirectClient = this.createRedirectClient(correlationId);
260
+ redirectResponse = invokeAsync(redirectClient.handleRedirectPromise.bind(redirectClient), HandleRedirectPromiseMeasurement, this.logger, this.performanceClient, rootMeasurement.event.correlationId)(standardRequest, codeVerifier, rootMeasurement, options);
261
+ }
262
+ }
263
+ catch (e) {
264
+ this.browserStorage.resetRequestCache("");
265
+ throw e;
266
+ }
267
+ return redirectResponse
268
+ .then((result) => {
269
+ if (result) {
270
+ this.browserStorage.resetRequestCache(result.correlationId);
271
+ this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_SUCCESS, result.correlationId, InteractionType.Redirect, result);
272
+ this.logger.verbose("0ui8f5", result.correlationId);
273
+ // Emit login event if number of accounts change
274
+ const isLoggingIn = loggedInAccounts.length < this.getAllAccounts().length;
275
+ if (isLoggingIn) {
276
+ this.eventHandler.emitEvent(EventType.LOGIN_SUCCESS, result.correlationId, InteractionType.Redirect, result.account);
277
+ this.logger.verbose("16im3l", result.correlationId);
278
+ }
279
+ rootMeasurement.end({
280
+ success: true,
281
+ isNativeBroker: result.fromPlatformBroker ?? false,
282
+ }, undefined, result.account);
283
+ // Fire-and-forget SSO capability verification in background
284
+ this.verifySsoCapability(cachedRedirectRequest, InteractionType.Redirect);
285
+ }
286
+ else {
287
+ /*
288
+ * Instrument an event only if an error code is set. Otherwise, discard it when the redirect response
289
+ * is empty and the error code is missing.
290
+ */
291
+ if (!!rootMeasurement.event.errorCode) {
292
+ rootMeasurement.end({ success: false });
293
+ }
294
+ else {
295
+ rootMeasurement.discard();
296
+ }
297
+ }
298
+ this.eventHandler.emitEvent(EventType.HANDLE_REDIRECT_END, rootMeasurement.event.correlationId, InteractionType.Redirect);
299
+ return result;
300
+ })
301
+ .catch((e) => {
302
+ this.browserStorage.resetRequestCache(rootMeasurement.event.correlationId);
303
+ const eventError = e;
304
+ this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, rootMeasurement.event.correlationId, InteractionType.Redirect, null, eventError);
305
+ this.eventHandler.emitEvent(EventType.HANDLE_REDIRECT_END, rootMeasurement.event.correlationId, InteractionType.Redirect);
306
+ rootMeasurement.end({
307
+ success: false,
308
+ }, eventError);
309
+ throw e;
310
+ });
311
+ }
312
+ /**
313
+ * Use when you want to obtain an access_token for your API by redirecting the user's browser window to the authorization endpoint. This function redirects
314
+ * the page, so any code that follows this function will not execute.
315
+ *
316
+ * IMPORTANT: It is NOT recommended to have code that is dependent on the resolution of the Promise. This function will navigate away from the current
317
+ * browser window. It currently returns a Promise in order to reflect the asynchronous nature of the code running in this function.
318
+ *
319
+ * @param request
320
+ */
321
+ async acquireTokenRedirect(request) {
322
+ // Preflight request
323
+ const correlationId = this.getRequestCorrelationId(request);
324
+ this.logger.verbose("0os66p", correlationId);
325
+ redirectPreflightCheck(this.initialized, this.config);
326
+ this.browserStorage.setInteractionInProgress(true, INTERACTION_TYPE.SIGNIN);
327
+ const atrMeasurement = this.performanceClient.startMeasurement(AcquireTokenPreRedirect, correlationId);
328
+ atrMeasurement.add({
329
+ scenarioId: request.scenarioId,
330
+ });
331
+ const configOnRedirectNavigateCb = this.config.auth.onRedirectNavigate;
332
+ this.config.auth.onRedirectNavigate = (url) => {
333
+ const navigate = typeof configOnRedirectNavigateCb === "function"
334
+ ? configOnRedirectNavigateCb(url)
335
+ : undefined;
336
+ atrMeasurement.add({
337
+ navigateCallbackResult: navigate !== false,
338
+ });
339
+ atrMeasurement.event =
340
+ atrMeasurement.end({ success: true }, undefined, request.account) || atrMeasurement.event;
341
+ return navigate;
342
+ };
343
+ try {
344
+ enforceResourceParameter(this.config.auth.isMcp, request);
345
+ this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_START, correlationId, InteractionType.Redirect, request);
346
+ let result;
347
+ if (this.platformAuthProvider &&
348
+ this.canUsePlatformBroker(request)) {
349
+ const nativeClient = new PlatformAuthInteractionClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, ApiId.acquireTokenRedirect, this.performanceClient, this.platformAuthProvider, this.getNativeAccountId(request), this.nativeInternalStorage, correlationId, this.tokenBindingKeyManager);
350
+ result = invokeAsync(nativeClient.acquireTokenRedirect.bind(nativeClient), NativeInteractionClientAcquireTokenRedirect, this.logger, this.performanceClient, correlationId)(request, atrMeasurement).catch((e) => {
351
+ if (e instanceof NativeAuthError &&
352
+ isFatalNativeAuthError(e)) {
353
+ this.platformAuthProvider = undefined; // If extension gets uninstalled during session prevent future requests from continuing to attempt platform broker calls
354
+ const redirectClient = this.createRedirectClient(correlationId);
355
+ return redirectClient.acquireToken(request);
356
+ }
357
+ else if (e instanceof InteractionRequiredAuthError) {
358
+ this.logger.verbose("1ipyz4", correlationId);
359
+ const redirectClient = this.createRedirectClient(correlationId);
360
+ return redirectClient.acquireToken(request);
361
+ }
362
+ throw e;
363
+ });
364
+ }
365
+ else {
366
+ const redirectClient = this.createRedirectClient(correlationId);
367
+ result = redirectClient.acquireToken(request);
368
+ }
369
+ return await result;
370
+ }
371
+ catch (e) {
372
+ this.browserStorage.resetRequestCache(correlationId);
373
+ /*
374
+ * Pre-redirect event completes before navigation occurs.
375
+ * Timed out navigation needs to be instrumented separately as a post-redirect event.
376
+ */
377
+ if (atrMeasurement.event.status === 2) {
378
+ this.performanceClient
379
+ .startMeasurement(AcquireTokenRedirect, correlationId)
380
+ .end({ success: false }, e, request.account);
381
+ }
382
+ else {
383
+ atrMeasurement.end({ success: false }, e, request.account);
384
+ }
385
+ this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, correlationId, InteractionType.Redirect, null, e);
386
+ throw e;
387
+ }
388
+ }
389
+ // #endregion
390
+ // #region Popup Flow
391
+ /**
392
+ * Use when you want to obtain an access_token for your API via opening a popup window in the user's browser
393
+ *
394
+ * @param request
395
+ *
396
+ * @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
397
+ */
398
+ acquireTokenPopup(request) {
399
+ const correlationId = this.getRequestCorrelationId(request);
400
+ const atPopupMeasurement = this.performanceClient.startMeasurement(AcquireTokenPopup, correlationId);
401
+ atPopupMeasurement.add({
402
+ scenarioId: request.scenarioId,
403
+ });
404
+ try {
405
+ this.logger.verbose("0ch87b", correlationId);
406
+ preflightCheck(this.initialized, atPopupMeasurement, this.config, request);
407
+ this.browserStorage.setInteractionInProgress(true, INTERACTION_TYPE.SIGNIN, request.overrideInteractionInProgress, correlationId);
408
+ }
409
+ catch (e) {
410
+ // Since this function is syncronous we need to reject
411
+ return Promise.reject(e);
412
+ }
413
+ // If logged in, emit acquire token events
414
+ const loggedInAccounts = this.getAllAccounts();
415
+ this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_START, correlationId, InteractionType.Popup, request);
416
+ let result;
417
+ const pkce = this.getPreGeneratedPkceCodes(correlationId);
418
+ if (this.canUsePlatformBroker(request)) {
419
+ // Cached nativeAccountId routes directly to the broker (no /authorize call)
420
+ atPopupMeasurement.add({
421
+ isPlatformBrokerRequest: true,
422
+ });
423
+ result = this.acquireTokenNative({
424
+ ...request,
425
+ correlationId,
426
+ }, ApiId.acquireTokenPopup)
427
+ .then((response) => {
428
+ atPopupMeasurement.end({
429
+ success: true,
430
+ isNativeBroker: response.fromPlatformBroker ?? false,
431
+ }, undefined, response.account);
432
+ return response;
433
+ })
434
+ .catch((e) => {
435
+ if (e instanceof NativeAuthError &&
436
+ isFatalNativeAuthError(e)) {
437
+ this.platformAuthProvider = undefined; // If extension gets uninstalled during session prevent future requests from continuing to attempt platform broker calls
438
+ const popupClient = this.createPopupClient(correlationId);
439
+ return popupClient.acquireToken(request, pkce);
440
+ }
441
+ else if (e instanceof InteractionRequiredAuthError) {
442
+ this.logger.verbose("0yy5fw", correlationId);
443
+ const popupClient = this.createPopupClient(correlationId);
444
+ return popupClient.acquireToken(request, pkce);
445
+ }
446
+ throw e;
447
+ });
448
+ }
449
+ else {
450
+ const popupClient = this.createPopupClient(correlationId);
451
+ result = popupClient.acquireToken(request, pkce);
452
+ }
453
+ return result
454
+ .then((result) => {
455
+ /*
456
+ * If logged in, emit acquire token events
457
+ */
458
+ const isLoggingIn = loggedInAccounts.length < this.getAllAccounts().length;
459
+ this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_SUCCESS, correlationId, InteractionType.Popup, result);
460
+ if (isLoggingIn) {
461
+ this.eventHandler.emitEvent(EventType.LOGIN_SUCCESS, correlationId, InteractionType.Popup, result.account);
462
+ }
463
+ atPopupMeasurement.end({
464
+ success: true,
465
+ isNativeBroker: result.fromPlatformBroker ?? false,
466
+ accessTokenSize: result.accessToken.length,
467
+ idTokenSize: result.idToken.length,
468
+ }, undefined, result.account);
469
+ // SSO capability verification in background
470
+ this.verifySsoCapability(request, InteractionType.Popup);
471
+ return result;
472
+ })
473
+ .catch((e) => {
474
+ this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, correlationId, InteractionType.Popup, null, e);
475
+ atPopupMeasurement.end({
476
+ success: false,
477
+ }, e, request.account);
478
+ // Since this function is syncronous we need to reject
479
+ return Promise.reject(e);
480
+ })
481
+ .finally(async () => {
482
+ this.browserStorage.setInteractionInProgress(false);
483
+ if (!this.config.system.navigatePopups) {
484
+ await this.preGeneratePkceCodes(correlationId);
485
+ }
486
+ });
487
+ }
488
+ trackStateChangeWithMeasurement(event) {
489
+ const measurement = this.ssoSilentMeasurement ||
490
+ this.acquireTokenByCodeAsyncMeasurement;
491
+ if (!measurement) {
492
+ return;
493
+ }
494
+ if (event.type === "visibilitychange") {
495
+ this.logger.info(`0yzimq ${measurement.event.name}`, measurement.event.correlationId);
496
+ measurement.increment({
497
+ visibilityChangeCount: 1,
498
+ });
499
+ }
500
+ else if (event.type === "online") {
501
+ this.logger.info(`1caf53 ${measurement.event.name}`, measurement.event.correlationId);
502
+ measurement.increment({
503
+ onlineStatusChangeCount: 1,
504
+ });
505
+ }
506
+ else if (event.type === "offline") {
507
+ this.logger.info(`0fdyk7 ${measurement.event.name}`, measurement.event.correlationId);
508
+ measurement.increment({
509
+ onlineStatusChangeCount: 1,
510
+ });
511
+ }
512
+ }
513
+ addStateChangeListeners(listener) {
514
+ document.addEventListener("visibilitychange", listener);
515
+ window.addEventListener("online", listener);
516
+ window.addEventListener("offline", listener);
517
+ }
518
+ removeStateChangeListeners(listener) {
519
+ document.removeEventListener("visibilitychange", listener);
520
+ window.removeEventListener("online", listener);
521
+ window.removeEventListener("offline", listener);
522
+ }
523
+ /**
524
+ * Reads the cached ssoCapable value from localStorage.
525
+ * @returns The cached ssoCapable boolean value, or undefined if not cached or expired.
526
+ */
527
+ getCachedSsoCapable() {
528
+ try {
529
+ const cachedValue = window.localStorage.getItem(SSO_CAPABLE);
530
+ if (cachedValue) {
531
+ const parsed = JSON.parse(cachedValue);
532
+ if (parsed &&
533
+ typeof parsed.ssoCapable === "boolean" &&
534
+ parsed.expiresOn &&
535
+ Date.now() < parsed.expiresOn) {
536
+ return parsed.ssoCapable;
537
+ }
538
+ }
539
+ }
540
+ catch {
541
+ // If parsing fails, return undefined
542
+ }
543
+ return undefined;
544
+ }
545
+ /**
546
+ * SSO capability verification in the background.
547
+ * This method makes an iframe request to /authorize to verify SSO capability without calling /token.
548
+ * This method does not block the caller and tracks telemetry for success/failure.
549
+ * This method only executes if verifySSO is set to true in the auth configuration.
550
+ * The result is cached in localStorage with a 24-hour TTL; the SSO verification call
551
+ * is only attempted when the cached value is absent or expired.
552
+ * @param request - The original request used for the authentication flow
553
+ * @param interactionType - The interactionType of the AT operation for logging purposes
554
+ */
555
+ verifySsoCapability(request, interactionType) {
556
+ // Check if SSO capability verification is enabled
557
+ if (!this.config.auth.verifySSO) {
558
+ return;
559
+ }
560
+ // Check TTL: derive ssoCapable state from localStorage and skip if not expired
561
+ const ssoCacheKey = SSO_CAPABLE;
562
+ const SSO_CAPABLE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
563
+ const cachedSsoCapable = this.getCachedSsoCapable();
564
+ if (cachedSsoCapable !== undefined) {
565
+ this.logger.verbose(`13poou ${interactionType}`, "");
566
+ return;
567
+ }
568
+ const correlationId = createNewGuid();
569
+ const ssoCapableMeasurement = this.performanceClient.startMeasurement(SsoCapable, correlationId);
570
+ ssoCapableMeasurement.add({
571
+ "ext.interactionType": interactionType,
572
+ });
573
+ this.logger.verbose(`0pbr0i ${interactionType}`, correlationId);
574
+ /*
575
+ * Use setTimeout to ensure this runs in a separate macrotask after the current call stack completes
576
+ * This ensures the result is returned to the caller before the SSO verification starts and doesn't affect performance
577
+ */
578
+ setTimeout(() => {
579
+ const ssoVerificationRequest = {
580
+ ...request,
581
+ correlationId: correlationId,
582
+ };
583
+ const silentIframeClient = this.createSilentIframeClient(correlationId);
584
+ silentIframeClient
585
+ .verifySso(ssoVerificationRequest)
586
+ .then((result) => {
587
+ this.logger.verbose(`1gd1iv ${interactionType} ${result}`, correlationId);
588
+ // TBD to add profileTelemetry later in localStorage with 24h TTL
589
+ try {
590
+ const cacheEntry = JSON.stringify({
591
+ ssoCapable: result,
592
+ expiresOn: Date.now() + SSO_CAPABLE_TTL_MS,
593
+ });
594
+ window.localStorage.setItem(ssoCacheKey, cacheEntry);
595
+ }
596
+ catch {
597
+ this.logger.warning(`18lmoj ${interactionType}`, correlationId);
598
+ }
599
+ ssoCapableMeasurement.end({
600
+ fromCache: false,
601
+ success: result,
602
+ }, undefined);
603
+ })
604
+ .catch((error) => {
605
+ this.logger.warning(`05g83w ${interactionType} ${error.message}`, correlationId);
606
+ // reset the cache
607
+ try {
608
+ window.localStorage.removeItem(ssoCacheKey);
609
+ }
610
+ catch {
611
+ this.logger.warning(`0nlf9q ${interactionType}`, correlationId);
612
+ }
613
+ ssoCapableMeasurement.end({
614
+ fromCache: false,
615
+ success: false,
616
+ }, error);
617
+ });
618
+ }, 0);
619
+ }
620
+ // #endregion
621
+ // #region Silent Flow
622
+ /**
623
+ * This function uses a hidden iframe to fetch an authorization code from the eSTS. There are cases where this may not work:
624
+ * - Any browser using a form of Intelligent Tracking Prevention
625
+ * - If there is not an established session with the service
626
+ *
627
+ * In these cases, the request must be done inside a popup or full frame redirect.
628
+ *
629
+ * For the cases where interaction is required, you cannot send a request with prompt=none.
630
+ *
631
+ * If your refresh token has expired, you can use this function to fetch a new set of tokens silently as long as
632
+ * you session on the server still exists.
633
+ * @param request {@link SsoSilentRequest}
634
+ *
635
+ * @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
636
+ */
637
+ async ssoSilent(request) {
638
+ const correlationId = this.getRequestCorrelationId(request);
639
+ const validRequest = {
640
+ ...request,
641
+ correlationId: correlationId,
642
+ };
643
+ this.ssoSilentMeasurement = this.performanceClient.startMeasurement(SsoSilent, correlationId);
644
+ this.ssoSilentMeasurement?.add({
645
+ scenarioId: request.scenarioId,
646
+ ssoCapable: this.getCachedSsoCapable(),
647
+ });
648
+ preflightCheck(this.initialized, this.ssoSilentMeasurement, this.config, validRequest);
649
+ this.ssoSilentMeasurement?.increment({
650
+ visibilityChangeCount: 0,
651
+ onlineStatusChangeCount: 0,
652
+ });
653
+ this.addStateChangeListeners(this.trackStateChangeWithMeasurement);
654
+ const loggedInAccounts = this.getAllAccounts();
655
+ this.logger.verbose("0w1b45", correlationId);
656
+ this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_START, correlationId, InteractionType.Silent, validRequest);
657
+ let result;
658
+ if (this.canUsePlatformBroker(validRequest)) {
659
+ // Cached nativeAccountId routes directly to the broker (no /authorize call)
660
+ this.ssoSilentMeasurement?.add({
661
+ isPlatformBrokerRequest: true,
662
+ });
663
+ result = this.acquireTokenNative(validRequest, ApiId.ssoSilent).catch((e) => {
664
+ // If native token acquisition fails for availability reasons fallback to standard flow
665
+ if (e instanceof NativeAuthError && isFatalNativeAuthError(e)) {
666
+ this.platformAuthProvider = undefined; // If extension gets uninstalled during session prevent future requests from continuing to attempt platform broker calls
667
+ const silentIframeClient = this.createSilentIframeClient(validRequest.correlationId);
668
+ return silentIframeClient.acquireToken(validRequest);
669
+ }
670
+ throw e;
671
+ });
672
+ }
673
+ else {
674
+ const silentIframeClient = this.createSilentIframeClient(validRequest.correlationId);
675
+ result = silentIframeClient.acquireToken(validRequest);
676
+ }
677
+ return result
678
+ .then((response) => {
679
+ const isLoggingIn = loggedInAccounts.length < this.getAllAccounts().length;
680
+ this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_SUCCESS, correlationId, InteractionType.Silent, response);
681
+ if (isLoggingIn) {
682
+ this.eventHandler.emitEvent(EventType.LOGIN_SUCCESS, correlationId, InteractionType.Silent, response.account);
683
+ }
684
+ this.ssoSilentMeasurement?.end({
685
+ success: true,
686
+ isNativeBroker: response.fromPlatformBroker ?? false,
687
+ accessTokenSize: response.accessToken.length,
688
+ idTokenSize: response.idToken.length,
689
+ }, undefined, response.account);
690
+ return response;
691
+ })
692
+ .catch((e) => {
693
+ this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, correlationId, InteractionType.Silent, null, e);
694
+ this.ssoSilentMeasurement?.end({
695
+ success: false,
696
+ }, e, request.account);
697
+ throw e;
698
+ })
699
+ .finally(() => {
700
+ this.removeStateChangeListeners(this.trackStateChangeWithMeasurement);
701
+ });
702
+ }
703
+ /**
704
+ * This function redeems an authorization code (passed as code) from the eSTS token endpoint.
705
+ * This authorization code should be acquired server-side using a confidential client to acquire a spa_code.
706
+ * This API is not indended for normal authorization code acquisition and redemption.
707
+ *
708
+ * Redemption of this authorization code will not require PKCE, as it was acquired by a confidential client.
709
+ *
710
+ * @param request {@link AuthorizationCodeRequest}
711
+ * @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
712
+ */
713
+ async acquireTokenByCode(request) {
714
+ const correlationId = this.getRequestCorrelationId(request);
715
+ this.logger.trace("0ch6ga", correlationId);
716
+ const atbcMeasurement = this.performanceClient.startMeasurement(AcquireTokenByCode, correlationId);
717
+ preflightCheck(this.initialized, atbcMeasurement, this.config, request);
718
+ this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_START, correlationId, InteractionType.Silent, request);
719
+ atbcMeasurement.add({ scenarioId: request.scenarioId });
720
+ try {
721
+ if (request.code && request.nativeAccountId) {
722
+ // Throw error in case server returns both spa_code and spa_accountid in exchange for auth code.
723
+ throw createBrowserAuthError(spaCodeAndNativeAccountIdPresent, correlationId);
724
+ }
725
+ else if (request.code) {
726
+ const hybridAuthCode = request.code;
727
+ let response = this.hybridAuthCodeResponses.get(hybridAuthCode);
728
+ if (!response) {
729
+ this.logger.verbose("06eh73", correlationId);
730
+ response = this.acquireTokenByCodeAsync({
731
+ ...request,
732
+ correlationId,
733
+ })
734
+ .then((result) => {
735
+ this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_SUCCESS, correlationId, InteractionType.Silent, result);
736
+ this.hybridAuthCodeResponses.delete(hybridAuthCode);
737
+ atbcMeasurement.end({
738
+ success: true,
739
+ isNativeBroker: false,
740
+ accessTokenSize: result.accessToken.length,
741
+ idTokenSize: result.idToken.length,
742
+ }, undefined, result.account);
743
+ return result;
744
+ })
745
+ .catch((error) => {
746
+ this.hybridAuthCodeResponses.delete(hybridAuthCode);
747
+ this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, correlationId, InteractionType.Silent, null, error);
748
+ atbcMeasurement.end({
749
+ success: false,
750
+ }, error);
751
+ throw error;
752
+ });
753
+ this.hybridAuthCodeResponses.set(hybridAuthCode, response);
754
+ }
755
+ else {
756
+ this.logger.verbose("0qgp28", correlationId);
757
+ atbcMeasurement.discard();
758
+ }
759
+ return await response;
760
+ }
761
+ else if (request.nativeAccountId) {
762
+ if (this.canUsePlatformBroker(request, request.nativeAccountId)) {
763
+ atbcMeasurement.add({
764
+ isPlatformBrokerRequest: true,
765
+ });
766
+ const result = await this.acquireTokenNative({
767
+ ...request,
768
+ correlationId,
769
+ }, ApiId.acquireTokenByCode, request.nativeAccountId).catch((e) => {
770
+ // If native token acquisition fails for availability reasons fallback to standard flow
771
+ if (e instanceof NativeAuthError &&
772
+ isFatalNativeAuthError(e)) {
773
+ this.platformAuthProvider = undefined; // If extension gets uninstalled during session prevent future requests from continuing to attempt
774
+ }
775
+ throw e;
776
+ });
777
+ atbcMeasurement.end({
778
+ success: true,
779
+ isNativeBroker: result.fromPlatformBroker ?? false,
780
+ }, undefined, result.account);
781
+ return result;
782
+ }
783
+ else {
784
+ throw createBrowserAuthError(unableToAcquireTokenFromNativePlatform, correlationId);
785
+ }
786
+ }
787
+ else {
788
+ throw createBrowserAuthError(authCodeOrNativeAccountIdRequired, correlationId);
789
+ }
790
+ }
791
+ catch (e) {
792
+ this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, correlationId, InteractionType.Silent, null, e);
793
+ atbcMeasurement.end({
794
+ success: false,
795
+ }, e);
796
+ throw e;
797
+ }
798
+ }
799
+ /**
800
+ * Creates a SilentAuthCodeClient to redeem an authorization code.
801
+ * @param request
802
+ * @returns Result of the operation to redeem the authorization code
803
+ */
804
+ async acquireTokenByCodeAsync(request) {
805
+ const correlationId = this.getRequestCorrelationId(request);
806
+ this.logger.trace("10d9hy", correlationId);
807
+ this.acquireTokenByCodeAsyncMeasurement =
808
+ this.performanceClient.startMeasurement(AcquireTokenByCodeAsync, correlationId);
809
+ this.acquireTokenByCodeAsyncMeasurement?.increment({
810
+ visibilityChangeCount: 0,
811
+ onlineStatusChangeCount: 0,
812
+ });
813
+ this.addStateChangeListeners(this.trackStateChangeWithMeasurement);
814
+ const silentAuthCodeClient = this.createSilentAuthCodeClient(correlationId);
815
+ const silentTokenResult = await silentAuthCodeClient
816
+ .acquireToken(request)
817
+ .then((response) => {
818
+ this.acquireTokenByCodeAsyncMeasurement?.end({
819
+ success: true,
820
+ isNativeBroker: false,
821
+ fromCache: response.fromCache,
822
+ });
823
+ return response;
824
+ })
825
+ .catch((tokenRenewalError) => {
826
+ this.acquireTokenByCodeAsyncMeasurement?.end({
827
+ success: false,
828
+ }, tokenRenewalError);
829
+ throw tokenRenewalError;
830
+ })
831
+ .finally(() => {
832
+ this.removeStateChangeListeners(this.trackStateChangeWithMeasurement);
833
+ });
834
+ return silentTokenResult;
835
+ }
836
+ /**
837
+ * Attempt to acquire an access token from the cache
838
+ * @param silentCacheClient SilentCacheClient
839
+ * @param commonRequest CommonSilentFlowRequest
840
+ * @param silentRequest SilentRequest
841
+ * @returns A promise that, when resolved, returns the access token
842
+ */
843
+ async acquireTokenFromCache(commonRequest, cacheLookupPolicy) {
844
+ switch (cacheLookupPolicy) {
845
+ case CacheLookupPolicy.Default:
846
+ case CacheLookupPolicy.AccessToken:
847
+ case CacheLookupPolicy.AccessTokenAndRefreshToken:
848
+ const silentCacheClient = this.createSilentCacheClient(commonRequest.correlationId);
849
+ return invokeAsync(silentCacheClient.acquireToken.bind(silentCacheClient), SilentCacheClientAcquireToken, this.logger, this.performanceClient, commonRequest.correlationId)(commonRequest);
850
+ default:
851
+ throw createClientAuthError(ClientAuthErrorCodes.tokenRefreshRequired, commonRequest.correlationId);
852
+ }
853
+ }
854
+ /**
855
+ * Attempt to acquire an access token via a refresh token
856
+ * @param commonRequest CommonSilentFlowRequest
857
+ * @param cacheLookupPolicy CacheLookupPolicy
858
+ * @returns A promise that, when resolved, returns the access token
859
+ */
860
+ async acquireTokenByRefreshToken(commonRequest, cacheLookupPolicy) {
861
+ switch (cacheLookupPolicy) {
862
+ case CacheLookupPolicy.Default:
863
+ case CacheLookupPolicy.AccessTokenAndRefreshToken:
864
+ case CacheLookupPolicy.RefreshToken:
865
+ case CacheLookupPolicy.RefreshTokenAndNetwork:
866
+ const silentRefreshClient = this.createSilentRefreshClient(commonRequest.correlationId);
867
+ return invokeAsync(silentRefreshClient.acquireToken.bind(silentRefreshClient), SilentRefreshClientAcquireToken, this.logger, this.performanceClient, commonRequest.correlationId)(commonRequest);
868
+ default:
869
+ throw createClientAuthError(ClientAuthErrorCodes.tokenRefreshRequired, commonRequest.correlationId);
870
+ }
871
+ }
872
+ /**
873
+ * Attempt to acquire an access token via an iframe
874
+ * @param request CommonSilentFlowRequest
875
+ * @returns A promise that, when resolved, returns the access token
876
+ */
877
+ async acquireTokenBySilentIframe(request) {
878
+ const silentIframeClient = this.createSilentIframeClient(request.correlationId);
879
+ return invokeAsync(silentIframeClient.acquireToken.bind(silentIframeClient), SilentIframeClientAcquireToken, this.logger, this.performanceClient, request.correlationId)(request);
880
+ }
881
+ // #endregion
882
+ // #region Logout
883
+ /**
884
+ * Use to log out the current user, and redirect the user to the postLogoutRedirectUri.
885
+ * Default behaviour is to redirect the user to `window.location.href`.
886
+ * @param logoutRequest
887
+ */
888
+ async logoutRedirect(logoutRequest) {
889
+ const correlationId = this.getRequestCorrelationId(logoutRequest);
890
+ redirectPreflightCheck(this.initialized, this.config);
891
+ this.browserStorage.setInteractionInProgress(true, INTERACTION_TYPE.SIGNOUT);
892
+ const redirectClient = this.createRedirectClient(correlationId);
893
+ return redirectClient.logout(logoutRequest);
894
+ }
895
+ /**
896
+ * Clears local cache for the current user then opens a popup window prompting the user to sign-out of the server
897
+ * @param logoutRequest
898
+ */
899
+ logoutPopup(logoutRequest) {
900
+ try {
901
+ const correlationId = this.getRequestCorrelationId(logoutRequest);
902
+ preflightCheck$1(this.initialized);
903
+ this.browserStorage.setInteractionInProgress(true, INTERACTION_TYPE.SIGNOUT);
904
+ const popupClient = this.createPopupClient(correlationId);
905
+ return popupClient.logout(logoutRequest).finally(() => {
906
+ this.browserStorage.setInteractionInProgress(false);
907
+ });
908
+ }
909
+ catch (e) {
910
+ // Since this function is syncronous we need to reject
911
+ return Promise.reject(e);
912
+ }
913
+ }
914
+ /**
915
+ * Creates a cache interaction client to clear broswer cache.
916
+ * @param logoutRequest
917
+ */
918
+ async clearCache(logoutRequest) {
919
+ if (!this.isBrowserEnvironment) {
920
+ return;
921
+ }
922
+ const correlationId = this.getRequestCorrelationId(logoutRequest);
923
+ const cacheClient = this.createSilentCacheClient(correlationId);
924
+ return cacheClient.logout(logoutRequest);
925
+ }
926
+ // #endregion
927
+ // #region Account APIs
928
+ /**
929
+ * Returns all the accounts in the cache that match the optional filter. If no filter is provided, all accounts are returned.
930
+ * @param accountFilter - (Optional) filter to narrow down the accounts returned
931
+ * @returns Array of AccountInfo objects in cache
932
+ */
933
+ getAllAccounts(accountFilter) {
934
+ return getAllAccounts(this.logger, this.browserStorage, this.isBrowserEnvironment, this.getRequestCorrelationId(), accountFilter);
935
+ }
936
+ /**
937
+ * Returns the first account found in the cache that matches the account filter passed in.
938
+ * @param accountFilter
939
+ * @returns The first account found in the cache matching the provided filter or null if no account could be found.
940
+ */
941
+ getAccount(accountFilter) {
942
+ return getAccount(accountFilter, this.logger, this.browserStorage, this.getRequestCorrelationId());
943
+ }
944
+ /**
945
+ * Sets the account to use as the active account. If no account is passed to the acquireToken APIs, then MSAL will use this active account.
946
+ * @param account
947
+ */
948
+ setActiveAccount(account) {
949
+ setActiveAccount(account, this.browserStorage, this.getRequestCorrelationId());
950
+ }
951
+ /**
952
+ * Gets the currently active account
953
+ */
954
+ getActiveAccount() {
955
+ return getActiveAccount(this.browserStorage, this.getRequestCorrelationId());
956
+ }
957
+ // #endregion
958
+ /**
959
+ * Hydrates the cache with the tokens from an AuthenticationResult
960
+ * @param result
961
+ * @param request
962
+ * @returns
963
+ */
964
+ async hydrateCache(result, request) {
965
+ this.logger.verbose("16jycr", result.correlationId);
966
+ // Account gets saved to browser storage regardless of native or not
967
+ const accountEntity = AccountEntityUtils.createAccountEntityFromAccountInfo(result.account, result.cloudGraphHostName, result.msGraphHost);
968
+ await this.browserStorage.setAccount(accountEntity, result.correlationId, AuthToken.isKmsi(result.idTokenClaims), ApiId.hydrateCache);
969
+ if (result.fromPlatformBroker) {
970
+ this.logger.verbose("1i5atf", result.correlationId);
971
+ // Create idToken entity and store in browser storage
972
+ const idTokenEntity = CacheHelpers.createIdTokenEntity(result.account.homeAccountId, result.account.environment, result.idToken, this.config.auth.clientId, result.tenantId);
973
+ // Create accessToken entity and store in native internal storage
974
+ const attributeTokenPartition = CacheHelpers.serializeAttributeTokens(request.attributeTokens);
975
+ const additionalCacheKeyComponents = attributeTokenPartition
976
+ ? {
977
+ attribute_tokens: attributeTokenPartition,
978
+ }
979
+ : undefined;
980
+ const accessTokenEntity = CacheHelpers.createAccessTokenEntity(result.account.homeAccountId, result.account.environment, result.accessToken, this.config.auth.clientId, result.tenantId, result.scopes.join(" "), result.expiresOn
981
+ ? TimeUtils.toSecondsFromDate(result.expiresOn)
982
+ : 0, result.extExpiresOn
983
+ ? TimeUtils.toSecondsFromDate(result.extExpiresOn)
984
+ : 0, base64Decode, request.correlationId || "", undefined, // refreshOn
985
+ result.tokenType, undefined, // userAssertionHash
986
+ request.sshKid, additionalCacheKeyComponents);
987
+ if (request.resource) {
988
+ accessTokenEntity.resource = request.resource;
989
+ }
990
+ // Get attribute token partition hash for cache key isolation
991
+ const components = additionalCacheKeyComponents;
992
+ const additionalCacheKeyHash = components
993
+ ? await this.browserCrypto.hashString(JSON.stringify(components))
994
+ : undefined;
995
+ const kmsi = AuthToken.isKmsi(result.idTokenClaims);
996
+ // Store idToken in browser storage
997
+ await this.browserStorage.setIdTokenCredential(idTokenEntity, result.correlationId, kmsi);
998
+ // Store accessToken in native internal storage
999
+ await this.nativeInternalStorage.setAccessTokenCredential(accessTokenEntity, result.correlationId, kmsi, additionalCacheKeyHash);
1000
+ }
1001
+ else {
1002
+ return this.browserStorage.hydrateCache(result, request);
1003
+ }
1004
+ }
1005
+ // #region Helpers
1006
+ /**
1007
+ * Acquire a token from native device (e.g. WAM)
1008
+ * @param request
1009
+ * @param apiId
1010
+ * @param accountId
1011
+ * @param cacheLookupPolicy
1012
+ */
1013
+ async acquireTokenNative(request, apiId, accountId, cacheLookupPolicy) {
1014
+ /*
1015
+ * Callers always normalize correlationId onto the request before delegating
1016
+ * here, so it is guaranteed defined and is the single id used to key this
1017
+ * flow's telemetry.
1018
+ */
1019
+ const correlationId = this.getRequestCorrelationId(request);
1020
+ this.logger.trace("0b9y3p", correlationId);
1021
+ if (!this.platformAuthProvider) {
1022
+ throw createBrowserAuthError(nativeConnectionNotEstablished, correlationId);
1023
+ }
1024
+ const nativeClient = new PlatformAuthInteractionClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, apiId, this.performanceClient, this.platformAuthProvider, accountId || this.getNativeAccountId(request), this.nativeInternalStorage, correlationId, this.tokenBindingKeyManager);
1025
+ return invokeAsync(nativeClient.acquireToken.bind(nativeClient), NativeInteractionClientAcquireToken, this.logger, this.performanceClient, correlationId)(request, cacheLookupPolicy);
1026
+ }
1027
+ /**
1028
+ * Returns boolean indicating if this request can use the platform broker
1029
+ * @param request
1030
+ */
1031
+ canUsePlatformBroker(request, accountId) {
1032
+ const correlationId = this.getRequestCorrelationId(request);
1033
+ this.logger.trace("1n9lbl", correlationId);
1034
+ if (!this.platformAuthProvider) {
1035
+ this.logger.trace("0vnu11", correlationId);
1036
+ return false;
1037
+ }
1038
+ if (!isPlatformAuthAllowed(this.config, this.logger, correlationId, this.platformAuthProvider, request.authenticationScheme)) {
1039
+ this.logger.trace("0yoy1g", correlationId);
1040
+ return false;
1041
+ }
1042
+ if (request.prompt) {
1043
+ switch (request.prompt) {
1044
+ case Constants.PromptValue.NONE:
1045
+ case Constants.PromptValue.CONSENT:
1046
+ case Constants.PromptValue.LOGIN:
1047
+ this.logger.trace("0vdv8e", correlationId);
1048
+ break;
1049
+ default:
1050
+ this.logger.trace(`0pdzw6 ${request.prompt}`, correlationId);
1051
+ return false;
1052
+ }
1053
+ }
1054
+ if (!accountId && !this.getNativeAccountId(request)) {
1055
+ this.logger.trace("16lbtk", correlationId);
1056
+ return false;
1057
+ }
1058
+ return true;
1059
+ }
1060
+ /**
1061
+ * Get the native accountId from the account
1062
+ * @param request
1063
+ * @returns
1064
+ */
1065
+ getNativeAccountId(request) {
1066
+ const account = request.account ||
1067
+ this.getAccount({
1068
+ loginHint: request.loginHint,
1069
+ sid: request.sid,
1070
+ }) ||
1071
+ (!request.loginHint && !request.sid
1072
+ ? this.getActiveAccount()
1073
+ : null);
1074
+ return (account && account.nativeAccountId) || "";
1075
+ }
1076
+ /**
1077
+ * Returns new instance of the Popup Interaction Client
1078
+ * @param correlationId
1079
+ */
1080
+ createPopupClient(correlationId) {
1081
+ return new PopupClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, this.performanceClient, this.nativeInternalStorage, correlationId, this.platformAuthProvider, this.operatingContext.getResponseHandlers()?.waitForPopupResponse, this.tokenBindingKeyManager);
1082
+ }
1083
+ /**
1084
+ * Returns new instance of the Redirect Interaction Client
1085
+ * @param correlationId
1086
+ */
1087
+ createRedirectClient(correlationId) {
1088
+ return new RedirectClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, this.performanceClient, this.nativeInternalStorage, correlationId, this.platformAuthProvider, this.tokenBindingKeyManager);
1089
+ }
1090
+ /**
1091
+ * Returns new instance of the Silent Iframe Interaction Client
1092
+ * @param correlationId
1093
+ */
1094
+ createSilentIframeClient(correlationId) {
1095
+ return new SilentIframeClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, ApiId.ssoSilent, this.performanceClient, this.nativeInternalStorage, correlationId, this.platformAuthProvider, this.operatingContext.getResponseHandlers()?.waitForIframeResponse, this.tokenBindingKeyManager);
1096
+ }
1097
+ /**
1098
+ * Returns new instance of the Silent Cache Interaction Client
1099
+ */
1100
+ createSilentCacheClient(correlationId) {
1101
+ return new SilentCacheClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, this.performanceClient, correlationId, this.platformAuthProvider, this.tokenBindingKeyManager);
1102
+ }
1103
+ /**
1104
+ * Returns new instance of the Silent Refresh Interaction Client
1105
+ */
1106
+ createSilentRefreshClient(correlationId) {
1107
+ return new SilentRefreshClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, this.performanceClient, correlationId, this.platformAuthProvider, this.tokenBindingKeyManager);
1108
+ }
1109
+ /**
1110
+ * Returns new instance of the Silent AuthCode Interaction Client
1111
+ */
1112
+ createSilentAuthCodeClient(correlationId) {
1113
+ return new SilentAuthCodeClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, ApiId.acquireTokenByCode, this.performanceClient, correlationId, this.platformAuthProvider, this.tokenBindingKeyManager);
1114
+ }
1115
+ /**
1116
+ * Adds event callbacks to array
1117
+ * @param callback
1118
+ */
1119
+ addEventCallback(callback, eventTypes) {
1120
+ return this.eventHandler.addEventCallback(callback, eventTypes);
1121
+ }
1122
+ /**
1123
+ * Removes callback with provided id from callback array
1124
+ * @param callbackId
1125
+ */
1126
+ removeEventCallback(callbackId) {
1127
+ this.eventHandler.removeEventCallback(callbackId);
1128
+ }
1129
+ /**
1130
+ * Registers a callback to receive performance events.
1131
+ *
1132
+ * @param {PerformanceCallbackFunction} callback
1133
+ * @returns {string}
1134
+ */
1135
+ addPerformanceCallback(callback) {
1136
+ blockNonBrowserEnvironment();
1137
+ return this.performanceClient.addPerformanceCallback(callback);
1138
+ }
1139
+ /**
1140
+ * Removes a callback registered with addPerformanceCallback.
1141
+ *
1142
+ * @param {string} callbackId
1143
+ * @returns {boolean}
1144
+ */
1145
+ removePerformanceCallback(callbackId) {
1146
+ return this.performanceClient.removePerformanceCallback(callbackId);
1147
+ }
1148
+ /**
1149
+ * Returns the logger instance
1150
+ */
1151
+ getLogger() {
1152
+ return this.logger;
1153
+ }
1154
+ /**
1155
+ * Replaces the default logger set in configurations with new Logger with new configurations
1156
+ * @param logger Logger instance
1157
+ */
1158
+ setLogger(logger) {
1159
+ this.logger = logger;
1160
+ }
1161
+ /**
1162
+ * Called by wrapper libraries (Angular & React) to set SKU and Version passed down to telemetry, logger, etc.
1163
+ * @param sku
1164
+ * @param version
1165
+ */
1166
+ initializeWrapperLibrary(sku, version) {
1167
+ // Validate the SKU passed in is one we expect
1168
+ this.browserStorage.setWrapperMetadata(sku, version);
1169
+ }
1170
+ /**
1171
+ * Sets navigation client
1172
+ * @param navigationClient
1173
+ */
1174
+ setNavigationClient(navigationClient) {
1175
+ this.navigationClient = navigationClient;
1176
+ }
1177
+ /**
1178
+ * Returns the configuration object
1179
+ */
1180
+ getConfiguration() {
1181
+ return this.config;
1182
+ }
1183
+ /**
1184
+ * Returns the performance client
1185
+ */
1186
+ getPerformanceClient() {
1187
+ return this.performanceClient;
1188
+ }
1189
+ /**
1190
+ * Returns the browser env indicator
1191
+ */
1192
+ isBrowserEnv() {
1193
+ return this.isBrowserEnvironment;
1194
+ }
1195
+ /**
1196
+ * Generates a correlation id for a request if none is provided.
1197
+ *
1198
+ * @protected
1199
+ * @param {?Partial<BaseAuthRequest>} [request]
1200
+ * @returns {string}
1201
+ */
1202
+ getRequestCorrelationId(request) {
1203
+ if (request?.correlationId) {
1204
+ return request.correlationId;
1205
+ }
1206
+ if (this.isBrowserEnvironment) {
1207
+ return createNewGuid();
1208
+ }
1209
+ /*
1210
+ * Included for fallback for non-browser environments,
1211
+ * and to ensure this method always returns a string.
1212
+ */
1213
+ return "";
1214
+ }
1215
+ // #endregion
1216
+ /**
1217
+ * Use when initiating the login process by redirecting the user's browser to the authorization endpoint. This function redirects the page, so
1218
+ * any code that follows this function will not execute.
1219
+ *
1220
+ * IMPORTANT: It is NOT recommended to have code that is dependent on the resolution of the Promise. This function will navigate away from the current
1221
+ * browser window. It currently returns a Promise in order to reflect the asynchronous nature of the code running in this function.
1222
+ *
1223
+ * @param request
1224
+ */
1225
+ async loginRedirect(request) {
1226
+ const correlationId = this.getRequestCorrelationId(request);
1227
+ this.logger.verbose("0lz9hf", correlationId);
1228
+ return this.acquireTokenRedirect({
1229
+ correlationId,
1230
+ ...(request || DEFAULT_REQUEST),
1231
+ });
1232
+ }
1233
+ /**
1234
+ * Use when initiating the login process via opening a popup window in the user's browser
1235
+ *
1236
+ * @param request
1237
+ *
1238
+ * @returns A promise that is fulfilled when this function has completed, or rejected if an error was raised.
1239
+ */
1240
+ loginPopup(request) {
1241
+ const correlationId = this.getRequestCorrelationId(request);
1242
+ this.logger.verbose("0qw7v5", correlationId);
1243
+ return this.acquireTokenPopup({
1244
+ correlationId,
1245
+ ...(request || DEFAULT_REQUEST),
1246
+ });
1247
+ }
1248
+ /**
1249
+ * Silently acquire an access token for a given set of scopes. Returns currently processing promise if parallel requests are made.
1250
+ *
1251
+ * @param {@link (SilentRequest:type)}
1252
+ * @returns {Promise.<AuthenticationResult>} - a promise that is fulfilled when this function has completed, or rejected if an error was raised. Returns the {@link AuthResponse} object
1253
+ */
1254
+ async acquireTokenSilent(request) {
1255
+ const correlationId = this.getRequestCorrelationId(request);
1256
+ const atsMeasurement = this.performanceClient.startMeasurement(AcquireTokenSilent, correlationId);
1257
+ atsMeasurement.add({
1258
+ cacheLookupPolicy: request.cacheLookupPolicy,
1259
+ scenarioId: request.scenarioId,
1260
+ ssoCapable: this.getCachedSsoCapable(),
1261
+ });
1262
+ preflightCheck(this.initialized, atsMeasurement, this.config, request);
1263
+ this.logger.verbose("0x1c4s", correlationId);
1264
+ const account = request.account || this.getActiveAccount();
1265
+ if (!account) {
1266
+ throw createBrowserAuthError(noAccountError, correlationId);
1267
+ }
1268
+ return this.acquireTokenSilentDeduped(request, account, correlationId)
1269
+ .then((result) => {
1270
+ atsMeasurement.end({
1271
+ success: true,
1272
+ isNativeBroker: result.fromPlatformBroker ?? false,
1273
+ fromCache: result.fromCache,
1274
+ accessTokenSize: result.accessToken.length,
1275
+ idTokenSize: result.idToken.length,
1276
+ }, undefined, result.account);
1277
+ return {
1278
+ ...result,
1279
+ state: request.state,
1280
+ correlationId: correlationId, // Ensures PWB scenarios can correctly match request to response
1281
+ };
1282
+ })
1283
+ .catch((error) => {
1284
+ if (error instanceof AuthError) {
1285
+ // Ensures PWB scenarios can correctly match request to response
1286
+ error.correlationId = correlationId;
1287
+ }
1288
+ atsMeasurement.end({
1289
+ success: false,
1290
+ }, error, account);
1291
+ throw error;
1292
+ });
1293
+ }
1294
+ /**
1295
+ * Checks if identical request is already in flight and returns reference to the existing promise or fires off a new one if this is the first
1296
+ * @param request
1297
+ * @param account
1298
+ * @param correlationId
1299
+ * @returns
1300
+ */
1301
+ async acquireTokenSilentDeduped(request, account, correlationId) {
1302
+ const thumbprint = getRequestThumbprint(this.config.auth.clientId, {
1303
+ ...request,
1304
+ authority: request.authority || this.config.auth.authority,
1305
+ correlationId: correlationId,
1306
+ }, account.homeAccountId);
1307
+ const silentRequestKey = JSON.stringify(thumbprint);
1308
+ const inProgressRequest = this.activeSilentTokenRequests.get(silentRequestKey);
1309
+ if (typeof inProgressRequest === "undefined") {
1310
+ this.logger.verbose("0fcjbk", correlationId);
1311
+ this.performanceClient.addFields({ deduped: false }, correlationId);
1312
+ const activeRequest = invokeAsync(this.acquireTokenSilentAsync.bind(this), AcquireTokenSilentAsync, this.logger, this.performanceClient, correlationId)({
1313
+ ...request,
1314
+ correlationId,
1315
+ }, account);
1316
+ this.activeSilentTokenRequests.set(silentRequestKey, activeRequest);
1317
+ return activeRequest.finally(() => {
1318
+ this.activeSilentTokenRequests.delete(silentRequestKey);
1319
+ });
1320
+ }
1321
+ else {
1322
+ this.logger.verbose("1yq7nb", correlationId);
1323
+ this.performanceClient.addFields({ deduped: true }, correlationId);
1324
+ return inProgressRequest;
1325
+ }
1326
+ }
1327
+ /**
1328
+ * Silently acquire an access token for a given set of scopes. Will use cached token if available, otherwise will attempt to acquire a new token from the network via refresh token.
1329
+ * @param {@link (SilentRequest:type)}
1330
+ * @param {@link (AccountInfo:type)}
1331
+ * @returns {Promise.<AuthenticationResult>} - a promise that is fulfilled when this function has completed, or rejected if an error was raised. Returns the {@link AuthResponse}
1332
+ */
1333
+ async acquireTokenSilentAsync(request, account) {
1334
+ const trackStateChange = (event) => this.trackStateChange(request.correlationId, event);
1335
+ this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_START, request.correlationId, InteractionType.Silent, request);
1336
+ if (request.correlationId) {
1337
+ this.performanceClient.incrementFields({ visibilityChangeCount: 0, onlineStatusChangeCount: 0 }, request.correlationId);
1338
+ }
1339
+ this.addStateChangeListeners(trackStateChange);
1340
+ const silentRequest = await invokeAsync(initializeSilentRequest, InitializeSilentRequest, this.logger, this.performanceClient, request.correlationId)(request, account, this.config, this.performanceClient, this.logger);
1341
+ const cacheLookupPolicy = request.cacheLookupPolicy || CacheLookupPolicy.Default;
1342
+ const result = this.acquireTokenSilentNoIframe(silentRequest, cacheLookupPolicy).catch(async (refreshTokenError) => {
1343
+ const shouldTryToResolveSilently = checkIfRefreshTokenErrorCanBeResolvedSilently(refreshTokenError, cacheLookupPolicy);
1344
+ if (shouldTryToResolveSilently) {
1345
+ const silentRefreshReason = `${refreshTokenError.errorCode}${refreshTokenError.subError
1346
+ ? `|${refreshTokenError.subError}`
1347
+ : ""}`;
1348
+ this.performanceClient.addFields({ silentRefreshReason }, request.correlationId);
1349
+ if (!this.activeIframeRequest) {
1350
+ let _resolve;
1351
+ // Always set the active request tracker immediately after checking it to prevent races
1352
+ this.activeIframeRequest = [
1353
+ new Promise((resolve) => {
1354
+ _resolve = resolve;
1355
+ }),
1356
+ silentRequest.correlationId,
1357
+ ];
1358
+ this.logger.verbose("0rh08z", silentRequest.correlationId);
1359
+ return invokeAsync(this.acquireTokenBySilentIframe.bind(this), AcquireTokenBySilentIframe, this.logger, this.performanceClient, silentRequest.correlationId)(silentRequest)
1360
+ .then((iframeResult) => {
1361
+ _resolve(true);
1362
+ return iframeResult;
1363
+ })
1364
+ .catch((e) => {
1365
+ _resolve(false);
1366
+ throw e;
1367
+ })
1368
+ .finally(() => {
1369
+ this.activeIframeRequest = undefined;
1370
+ });
1371
+ }
1372
+ else if (cacheLookupPolicy !== CacheLookupPolicy.Skip) {
1373
+ const [activePromise, activeCorrelationId] = this.activeIframeRequest;
1374
+ this.logger.verbose(`1w8fso ${activeCorrelationId}`, silentRequest.correlationId);
1375
+ const awaitConcurrentIframeMeasure = this.performanceClient.startMeasurement(AwaitConcurrentIframe, silentRequest.correlationId);
1376
+ awaitConcurrentIframeMeasure.add({
1377
+ awaitIframeCorrelationId: activeCorrelationId,
1378
+ });
1379
+ const activePromiseResult = await activePromise;
1380
+ awaitConcurrentIframeMeasure.end({
1381
+ success: activePromiseResult,
1382
+ });
1383
+ if (activePromiseResult) {
1384
+ this.logger.verbose(`0ywzzi ${activeCorrelationId}`, silentRequest.correlationId);
1385
+ // Retry cache lookup and/or RT exchange after iframe completes
1386
+ return this.acquireTokenSilentNoIframe(silentRequest, cacheLookupPolicy);
1387
+ }
1388
+ else {
1389
+ this.logger.info(`17y14q ${activeCorrelationId}`, silentRequest.correlationId);
1390
+ // If previous iframe request failed, it's unlikely to succeed this time. Throw original error.
1391
+ throw refreshTokenError;
1392
+ }
1393
+ }
1394
+ else {
1395
+ // Cache policy set to skip and another iframe request is already in progress
1396
+ this.logger.warning("1bd4p8", silentRequest.correlationId);
1397
+ return invokeAsync(this.acquireTokenBySilentIframe.bind(this), AcquireTokenBySilentIframe, this.logger, this.performanceClient, silentRequest.correlationId)(silentRequest);
1398
+ }
1399
+ }
1400
+ else {
1401
+ // Error cannot be silently resolved or iframe renewal is not allowed, interaction required
1402
+ throw refreshTokenError;
1403
+ }
1404
+ });
1405
+ return result
1406
+ .then((response) => {
1407
+ this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_SUCCESS, request.correlationId, InteractionType.Silent, response);
1408
+ if (request.correlationId) {
1409
+ this.performanceClient.addFields({
1410
+ fromCache: response.fromCache,
1411
+ isNativeBroker: response.fromPlatformBroker ?? false,
1412
+ }, request.correlationId);
1413
+ }
1414
+ return response;
1415
+ })
1416
+ .catch((tokenRenewalError) => {
1417
+ this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_FAILURE, request.correlationId, InteractionType.Silent, null, tokenRenewalError);
1418
+ throw tokenRenewalError;
1419
+ })
1420
+ .finally(() => {
1421
+ this.removeStateChangeListeners(trackStateChange);
1422
+ });
1423
+ }
1424
+ /**
1425
+ * AcquireTokenSilent without the iframe fallback. This is used to enable the correct fallbacks in cases where there's a potential for multiple silent requests to be made in parallel and prevent those requests from making concurrent iframe requests.
1426
+ * @param silentRequest
1427
+ * @param cacheLookupPolicy
1428
+ * @returns
1429
+ */
1430
+ async acquireTokenSilentNoIframe(silentRequest, cacheLookupPolicy) {
1431
+ // if the cache policy is set to access_token only, we should not be hitting the native layer yet
1432
+ if (isPlatformAuthAllowed(this.config, this.logger, silentRequest.correlationId, this.platformAuthProvider, silentRequest.authenticationScheme) &&
1433
+ silentRequest.account.nativeAccountId) {
1434
+ this.logger.verbose("0sczo4", silentRequest.correlationId);
1435
+ this.performanceClient.addFields({ isPlatformBrokerRequest: true }, silentRequest.correlationId);
1436
+ return this.acquireTokenNative(silentRequest, ApiId.acquireTokenSilent_silentFlow, silentRequest.account.nativeAccountId, cacheLookupPolicy).catch(async (e) => {
1437
+ // If native token acquisition fails for availability reasons fallback to web flow
1438
+ if (e instanceof NativeAuthError && isFatalNativeAuthError(e)) {
1439
+ this.logger.verbose("07rkmb", silentRequest.correlationId);
1440
+ this.platformAuthProvider = undefined; // Prevent future requests from continuing to attempt
1441
+ // Cache will not contain tokens, given that previous WAM requests succeeded. Skip cache and RT renewal and go straight to iframe renewal
1442
+ throw createClientAuthError(ClientAuthErrorCodes.tokenRefreshRequired, silentRequest.correlationId);
1443
+ }
1444
+ throw e;
1445
+ });
1446
+ }
1447
+ else {
1448
+ this.logger.verbose("0ox81t", silentRequest.correlationId);
1449
+ // add logs to identify embedded cache retrieval
1450
+ if (cacheLookupPolicy === CacheLookupPolicy.AccessToken) {
1451
+ this.logger.verbose("0fvwxe", silentRequest.correlationId);
1452
+ }
1453
+ return invokeAsync(this.acquireTokenFromCache.bind(this), AcquireTokenFromCache, this.logger, this.performanceClient, silentRequest.correlationId)(silentRequest, cacheLookupPolicy).catch((cacheError) => {
1454
+ if (cacheLookupPolicy === CacheLookupPolicy.AccessToken) {
1455
+ throw cacheError;
1456
+ }
1457
+ this.eventHandler.emitEvent(EventType.ACQUIRE_TOKEN_NETWORK_START, silentRequest.correlationId, InteractionType.Silent, silentRequest);
1458
+ return invokeAsync(this.acquireTokenByRefreshToken.bind(this), AcquireTokenByRefreshToken, this.logger, this.performanceClient, silentRequest.correlationId)(silentRequest, cacheLookupPolicy);
1459
+ });
1460
+ }
1461
+ }
1462
+ /**
1463
+ * Pre-generates PKCE codes and stores it in local variable
1464
+ * @param correlationId
1465
+ */
1466
+ async preGeneratePkceCodes(correlationId) {
1467
+ this.logger.verbose("1x6uj6", correlationId);
1468
+ this.pkceCode = await invokeAsync(generatePkceCodes, GeneratePkceCodes, this.logger, this.performanceClient, correlationId)(this.performanceClient, this.logger, correlationId);
1469
+ return Promise.resolve();
1470
+ }
1471
+ /**
1472
+ * Provides pre-generated PKCE codes, if any
1473
+ * @param correlationId
1474
+ */
1475
+ getPreGeneratedPkceCodes(correlationId) {
1476
+ const res = this.pkceCode ? { ...this.pkceCode } : undefined;
1477
+ this.pkceCode = undefined;
1478
+ if (res) {
1479
+ this.logger.verbose("12js1o", correlationId);
1480
+ }
1481
+ else {
1482
+ this.logger.verbose("1oe9ci", correlationId);
1483
+ }
1484
+ this.performanceClient.addFields({ usePreGeneratedPkce: !!res }, correlationId);
1485
+ return res;
1486
+ }
1487
+ logMultipleInstances(performanceEvent, correlationId) {
1488
+ const clientId = this.config.auth.clientId;
1489
+ if (!window)
1490
+ return;
1491
+ // @ts-ignore
1492
+ window.msal = window.msal || {};
1493
+ // @ts-ignore
1494
+ window.msal.clientIds = window.msal.clientIds || [];
1495
+ // @ts-ignore
1496
+ const clientIds = window.msal.clientIds;
1497
+ if (clientIds.length > 0) {
1498
+ this.logger.verbose("1qtz3l", correlationId);
1499
+ }
1500
+ // @ts-ignore
1501
+ window.msal.clientIds.push(clientId);
1502
+ collectInstanceStats(clientId, performanceEvent, this.logger, correlationId);
1503
+ }
1504
+ }
1505
+ /**
1506
+ * Determines whether an error thrown by the refresh token endpoint can be resolved without interaction
1507
+ * @param refreshTokenError
1508
+ * @param silentRequest
1509
+ * @param cacheLookupPolicy
1510
+ * @returns
1511
+ */
1512
+ function checkIfRefreshTokenErrorCanBeResolvedSilently(refreshTokenError, cacheLookupPolicy) {
1513
+ const noInteractionRequired = !(refreshTokenError instanceof InteractionRequiredAuthError &&
1514
+ // For refresh token errors, bad_token does not always require interaction (silently resolvable)
1515
+ refreshTokenError.subError !==
1516
+ InteractionRequiredAuthErrorCodes.badToken);
1517
+ // Errors that result when the refresh token needs to be replaced
1518
+ const refreshTokenRefreshRequired = refreshTokenError.errorCode === BrowserConstants.INVALID_GRANT_ERROR ||
1519
+ refreshTokenError.errorCode ===
1520
+ ClientAuthErrorCodes.tokenRefreshRequired;
1521
+ // Errors that may be resolved before falling back to interaction (through iframe renewal)
1522
+ const isSilentlyResolvable = (noInteractionRequired && refreshTokenRefreshRequired) ||
1523
+ refreshTokenError.errorCode ===
1524
+ InteractionRequiredAuthErrorCodes.noTokensFound ||
1525
+ refreshTokenError.errorCode ===
1526
+ InteractionRequiredAuthErrorCodes.refreshTokenExpired;
1527
+ // Only these policies allow for an iframe renewal attempt
1528
+ const tryIframeRenewal = iFrameRenewalPolicies.includes(cacheLookupPolicy);
1529
+ return isSilentlyResolvable && tryIframeRenewal;
1530
+ }
1531
+
1532
+ export { StandardController };