daftari 3.13.1 → 3.15.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 (278) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/dist/consolidate/index.d.ts.map +1 -1
  3. package/dist/consolidate/index.js +3 -12
  4. package/dist/consolidate/index.js.map +1 -1
  5. package/dist/distill/cli.d.ts.map +1 -1
  6. package/dist/distill/cli.js +2 -1
  7. package/dist/distill/cli.js.map +1 -1
  8. package/dist/distill/cost.d.ts +3 -3
  9. package/dist/distill/cost.d.ts.map +1 -1
  10. package/dist/distill/index.d.ts.map +1 -1
  11. package/dist/distill/index.js +3 -15
  12. package/dist/distill/index.js.map +1 -1
  13. package/dist/distill/propose.d.ts.map +1 -1
  14. package/dist/distill/propose.js +10 -3
  15. package/dist/distill/propose.js.map +1 -1
  16. package/dist/distill/state.d.ts +12 -0
  17. package/dist/distill/state.d.ts.map +1 -1
  18. package/dist/distill/state.js +16 -6
  19. package/dist/distill/state.js.map +1 -1
  20. package/dist/eval/index.d.ts.map +1 -1
  21. package/dist/eval/index.js +11 -16
  22. package/dist/eval/index.js.map +1 -1
  23. package/dist/eval/llm-openrouter.d.ts +4 -1
  24. package/dist/eval/llm-openrouter.d.ts.map +1 -1
  25. package/dist/eval/llm-openrouter.js +21 -5
  26. package/dist/eval/llm-openrouter.js.map +1 -1
  27. package/dist/eval/transport.d.ts +5 -0
  28. package/dist/eval/transport.d.ts.map +1 -0
  29. package/dist/eval/transport.js +27 -0
  30. package/dist/eval/transport.js.map +1 -0
  31. package/dist/extract/index.d.ts +16 -0
  32. package/dist/extract/index.d.ts.map +1 -0
  33. package/dist/extract/index.js +95 -0
  34. package/dist/extract/index.js.map +1 -0
  35. package/dist/extract/normalize.d.ts +7 -0
  36. package/dist/extract/normalize.d.ts.map +1 -0
  37. package/dist/extract/normalize.js +52 -0
  38. package/dist/extract/normalize.js.map +1 -0
  39. package/dist/extract/office.d.ts +63 -0
  40. package/dist/extract/office.d.ts.map +1 -0
  41. package/dist/extract/office.js +763 -0
  42. package/dist/extract/office.js.map +1 -0
  43. package/dist/extract/pdf.d.ts +16 -0
  44. package/dist/extract/pdf.d.ts.map +1 -0
  45. package/dist/extract/pdf.js +196 -0
  46. package/dist/extract/pdf.js.map +1 -0
  47. package/dist/extract/types.d.ts +55 -0
  48. package/dist/extract/types.d.ts.map +1 -0
  49. package/dist/extract/types.js +47 -0
  50. package/dist/extract/types.js.map +1 -0
  51. package/dist/extract/worker.d.ts +2 -0
  52. package/dist/extract/worker.d.ts.map +1 -0
  53. package/dist/extract/worker.js +57 -0
  54. package/dist/extract/worker.js.map +1 -0
  55. package/dist/integrations/engine.d.ts +174 -3
  56. package/dist/integrations/engine.d.ts.map +1 -1
  57. package/dist/integrations/engine.js +184 -16
  58. package/dist/integrations/engine.js.map +1 -1
  59. package/dist/integrations/google.d.ts +2 -1
  60. package/dist/integrations/google.d.ts.map +1 -1
  61. package/dist/integrations/google.js +12 -117
  62. package/dist/integrations/google.js.map +1 -1
  63. package/dist/integrations/http-json.d.ts +27 -0
  64. package/dist/integrations/http-json.d.ts.map +1 -0
  65. package/dist/integrations/http-json.js +148 -0
  66. package/dist/integrations/http-json.js.map +1 -0
  67. package/dist/integrations/microsoft.d.ts +22 -0
  68. package/dist/integrations/microsoft.d.ts.map +1 -0
  69. package/dist/integrations/microsoft.js +1780 -0
  70. package/dist/integrations/microsoft.js.map +1 -0
  71. package/dist/integrations/microsoft.ui.d.ts +18 -0
  72. package/dist/integrations/microsoft.ui.d.ts.map +1 -0
  73. package/dist/integrations/microsoft.ui.js +131 -0
  74. package/dist/integrations/microsoft.ui.js.map +1 -0
  75. package/dist/integrations/oauth.d.ts.map +1 -1
  76. package/dist/integrations/oauth.js +10 -2
  77. package/dist/integrations/oauth.js.map +1 -1
  78. package/dist/integrations/queue.d.ts +1 -1
  79. package/dist/integrations/queue.d.ts.map +1 -1
  80. package/dist/integrations/queue.js +23 -1
  81. package/dist/integrations/queue.js.map +1 -1
  82. package/dist/integrations/routes.d.ts +26 -0
  83. package/dist/integrations/routes.d.ts.map +1 -1
  84. package/dist/integrations/routes.js +502 -8
  85. package/dist/integrations/routes.js.map +1 -1
  86. package/dist/integrations/runtime.d.ts +14 -2
  87. package/dist/integrations/runtime.d.ts.map +1 -1
  88. package/dist/integrations/runtime.js +39 -7
  89. package/dist/integrations/runtime.js.map +1 -1
  90. package/dist/integrations/state.d.ts +1 -1
  91. package/dist/integrations/state.d.ts.map +1 -1
  92. package/dist/integrations/state.js +48 -8
  93. package/dist/integrations/state.js.map +1 -1
  94. package/dist/integrations/types.d.ts +54 -3
  95. package/dist/integrations/types.d.ts.map +1 -1
  96. package/dist/integrations/types.js +21 -1
  97. package/dist/integrations/types.js.map +1 -1
  98. package/dist/search/watcher.d.ts.map +1 -1
  99. package/dist/search/watcher.js +3 -22
  100. package/dist/search/watcher.js.map +1 -1
  101. package/dist/serve/index.d.ts.map +1 -1
  102. package/dist/serve/index.js +7 -0
  103. package/dist/serve/index.js.map +1 -1
  104. package/dist/sleep/index.d.ts.map +1 -1
  105. package/dist/sleep/index.js +6 -16
  106. package/dist/sleep/index.js.map +1 -1
  107. package/dist/sleep/report.js +1 -1
  108. package/dist/sleep/report.js.map +1 -1
  109. package/dist/sleep/tension-scan.d.ts.map +1 -1
  110. package/dist/sleep/tension-scan.js +0 -0
  111. package/dist/sleep/tension-scan.js.map +1 -1
  112. package/dist/storage/local.d.ts +1 -0
  113. package/dist/storage/local.d.ts.map +1 -1
  114. package/dist/storage/local.js +8 -1
  115. package/dist/storage/local.js.map +1 -1
  116. package/dist/utils/config.d.ts +8 -1
  117. package/dist/utils/config.d.ts.map +1 -1
  118. package/dist/utils/config.js +143 -19
  119. package/dist/utils/config.js.map +1 -1
  120. package/dist/view/pages.d.ts.map +1 -1
  121. package/dist/view/pages.js +11 -0
  122. package/dist/view/pages.js.map +1 -1
  123. package/dist/view/render.d.ts.map +1 -1
  124. package/dist/view/render.js +37 -2
  125. package/dist/view/render.js.map +1 -1
  126. package/package.json +8 -3
  127. package/src/integrations/microsoft/assets/VENDORING.md +109 -0
  128. package/src/integrations/microsoft/assets/glue.js +244 -0
  129. package/src/integrations/microsoft/assets/picker-serializer.js +99 -0
  130. package/src/integrations/microsoft/assets/vendor/msal-browser/app/IPublicClientApplication.mjs +91 -0
  131. package/src/integrations/microsoft/assets/vendor/msal-browser/app/PublicClientApplication.mjs +355 -0
  132. package/src/integrations/microsoft/assets/vendor/msal-browser/broker/nativeBroker/NativeStatusCodes.mjs +15 -0
  133. package/src/integrations/microsoft/assets/vendor/msal-browser/broker/nativeBroker/PlatformAuthDOMHandler.mjs +153 -0
  134. package/src/integrations/microsoft/assets/vendor/msal-browser/broker/nativeBroker/PlatformAuthExtensionHandler.mjs +271 -0
  135. package/src/integrations/microsoft/assets/vendor/msal-browser/broker/nativeBroker/PlatformAuthProvider.mjs +95 -0
  136. package/src/integrations/microsoft/assets/vendor/msal-browser/cache/AccountManager.mjs +49 -0
  137. package/src/integrations/microsoft/assets/vendor/msal-browser/cache/AsyncMemoryStorage.mjs +144 -0
  138. package/src/integrations/microsoft/assets/vendor/msal-browser/cache/BrowserCacheManager.mjs +1465 -0
  139. package/src/integrations/microsoft/assets/vendor/msal-browser/cache/CacheHelpers.mjs +45 -0
  140. package/src/integrations/microsoft/assets/vendor/msal-browser/cache/CacheKeys.mjs +32 -0
  141. package/src/integrations/microsoft/assets/vendor/msal-browser/cache/CookieStorage.mjs +94 -0
  142. package/src/integrations/microsoft/assets/vendor/msal-browser/cache/DatabaseStorage.mjs +208 -0
  143. package/src/integrations/microsoft/assets/vendor/msal-browser/cache/EncryptedData.mjs +13 -0
  144. package/src/integrations/microsoft/assets/vendor/msal-browser/cache/LocalStorage.mjs +319 -0
  145. package/src/integrations/microsoft/assets/vendor/msal-browser/cache/MemoryStorage.mjs +48 -0
  146. package/src/integrations/microsoft/assets/vendor/msal-browser/cache/SessionStorage.mjs +46 -0
  147. package/src/integrations/microsoft/assets/vendor/msal-browser/cache/TokenCache.mjs +220 -0
  148. package/src/integrations/microsoft/assets/vendor/msal-browser/config/Configuration.mjs +138 -0
  149. package/src/integrations/microsoft/assets/vendor/msal-browser/controllers/NestedAppAuthController.mjs +483 -0
  150. package/src/integrations/microsoft/assets/vendor/msal-browser/controllers/StandardController.mjs +1532 -0
  151. package/src/integrations/microsoft/assets/vendor/msal-browser/crypto/BrowserCrypto.mjs +354 -0
  152. package/src/integrations/microsoft/assets/vendor/msal-browser/crypto/CryptoOps.mjs +146 -0
  153. package/src/integrations/microsoft/assets/vendor/msal-browser/crypto/PkceGenerator.mjs +63 -0
  154. package/src/integrations/microsoft/assets/vendor/msal-browser/crypto/SignedHttpRequest.mjs +50 -0
  155. package/src/integrations/microsoft/assets/vendor/msal-browser/crypto/TokenBindingKeyManager.mjs +156 -0
  156. package/src/integrations/microsoft/assets/vendor/msal-browser/encode/Base64Decode.mjs +43 -0
  157. package/src/integrations/microsoft/assets/vendor/msal-browser/encode/Base64Encode.mjs +47 -0
  158. package/src/integrations/microsoft/assets/vendor/msal-browser/error/BrowserAuthError.mjs +26 -0
  159. package/src/integrations/microsoft/assets/vendor/msal-browser/error/BrowserAuthErrorCodes.mjs +65 -0
  160. package/src/integrations/microsoft/assets/vendor/msal-browser/error/BrowserConfigurationAuthError.mjs +24 -0
  161. package/src/integrations/microsoft/assets/vendor/msal-browser/error/BrowserConfigurationAuthErrorCodes.mjs +11 -0
  162. package/src/integrations/microsoft/assets/vendor/msal-browser/error/NativeAuthError.mjs +79 -0
  163. package/src/integrations/microsoft/assets/vendor/msal-browser/error/NativeAuthErrorCodes.mjs +12 -0
  164. package/src/integrations/microsoft/assets/vendor/msal-browser/error/NestedAppAuthError.mjs +25 -0
  165. package/src/integrations/microsoft/assets/vendor/msal-browser/event/EventHandler.mjs +110 -0
  166. package/src/integrations/microsoft/assets/vendor/msal-browser/event/EventMessage.mjs +60 -0
  167. package/src/integrations/microsoft/assets/vendor/msal-browser/event/EventType.mjs +30 -0
  168. package/src/integrations/microsoft/assets/vendor/msal-browser/index.mjs +48 -0
  169. package/src/integrations/microsoft/assets/vendor/msal-browser/interaction_client/BaseInteractionClient.mjs +150 -0
  170. package/src/integrations/microsoft/assets/vendor/msal-browser/interaction_client/HybridSpaAuthorizationCodeClient.mjs +16 -0
  171. package/src/integrations/microsoft/assets/vendor/msal-browser/interaction_client/PlatformAuthInteractionClient.mjs +734 -0
  172. package/src/integrations/microsoft/assets/vendor/msal-browser/interaction_client/PopupClient.mjs +528 -0
  173. package/src/integrations/microsoft/assets/vendor/msal-browser/interaction_client/RedirectClient.mjs +464 -0
  174. package/src/integrations/microsoft/assets/vendor/msal-browser/interaction_client/SilentAuthCodeClient.mjs +85 -0
  175. package/src/integrations/microsoft/assets/vendor/msal-browser/interaction_client/SilentCacheClient.mjs +58 -0
  176. package/src/integrations/microsoft/assets/vendor/msal-browser/interaction_client/SilentIframeClient.mjs +255 -0
  177. package/src/integrations/microsoft/assets/vendor/msal-browser/interaction_client/SilentRefreshClient.mjs +77 -0
  178. package/src/integrations/microsoft/assets/vendor/msal-browser/interaction_client/StandardInteractionClient.mjs +217 -0
  179. package/src/integrations/microsoft/assets/vendor/msal-browser/interaction_handler/InteractionHandler.mjs +95 -0
  180. package/src/integrations/microsoft/assets/vendor/msal-browser/interaction_handler/SilentHandler.mjs +71 -0
  181. package/src/integrations/microsoft/assets/vendor/msal-browser/naa/BridgeError.mjs +11 -0
  182. package/src/integrations/microsoft/assets/vendor/msal-browser/naa/BridgeProxy.mjs +152 -0
  183. package/src/integrations/microsoft/assets/vendor/msal-browser/naa/BridgeStatusCode.mjs +18 -0
  184. package/src/integrations/microsoft/assets/vendor/msal-browser/naa/mapping/NestedAppAuthAdapter.mjs +239 -0
  185. package/src/integrations/microsoft/assets/vendor/msal-browser/navigation/NavigationClient.mjs +47 -0
  186. package/src/integrations/microsoft/assets/vendor/msal-browser/network/FetchClient.mjs +153 -0
  187. package/src/integrations/microsoft/assets/vendor/msal-browser/operatingcontext/BaseOperatingContext.mjs +112 -0
  188. package/src/integrations/microsoft/assets/vendor/msal-browser/operatingcontext/NestedAppOperatingContext.mjs +79 -0
  189. package/src/integrations/microsoft/assets/vendor/msal-browser/operatingcontext/StandardOperatingContext.mjs +50 -0
  190. package/src/integrations/microsoft/assets/vendor/msal-browser/packageMetadata.mjs +7 -0
  191. package/src/integrations/microsoft/assets/vendor/msal-browser/popup_relay/constants.mjs +20 -0
  192. package/src/integrations/microsoft/assets/vendor/msal-browser/popup_relay/relayClient.mjs +113 -0
  193. package/src/integrations/microsoft/assets/vendor/msal-browser/protocol/Authorize.mjs +326 -0
  194. package/src/integrations/microsoft/assets/vendor/msal-browser/request/RequestHelpers.mjs +143 -0
  195. package/src/integrations/microsoft/assets/vendor/msal-browser/response/ResponseHandler.mjs +45 -0
  196. package/src/integrations/microsoft/assets/vendor/msal-browser/telemetry/BrowserPerformanceClient.mjs +126 -0
  197. package/src/integrations/microsoft/assets/vendor/msal-browser/telemetry/BrowserPerformanceEvents.mjs +133 -0
  198. package/src/integrations/microsoft/assets/vendor/msal-browser/telemetry/BrowserPerformanceMeasurement.mjs +96 -0
  199. package/src/integrations/microsoft/assets/vendor/msal-browser/telemetry/BrowserRootPerformanceEvents.mjs +53 -0
  200. package/src/integrations/microsoft/assets/vendor/msal-browser/utils/BrowserConstants.mjs +220 -0
  201. package/src/integrations/microsoft/assets/vendor/msal-browser/utils/BrowserProtocolUtils.mjs +27 -0
  202. package/src/integrations/microsoft/assets/vendor/msal-browser/utils/BrowserUtils.mjs +364 -0
  203. package/src/integrations/microsoft/assets/vendor/msal-browser/utils/Helpers.mjs +19 -0
  204. package/src/integrations/microsoft/assets/vendor/msal-browser/utils/MsalFrameStatsUtils.mjs +38 -0
  205. package/src/integrations/microsoft/assets/vendor/msal-browser/webBrokerBridge/PendingRequestRegistry.mjs +63 -0
  206. package/src/integrations/microsoft/assets/vendor/msal-browser/webBrokerBridge/WebBrokerBridgeError.mjs +38 -0
  207. package/src/integrations/microsoft/assets/vendor/msal-browser/webBrokerBridge/WebBrokerBridgeErrorMap.mjs +57 -0
  208. package/src/integrations/microsoft/assets/vendor/msal-common/account/AccountInfo.mjs +91 -0
  209. package/src/integrations/microsoft/assets/vendor/msal-common/account/AuthToken.mjs +70 -0
  210. package/src/integrations/microsoft/assets/vendor/msal-common/account/CcsCredential.mjs +12 -0
  211. package/src/integrations/microsoft/assets/vendor/msal-common/account/ClientInfo.mjs +43 -0
  212. package/src/integrations/microsoft/assets/vendor/msal-common/account/TokenClaims.mjs +24 -0
  213. package/src/integrations/microsoft/assets/vendor/msal-common/authority/Authority.mjs +988 -0
  214. package/src/integrations/microsoft/assets/vendor/msal-common/authority/AuthorityFactory.mjs +41 -0
  215. package/src/integrations/microsoft/assets/vendor/msal-common/authority/AuthorityMetadata.mjs +158 -0
  216. package/src/integrations/microsoft/assets/vendor/msal-common/authority/AuthorityOptions.mjs +20 -0
  217. package/src/integrations/microsoft/assets/vendor/msal-common/authority/AuthorityType.mjs +16 -0
  218. package/src/integrations/microsoft/assets/vendor/msal-common/authority/CloudInstanceDiscoveryErrorResponse.mjs +12 -0
  219. package/src/integrations/microsoft/assets/vendor/msal-common/authority/CloudInstanceDiscoveryResponse.mjs +12 -0
  220. package/src/integrations/microsoft/assets/vendor/msal-common/authority/OpenIdConfigResponse.mjs +14 -0
  221. package/src/integrations/microsoft/assets/vendor/msal-common/authority/ProtocolMode.mjs +26 -0
  222. package/src/integrations/microsoft/assets/vendor/msal-common/authority/RegionDiscovery.mjs +116 -0
  223. package/src/integrations/microsoft/assets/vendor/msal-common/cache/CacheManager.mjs +1202 -0
  224. package/src/integrations/microsoft/assets/vendor/msal-common/cache/persistence/TokenCacheContext.mjs +29 -0
  225. package/src/integrations/microsoft/assets/vendor/msal-common/cache/utils/AccountEntityUtils.mjs +222 -0
  226. package/src/integrations/microsoft/assets/vendor/msal-common/cache/utils/CacheHelpers.mjs +294 -0
  227. package/src/integrations/microsoft/assets/vendor/msal-common/client/AuthorizationCodeClient.mjs +289 -0
  228. package/src/integrations/microsoft/assets/vendor/msal-common/client/RefreshTokenClient.mjs +262 -0
  229. package/src/integrations/microsoft/assets/vendor/msal-common/client/SilentFlowClient.mjs +142 -0
  230. package/src/integrations/microsoft/assets/vendor/msal-common/config/ClientConfiguration.mjs +111 -0
  231. package/src/integrations/microsoft/assets/vendor/msal-common/constants/AADServerParamKeys.mjs +74 -0
  232. package/src/integrations/microsoft/assets/vendor/msal-common/crypto/DpopProofGenerator.mjs +152 -0
  233. package/src/integrations/microsoft/assets/vendor/msal-common/crypto/ICrypto.mjs +52 -0
  234. package/src/integrations/microsoft/assets/vendor/msal-common/crypto/ITokenBindingKeyManager.mjs +27 -0
  235. package/src/integrations/microsoft/assets/vendor/msal-common/crypto/JoseHeader.mjs +72 -0
  236. package/src/integrations/microsoft/assets/vendor/msal-common/crypto/PopTokenGenerator.mjs +109 -0
  237. package/src/integrations/microsoft/assets/vendor/msal-common/error/AuthError.mjs +31 -0
  238. package/src/integrations/microsoft/assets/vendor/msal-common/error/AuthErrorCodes.mjs +13 -0
  239. package/src/integrations/microsoft/assets/vendor/msal-common/error/CacheError.mjs +44 -0
  240. package/src/integrations/microsoft/assets/vendor/msal-common/error/CacheErrorCodes.mjs +10 -0
  241. package/src/integrations/microsoft/assets/vendor/msal-common/error/ClientAuthError.mjs +26 -0
  242. package/src/integrations/microsoft/assets/vendor/msal-common/error/ClientAuthErrorCodes.mjs +46 -0
  243. package/src/integrations/microsoft/assets/vendor/msal-common/error/ClientConfigurationError.mjs +23 -0
  244. package/src/integrations/microsoft/assets/vendor/msal-common/error/ClientConfigurationErrorCodes.mjs +38 -0
  245. package/src/integrations/microsoft/assets/vendor/msal-common/error/InteractionRequiredAuthError.mjs +73 -0
  246. package/src/integrations/microsoft/assets/vendor/msal-common/error/InteractionRequiredAuthErrorCodes.mjs +53 -0
  247. package/src/integrations/microsoft/assets/vendor/msal-common/error/JoseHeaderError.mjs +24 -0
  248. package/src/integrations/microsoft/assets/vendor/msal-common/error/JoseHeaderErrorCodes.mjs +12 -0
  249. package/src/integrations/microsoft/assets/vendor/msal-common/error/NetworkError.mjs +34 -0
  250. package/src/integrations/microsoft/assets/vendor/msal-common/error/PlatformBrokerError.mjs +48 -0
  251. package/src/integrations/microsoft/assets/vendor/msal-common/error/ServerError.mjs +22 -0
  252. package/src/integrations/microsoft/assets/vendor/msal-common/index-browser.mjs +79 -0
  253. package/src/integrations/microsoft/assets/vendor/msal-common/logger/Logger.mjs +291 -0
  254. package/src/integrations/microsoft/assets/vendor/msal-common/network/INetworkModule.mjs +20 -0
  255. package/src/integrations/microsoft/assets/vendor/msal-common/network/RequestThumbprint.mjs +27 -0
  256. package/src/integrations/microsoft/assets/vendor/msal-common/network/ThrottlingUtils.mjs +91 -0
  257. package/src/integrations/microsoft/assets/vendor/msal-common/packageMetadata.mjs +7 -0
  258. package/src/integrations/microsoft/assets/vendor/msal-common/protocol/Authorize.mjs +239 -0
  259. package/src/integrations/microsoft/assets/vendor/msal-common/protocol/Token.mjs +148 -0
  260. package/src/integrations/microsoft/assets/vendor/msal-common/request/AuthenticationHeaderParser.mjs +63 -0
  261. package/src/integrations/microsoft/assets/vendor/msal-common/request/BaseAuthRequest.mjs +37 -0
  262. package/src/integrations/microsoft/assets/vendor/msal-common/request/RequestParameterBuilder.mjs +529 -0
  263. package/src/integrations/microsoft/assets/vendor/msal-common/request/ScopeSet.mjs +204 -0
  264. package/src/integrations/microsoft/assets/vendor/msal-common/response/ResponseHandler.mjs +432 -0
  265. package/src/integrations/microsoft/assets/vendor/msal-common/telemetry/performance/PerformanceClient.mjs +557 -0
  266. package/src/integrations/microsoft/assets/vendor/msal-common/telemetry/performance/PerformanceEvent.mjs +68 -0
  267. package/src/integrations/microsoft/assets/vendor/msal-common/telemetry/performance/PerformanceEvents.mjs +73 -0
  268. package/src/integrations/microsoft/assets/vendor/msal-common/telemetry/performance/StubPerformanceClient.mjs +61 -0
  269. package/src/integrations/microsoft/assets/vendor/msal-common/telemetry/server/ServerTelemetryManager.mjs +297 -0
  270. package/src/integrations/microsoft/assets/vendor/msal-common/url/UrlString.mjs +164 -0
  271. package/src/integrations/microsoft/assets/vendor/msal-common/utils/ClientAssertionUtils.mjs +21 -0
  272. package/src/integrations/microsoft/assets/vendor/msal-common/utils/Constants.mjs +304 -0
  273. package/src/integrations/microsoft/assets/vendor/msal-common/utils/FunctionWrappers.mjs +95 -0
  274. package/src/integrations/microsoft/assets/vendor/msal-common/utils/ObjectUtils.mjs +27 -0
  275. package/src/integrations/microsoft/assets/vendor/msal-common/utils/ProtocolUtils.mjs +76 -0
  276. package/src/integrations/microsoft/assets/vendor/msal-common/utils/StringUtils.mjs +82 -0
  277. package/src/integrations/microsoft/assets/vendor/msal-common/utils/TimeUtils.mjs +75 -0
  278. package/src/integrations/microsoft/assets/vendor/msal-common/utils/UrlUtils.mjs +128 -0
@@ -0,0 +1,1465 @@
1
+ /*! @azure/msal-browser v5.20.0 2026-08-28 */
2
+ 'use strict';
3
+ import { CacheManager, DEFAULT_TOKEN_BINDING_KEY_MANAGER, TimeUtils, CacheHelpers, Constants, AuthToken, getTenantIdFromIdTokenClaims, buildTenantProfile, AccountEntityUtils, createCacheError, CacheErrorCodes, invokeAsync, PerformanceEvents, StringUtils, CacheError, DEFAULT_CRYPTO_IMPLEMENTATION } from '../../msal-common/index-browser.mjs';
4
+ import { createBrowserAuthError } from '../error/BrowserAuthError.mjs';
5
+ import { apiIdToName, InMemoryCacheKeys, TemporaryCacheKeys, INTERACTION_TYPE, ApiId, BrowserCacheLocation } from '../utils/BrowserConstants.mjs';
6
+ import { ACCOUNT_SCHEMA_VERSION, CREDENTIAL_SCHEMA_VERSION, VERSION_CACHE_KEY, getTokenKeysCacheKey, getAccountKeysCacheKey, PREFIX, CACHE_KEY_SEPARATOR } from './CacheKeys.mjs';
7
+ import { LocalStorage } from './LocalStorage.mjs';
8
+ import { SessionStorage } from './SessionStorage.mjs';
9
+ import { MemoryStorage } from './MemoryStorage.mjs';
10
+ import { base64Decode } from '../encode/Base64Decode.mjs';
11
+ import { base64Encode } from '../encode/Base64Encode.mjs';
12
+ import { CookieStorage } from './CookieStorage.mjs';
13
+ import { getAccountKeys, getTokenKeys } from './CacheHelpers.mjs';
14
+ import { EventType } from '../event/EventType.mjs';
15
+ import { clearHash, cancelPendingBridgeResponse } from '../utils/BrowserUtils.mjs';
16
+ import { version } from '../packageMetadata.mjs';
17
+ import { removeElementFromArray } from '../utils/Helpers.mjs';
18
+ import { isEncrypted } from './EncryptedData.mjs';
19
+ import { noTokenRequestCacheError, unableToParseTokenRequestCacheError, interactionInProgress } from '../error/BrowserAuthErrorCodes.mjs';
20
+
21
+ /*
22
+ * Copyright (c) Microsoft Corporation. All rights reserved.
23
+ * Licensed under the MIT License.
24
+ */
25
+ /**
26
+ * Reason an old-schema cache entry was removed during migration.
27
+ */
28
+ const MigrationRemovalReason = {
29
+ Invalid: "invalid",
30
+ TtlExpired: "ttlExpired",
31
+ DecryptFailed: "decryptFailed",
32
+ Expired: "expired",
33
+ };
34
+ /**
35
+ * This class implements the cache storage interface for MSAL through browser local or session storage.
36
+ */
37
+ class BrowserCacheManager extends CacheManager {
38
+ constructor(clientId, cacheConfig, cryptoImpl, logger, performanceClient, eventHandler, staticAuthorityOptions, tokenBindingKeyManager = DEFAULT_TOKEN_BINDING_KEY_MANAGER) {
39
+ super(clientId, cryptoImpl, logger, performanceClient, staticAuthorityOptions, tokenBindingKeyManager);
40
+ this.cacheConfig = cacheConfig;
41
+ this.logger = logger;
42
+ this.internalStorage = new MemoryStorage();
43
+ this.browserStorage = getStorageImplementation(clientId, cacheConfig.cacheLocation, logger, performanceClient);
44
+ this.temporaryCacheStorage = getStorageImplementation(clientId, BrowserCacheLocation.SessionStorage, logger, performanceClient);
45
+ this.cookieStorage = new CookieStorage();
46
+ this.eventHandler = eventHandler;
47
+ }
48
+ async initialize(correlationId) {
49
+ this.performanceClient.addFields({
50
+ cacheLocation: this.cacheConfig.cacheLocation,
51
+ cacheRetentionDays: this.cacheConfig.cacheRetentionDays,
52
+ }, correlationId);
53
+ await this.browserStorage.initialize(correlationId);
54
+ await this.migrateExistingCache(correlationId);
55
+ this.trackVersionChanges(correlationId);
56
+ }
57
+ /**
58
+ * Migrates any existing cache data from previous versions of MSAL.js into the current cache structure.
59
+ */
60
+ async migrateExistingCache(correlationId) {
61
+ let accountKeys = getAccountKeys(this.browserStorage);
62
+ let tokenKeys = getTokenKeys(this.clientId, this.browserStorage);
63
+ this.performanceClient.addFields({
64
+ preMigrateAcntCount: accountKeys.length,
65
+ preMigrateATCount: tokenKeys.accessToken.length,
66
+ preMigrateITCount: tokenKeys.idToken.length,
67
+ preMigrateRTCount: tokenKeys.refreshToken.length,
68
+ }, correlationId);
69
+ for (let i = 0; i < ACCOUNT_SCHEMA_VERSION; i++) {
70
+ const credentialSchema = i; // For now account and credential schemas are the same, but may diverge in future
71
+ await this.removeStaleAccounts(i, credentialSchema, correlationId);
72
+ }
73
+ // Must migrate idTokens first to ensure we have KMSI info for the rest
74
+ for (let i = 0; i < CREDENTIAL_SCHEMA_VERSION; i++) {
75
+ const accountSchema = i; // For now account and credential schemas are the same, but may diverge in future
76
+ await this.migrateIdTokens(i, accountSchema, correlationId);
77
+ }
78
+ const kmsiMap = this.getKMSIValues();
79
+ for (let i = 0; i < CREDENTIAL_SCHEMA_VERSION; i++) {
80
+ await this.migrateAccessTokens(i, kmsiMap, correlationId);
81
+ await this.migrateRefreshTokens(i, kmsiMap, correlationId);
82
+ }
83
+ accountKeys = getAccountKeys(this.browserStorage);
84
+ tokenKeys = getTokenKeys(this.clientId, this.browserStorage);
85
+ this.performanceClient.addFields({
86
+ postMigrateAcntCount: accountKeys.length,
87
+ postMigrateATCount: tokenKeys.accessToken.length,
88
+ postMigrateITCount: tokenKeys.idToken.length,
89
+ postMigrateRTCount: tokenKeys.refreshToken.length,
90
+ }, correlationId);
91
+ }
92
+ /**
93
+ * Parses entry, adds lastUpdatedAt if it doesn't exist, removes entry if expired or invalid
94
+ * @param key
95
+ * @param correlationId
96
+ * @returns
97
+ */
98
+ async updateOldEntry(key, correlationId) {
99
+ const rawValue = this.browserStorage.getItem(key);
100
+ const parsedValue = this.validateAndParseJson(rawValue || "");
101
+ if (!parsedValue) {
102
+ this.browserStorage.removeItem(key);
103
+ return {
104
+ entry: null,
105
+ removalReason: MigrationRemovalReason.Invalid,
106
+ };
107
+ }
108
+ if (!parsedValue.lastUpdatedAt) {
109
+ // Add lastUpdatedAt to the existing v0 entry if it doesnt exist so we know when it's safe to remove it
110
+ parsedValue.lastUpdatedAt = Date.now().toString();
111
+ this.setItem(key, JSON.stringify(parsedValue), correlationId);
112
+ }
113
+ else if (TimeUtils.isCacheExpired(parsedValue.lastUpdatedAt, this.cacheConfig.cacheRetentionDays)) {
114
+ this.browserStorage.removeItem(key);
115
+ return {
116
+ entry: null,
117
+ removalReason: MigrationRemovalReason.TtlExpired,
118
+ };
119
+ }
120
+ const wasEncrypted = isEncrypted(parsedValue);
121
+ const decryptedData = wasEncrypted
122
+ ? await this.browserStorage.decryptData(key, parsedValue, correlationId)
123
+ : parsedValue;
124
+ if (!decryptedData) {
125
+ this.browserStorage.removeItem(key);
126
+ return {
127
+ entry: null,
128
+ removalReason: wasEncrypted
129
+ ? MigrationRemovalReason.DecryptFailed
130
+ : MigrationRemovalReason.Invalid,
131
+ };
132
+ }
133
+ if (!CacheHelpers.isCredentialEntity(decryptedData)) {
134
+ this.browserStorage.removeItem(key);
135
+ return {
136
+ entry: null,
137
+ removalReason: MigrationRemovalReason.Invalid,
138
+ };
139
+ }
140
+ if ((CacheHelpers.isAccessTokenEntity(decryptedData) ||
141
+ CacheHelpers.isRefreshTokenEntity(decryptedData)) &&
142
+ decryptedData.expiresOn &&
143
+ TimeUtils.isTokenExpired(decryptedData.expiresOn, Constants.DEFAULT_TOKEN_RENEWAL_OFFSET_SEC)) {
144
+ this.browserStorage.removeItem(key);
145
+ return {
146
+ entry: null,
147
+ removalReason: MigrationRemovalReason.Expired,
148
+ };
149
+ }
150
+ return { entry: decryptedData };
151
+ }
152
+ /**
153
+ * Remove accounts from the cache for older schema versions if they have not been updated in the last cacheRetentionDays
154
+ * @param accountSchema
155
+ * @param credentialSchema
156
+ * @param correlationId
157
+ * @returns
158
+ */
159
+ async removeStaleAccounts(accountSchema, credentialSchema, correlationId) {
160
+ const accountKeysToCheck = getAccountKeys(this.browserStorage, accountSchema);
161
+ if (accountKeysToCheck.length === 0) {
162
+ return;
163
+ }
164
+ for (const accountKey of [...accountKeysToCheck]) {
165
+ this.performanceClient.incrementFields({ oldAcntCount: 1 }, correlationId);
166
+ const rawValue = this.browserStorage.getItem(accountKey);
167
+ const parsedValue = this.validateAndParseJson(rawValue || "");
168
+ if (!parsedValue) {
169
+ this.browserStorage.removeItem(accountKey);
170
+ this.performanceClient.incrementFields({ invalidAcntCount: 1 }, correlationId);
171
+ removeElementFromArray(accountKeysToCheck, accountKey);
172
+ continue;
173
+ }
174
+ if (!parsedValue.lastUpdatedAt) {
175
+ // Add lastUpdatedAt to the existing entry if it doesnt exist so we know when it's safe to remove it
176
+ parsedValue.lastUpdatedAt = Date.now().toString();
177
+ this.setItem(accountKey, JSON.stringify(parsedValue), correlationId);
178
+ continue;
179
+ }
180
+ else if (TimeUtils.isCacheExpired(parsedValue.lastUpdatedAt, this.cacheConfig.cacheRetentionDays)) {
181
+ // Cache expired remove account and associated tokens
182
+ await this.removeAccountOldSchema(accountKey, parsedValue, credentialSchema, correlationId);
183
+ this.performanceClient.incrementFields({ ttlExpiredAcntCount: 1 }, correlationId);
184
+ removeElementFromArray(accountKeysToCheck, accountKey);
185
+ }
186
+ else if (isEncrypted(parsedValue)) {
187
+ // Remove accounts encrypted with a different key (session cookie expired/changed)
188
+ const decrypted = await this.browserStorage.decryptData(accountKey, parsedValue, correlationId);
189
+ if (!decrypted) {
190
+ this.browserStorage.removeItem(accountKey);
191
+ this.performanceClient.incrementFields({
192
+ decryptFailedAcntCount: 1,
193
+ }, correlationId);
194
+ removeElementFromArray(accountKeysToCheck, accountKey);
195
+ }
196
+ }
197
+ }
198
+ this.setAccountKeys(accountKeysToCheck, correlationId, accountSchema);
199
+ }
200
+ /**
201
+ * Remove the given account and all associated tokens from the cache
202
+ * @param accountKey
203
+ * @param rawObject
204
+ * @param credentialSchema
205
+ * @param correlationId
206
+ */
207
+ async removeAccountOldSchema(accountKey, rawObject, credentialSchema, correlationId) {
208
+ const decryptedData = isEncrypted(rawObject)
209
+ ? (await this.browserStorage.decryptData(accountKey, rawObject, correlationId))
210
+ : rawObject;
211
+ const homeAccountId = decryptedData?.homeAccountId;
212
+ if (homeAccountId) {
213
+ const tokenKeys = this.getTokenKeys(credentialSchema);
214
+ [...tokenKeys.idToken]
215
+ .filter((key) => key.includes(homeAccountId))
216
+ .forEach((key) => {
217
+ this.browserStorage.removeItem(key);
218
+ removeElementFromArray(tokenKeys.idToken, key);
219
+ });
220
+ [...tokenKeys.accessToken]
221
+ .filter((key) => key.includes(homeAccountId))
222
+ .forEach((key) => {
223
+ this.browserStorage.removeItem(key);
224
+ removeElementFromArray(tokenKeys.accessToken, key);
225
+ });
226
+ [...tokenKeys.refreshToken]
227
+ .filter((key) => key.includes(homeAccountId))
228
+ .forEach((key) => {
229
+ this.browserStorage.removeItem(key);
230
+ removeElementFromArray(tokenKeys.refreshToken, key);
231
+ });
232
+ this.setTokenKeys(tokenKeys, correlationId, credentialSchema);
233
+ }
234
+ this.browserStorage.removeItem(accountKey);
235
+ }
236
+ /**
237
+ * Gets key value pair mapping homeAccountId to KMSI value
238
+ * @returns
239
+ */
240
+ getKMSIValues() {
241
+ const kmsiMap = {};
242
+ const tokenKeys = this.getTokenKeys().idToken;
243
+ for (const key of tokenKeys) {
244
+ const rawValue = this.browserStorage.getUserData(key);
245
+ if (rawValue) {
246
+ const idToken = JSON.parse(rawValue);
247
+ const claims = AuthToken.extractTokenClaims(idToken.secret, base64Decode, "");
248
+ if (claims) {
249
+ kmsiMap[idToken.homeAccountId] = AuthToken.isKmsi(claims);
250
+ }
251
+ }
252
+ }
253
+ return kmsiMap;
254
+ }
255
+ /**
256
+ * Migrates id tokens from the old schema to the new schema, also migrates associated account object if it doesn't already exist in the new schema
257
+ * @param credentialSchema
258
+ * @param accountSchema
259
+ * @param correlationId
260
+ * @returns
261
+ */
262
+ async migrateIdTokens(credentialSchema, accountSchema, correlationId) {
263
+ const credentialKeysToMigrate = getTokenKeys(this.clientId, this.browserStorage, credentialSchema);
264
+ if (credentialKeysToMigrate.idToken.length === 0) {
265
+ return;
266
+ }
267
+ const currentCredentialKeys = getTokenKeys(this.clientId, this.browserStorage, CREDENTIAL_SCHEMA_VERSION);
268
+ const currentAccountKeys = getAccountKeys(this.browserStorage);
269
+ const previousAccountKeys = getAccountKeys(this.browserStorage, accountSchema);
270
+ for (const idTokenKey of [...credentialKeysToMigrate.idToken]) {
271
+ this.performanceClient.incrementFields({ oldITCount: 1 }, correlationId);
272
+ const result = await this.updateOldEntry(idTokenKey, correlationId);
273
+ const oldSchemaData = result.entry;
274
+ if (!oldSchemaData) {
275
+ switch (result.removalReason) {
276
+ case MigrationRemovalReason.TtlExpired:
277
+ this.performanceClient.incrementFields({ ttlExpiredITCount: 1 }, correlationId);
278
+ break;
279
+ case MigrationRemovalReason.DecryptFailed:
280
+ this.performanceClient.incrementFields({ decryptFailedITCount: 1 }, correlationId);
281
+ break;
282
+ case MigrationRemovalReason.Invalid:
283
+ this.performanceClient.incrementFields({ invalidITCount: 1 }, correlationId);
284
+ break;
285
+ }
286
+ removeElementFromArray(credentialKeysToMigrate.idToken, idTokenKey);
287
+ continue;
288
+ }
289
+ const currentAccountKey = currentAccountKeys.find((key) => key.includes(oldSchemaData.homeAccountId));
290
+ const previousAccountKey = previousAccountKeys.find((key) => key.includes(oldSchemaData.homeAccountId));
291
+ let account = null;
292
+ if (currentAccountKey) {
293
+ account = this.getAccount(currentAccountKey, correlationId);
294
+ }
295
+ else if (previousAccountKey) {
296
+ const rawValue = this.browserStorage.getItem(previousAccountKey);
297
+ const parsedValue = this.validateAndParseJson(rawValue || "");
298
+ account =
299
+ parsedValue && isEncrypted(parsedValue)
300
+ ? (await this.browserStorage.decryptData(previousAccountKey, parsedValue, correlationId))
301
+ : parsedValue;
302
+ }
303
+ if (!account) {
304
+ // Don't migrate idToken if we don't have an account for it
305
+ this.performanceClient.incrementFields({ skipITMigrateCount: 1 }, correlationId);
306
+ continue;
307
+ }
308
+ const claims = AuthToken.extractTokenClaims(oldSchemaData.secret, base64Decode, correlationId);
309
+ const newIdTokenKey = this.generateCredentialKey(oldSchemaData);
310
+ const currentIdToken = this.getIdTokenCredential(newIdTokenKey, correlationId);
311
+ const oldTokenHasSignInState = Object.keys(claims).includes("signin_state");
312
+ const currentTokenHasSignInState = currentIdToken &&
313
+ Object.keys(AuthToken.extractTokenClaims(currentIdToken.secret, base64Decode, correlationId) || {}).includes("signin_state");
314
+ /**
315
+ * Only migrate if:
316
+ * 1. Token doesn't yet exist in current schema
317
+ * 2. Old schema token has been updated more recently than the current one AND migrating it won't result in loss of KMSI state
318
+ */
319
+ if (!currentIdToken ||
320
+ (oldSchemaData.lastUpdatedAt > currentIdToken.lastUpdatedAt &&
321
+ (oldTokenHasSignInState || !currentTokenHasSignInState))) {
322
+ const tenantProfiles = account.tenantProfiles || [];
323
+ const tenantId = getTenantIdFromIdTokenClaims(claims) || account.realm;
324
+ if (tenantId &&
325
+ !tenantProfiles.find((tenantProfile) => {
326
+ return tenantProfile.tenantId === tenantId;
327
+ })) {
328
+ const newTenantProfile = buildTenantProfile(account.homeAccountId, account.localAccountId, tenantId, account.nativeAccountId, claims);
329
+ tenantProfiles.push(newTenantProfile);
330
+ }
331
+ account.tenantProfiles = tenantProfiles;
332
+ const newAccountKey = this.generateAccountKey(AccountEntityUtils.getAccountInfo(account));
333
+ const kmsi = AuthToken.isKmsi(claims);
334
+ await this.setUserData(newAccountKey, JSON.stringify(account), correlationId, account.lastUpdatedAt, kmsi);
335
+ if (!currentAccountKeys.includes(newAccountKey)) {
336
+ currentAccountKeys.push(newAccountKey);
337
+ }
338
+ await this.setUserData(newIdTokenKey, JSON.stringify(oldSchemaData), correlationId, oldSchemaData.lastUpdatedAt, kmsi);
339
+ this.performanceClient.incrementFields({ migratedITCount: 1 }, correlationId);
340
+ if (!currentCredentialKeys.idToken.includes(newIdTokenKey)) {
341
+ currentCredentialKeys.idToken.push(newIdTokenKey);
342
+ }
343
+ }
344
+ }
345
+ this.setTokenKeys(credentialKeysToMigrate, correlationId, credentialSchema);
346
+ this.setTokenKeys(currentCredentialKeys, correlationId);
347
+ this.setAccountKeys(currentAccountKeys, correlationId);
348
+ }
349
+ /**
350
+ * Migrates access tokens from old cache schema to current schema
351
+ * @param credentialSchema
352
+ * @param kmsiMap
353
+ * @param correlationId
354
+ * @returns
355
+ */
356
+ async migrateAccessTokens(credentialSchema, kmsiMap, correlationId) {
357
+ const credentialKeysToMigrate = getTokenKeys(this.clientId, this.browserStorage, credentialSchema);
358
+ if (credentialKeysToMigrate.accessToken.length === 0) {
359
+ return;
360
+ }
361
+ const currentCredentialKeys = getTokenKeys(this.clientId, this.browserStorage, CREDENTIAL_SCHEMA_VERSION);
362
+ for (const accessTokenKey of [...credentialKeysToMigrate.accessToken]) {
363
+ this.performanceClient.incrementFields({ oldATCount: 1 }, correlationId);
364
+ const result = await this.updateOldEntry(accessTokenKey, correlationId);
365
+ const oldSchemaData = result.entry;
366
+ if (!oldSchemaData) {
367
+ switch (result.removalReason) {
368
+ case MigrationRemovalReason.TtlExpired:
369
+ this.performanceClient.incrementFields({ ttlExpiredATCount: 1 }, correlationId);
370
+ break;
371
+ case MigrationRemovalReason.DecryptFailed:
372
+ this.performanceClient.incrementFields({ decryptFailedATCount: 1 }, correlationId);
373
+ break;
374
+ case MigrationRemovalReason.Expired:
375
+ this.performanceClient.incrementFields({ expiredATCount: 1 }, correlationId);
376
+ break;
377
+ case MigrationRemovalReason.Invalid:
378
+ this.performanceClient.incrementFields({ invalidATCount: 1 }, correlationId);
379
+ break;
380
+ }
381
+ removeElementFromArray(credentialKeysToMigrate.accessToken, accessTokenKey);
382
+ continue;
383
+ }
384
+ if (!(oldSchemaData.homeAccountId in kmsiMap)) {
385
+ // Don't migrate tokens if we don't have an idToken for them
386
+ this.performanceClient.incrementFields({ skipATMigrateCount: 1 }, correlationId);
387
+ continue;
388
+ }
389
+ const newKey = this.generateCredentialKey(oldSchemaData);
390
+ const kmsi = kmsiMap[oldSchemaData.homeAccountId];
391
+ if (!currentCredentialKeys.accessToken.includes(newKey)) {
392
+ await this.setUserData(newKey, JSON.stringify(oldSchemaData), correlationId, oldSchemaData.lastUpdatedAt, kmsi);
393
+ this.performanceClient.incrementFields({ migratedATCount: 1 }, correlationId);
394
+ currentCredentialKeys.accessToken.push(newKey);
395
+ }
396
+ else {
397
+ const currentToken = this.getAccessTokenCredential(newKey, correlationId);
398
+ if (!currentToken ||
399
+ oldSchemaData.lastUpdatedAt > currentToken.lastUpdatedAt) {
400
+ // If the token already exists, only overwrite it if the old token has a more recent lastUpdatedAt
401
+ await this.setUserData(newKey, JSON.stringify(oldSchemaData), correlationId, oldSchemaData.lastUpdatedAt, kmsi);
402
+ this.performanceClient.incrementFields({ migratedATCount: 1 }, correlationId);
403
+ }
404
+ }
405
+ }
406
+ this.setTokenKeys(credentialKeysToMigrate, correlationId, credentialSchema);
407
+ this.setTokenKeys(currentCredentialKeys, correlationId);
408
+ }
409
+ /**
410
+ * Migrates refresh tokens from old cache schema to current schema
411
+ * @param credentialSchema
412
+ * @param kmsiMap
413
+ * @param correlationId
414
+ * @returns
415
+ */
416
+ async migrateRefreshTokens(credentialSchema, kmsiMap, correlationId) {
417
+ const credentialKeysToMigrate = getTokenKeys(this.clientId, this.browserStorage, credentialSchema);
418
+ if (credentialKeysToMigrate.refreshToken.length === 0) {
419
+ return;
420
+ }
421
+ const currentCredentialKeys = getTokenKeys(this.clientId, this.browserStorage, CREDENTIAL_SCHEMA_VERSION);
422
+ for (const refreshTokenKey of [
423
+ ...credentialKeysToMigrate.refreshToken,
424
+ ]) {
425
+ this.performanceClient.incrementFields({ oldRTCount: 1 }, correlationId);
426
+ const result = await this.updateOldEntry(refreshTokenKey, correlationId);
427
+ const oldSchemaData = result.entry;
428
+ if (!oldSchemaData) {
429
+ switch (result.removalReason) {
430
+ case MigrationRemovalReason.TtlExpired:
431
+ this.performanceClient.incrementFields({ ttlExpiredRTCount: 1 }, correlationId);
432
+ break;
433
+ case MigrationRemovalReason.DecryptFailed:
434
+ this.performanceClient.incrementFields({ decryptFailedRTCount: 1 }, correlationId);
435
+ break;
436
+ case MigrationRemovalReason.Expired:
437
+ this.performanceClient.incrementFields({ expiredRTCount: 1 }, correlationId);
438
+ break;
439
+ case MigrationRemovalReason.Invalid:
440
+ this.performanceClient.incrementFields({ invalidRTCount: 1 }, correlationId);
441
+ break;
442
+ }
443
+ removeElementFromArray(credentialKeysToMigrate.refreshToken, refreshTokenKey);
444
+ continue;
445
+ }
446
+ if (!(oldSchemaData.homeAccountId in kmsiMap)) {
447
+ // Don't migrate tokens if we don't have an idToken for them
448
+ this.performanceClient.incrementFields({ skipRTMigrateCount: 1 }, correlationId);
449
+ continue;
450
+ }
451
+ const newKey = this.generateCredentialKey(oldSchemaData);
452
+ const kmsi = kmsiMap[oldSchemaData.homeAccountId];
453
+ if (!currentCredentialKeys.refreshToken.includes(newKey)) {
454
+ await this.setUserData(newKey, JSON.stringify(oldSchemaData), correlationId, oldSchemaData.lastUpdatedAt, kmsi);
455
+ this.performanceClient.incrementFields({ migratedRTCount: 1 }, correlationId);
456
+ currentCredentialKeys.refreshToken.push(newKey);
457
+ }
458
+ else {
459
+ const currentToken = this.getRefreshTokenCredential(newKey, correlationId);
460
+ if (!currentToken ||
461
+ oldSchemaData.lastUpdatedAt > currentToken.lastUpdatedAt) {
462
+ // If the token already exists, only overwrite it if the old token has a more recent lastUpdatedAt
463
+ await this.setUserData(newKey, JSON.stringify(oldSchemaData), correlationId, oldSchemaData.lastUpdatedAt, kmsi);
464
+ this.performanceClient.incrementFields({ migratedRTCount: 1 }, correlationId);
465
+ }
466
+ }
467
+ }
468
+ this.setTokenKeys(credentialKeysToMigrate, correlationId, credentialSchema);
469
+ this.setTokenKeys(currentCredentialKeys, correlationId);
470
+ }
471
+ /**
472
+ * Tracks upgrades and downgrades for telemetry and debugging purposes
473
+ */
474
+ trackVersionChanges(correlationId) {
475
+ const previousVersion = this.browserStorage.getItem(VERSION_CACHE_KEY);
476
+ if (previousVersion) {
477
+ this.logger.info(`1wuc87 ${previousVersion}`, correlationId);
478
+ this.performanceClient.addGlobalFields({
479
+ previousLibraryVersion: previousVersion,
480
+ });
481
+ }
482
+ if (previousVersion !== version) {
483
+ this.setItem(VERSION_CACHE_KEY, version, correlationId);
484
+ }
485
+ }
486
+ /**
487
+ * Parses passed value as JSON object, JSON.parse() will throw an error.
488
+ * @param input
489
+ */
490
+ validateAndParseJson(jsonValue) {
491
+ if (!jsonValue) {
492
+ return null;
493
+ }
494
+ try {
495
+ const parsedJson = JSON.parse(jsonValue);
496
+ /**
497
+ * There are edge cases in which JSON.parse will successfully parse a non-valid JSON object
498
+ * (e.g. JSON.parse will parse an escaped string into an unescaped string), so adding a type check
499
+ * of the parsed value is necessary in order to be certain that the string represents a valid JSON object.
500
+ *
501
+ */
502
+ return parsedJson && typeof parsedJson === "object"
503
+ ? parsedJson
504
+ : null;
505
+ }
506
+ catch (error) {
507
+ return null;
508
+ }
509
+ }
510
+ /**
511
+ * Helper to setItem in browser storage, with cleanup in case of quota errors
512
+ * @param key
513
+ * @param value
514
+ */
515
+ setItem(key, value, correlationId) {
516
+ const tokenKeysCount = new Array(CREDENTIAL_SCHEMA_VERSION + 1).fill(0); // Array mapping schema version to number of token keys stored for that version
517
+ const accessTokenKeys = []; // Flat map of all access token keys stored, ordered by schema version
518
+ const maxRetries = 20;
519
+ for (let i = 0; i <= maxRetries; i++) {
520
+ // Attempt to store item in cache, if cache is full this call will throw and we'll attempt to clear space by removing access tokens from the cache one by one, starting with tokens stored by previous versions of MSAL.js
521
+ try {
522
+ this.browserStorage.setItem(key, value);
523
+ if (i > 0) {
524
+ // If any tokens were removed in order to store this item update the token keys array with the tokens removed
525
+ for (let schemaVersion = 0; schemaVersion <= CREDENTIAL_SCHEMA_VERSION; schemaVersion++) {
526
+ // Get the sum of all previous token counts to use as start index for this schema version
527
+ const startIndex = tokenKeysCount
528
+ .slice(0, schemaVersion)
529
+ .reduce((sum, count) => sum + count, 0);
530
+ if (startIndex >= i) {
531
+ // Done removing tokens
532
+ break;
533
+ }
534
+ const endIndex = i > startIndex + tokenKeysCount[schemaVersion]
535
+ ? startIndex + tokenKeysCount[schemaVersion]
536
+ : i;
537
+ if (i > startIndex &&
538
+ tokenKeysCount[schemaVersion] > 0) {
539
+ this.removeAccessTokenKeys(accessTokenKeys.slice(startIndex, endIndex), correlationId, schemaVersion);
540
+ }
541
+ }
542
+ }
543
+ break; // If setItem succeeds, exit the loop
544
+ }
545
+ catch (e) {
546
+ const cacheError = createCacheError(e);
547
+ if (cacheError.errorCode ===
548
+ CacheErrorCodes.cacheQuotaExceeded &&
549
+ i < maxRetries) {
550
+ if (!accessTokenKeys.length) {
551
+ // If we are currently trying to set the token keys, use the value we're trying to set
552
+ for (let i = 0; i <= CREDENTIAL_SCHEMA_VERSION; i++) {
553
+ if (key ===
554
+ getTokenKeysCacheKey(this.clientId, i)) {
555
+ const tokenKeys = JSON.parse(value).accessToken;
556
+ accessTokenKeys.push(...tokenKeys);
557
+ tokenKeysCount[i] = tokenKeys.length;
558
+ }
559
+ else {
560
+ const tokenKeys = this.getTokenKeys(i).accessToken;
561
+ accessTokenKeys.push(...tokenKeys);
562
+ tokenKeysCount[i] = tokenKeys.length;
563
+ }
564
+ }
565
+ }
566
+ if (accessTokenKeys.length <= i) {
567
+ // Nothing to remove, rethrow the error
568
+ throw cacheError;
569
+ }
570
+ // When cache quota is exceeded, start removing access tokens until we can successfully set the item
571
+ this.removeAccessToken(accessTokenKeys[i], correlationId, false // Don't save token keys yet, do it at the end
572
+ );
573
+ }
574
+ else {
575
+ // If the error is not a quota exceeded error, rethrow it
576
+ throw cacheError;
577
+ }
578
+ }
579
+ }
580
+ }
581
+ /**
582
+ * Helper to setUserData in browser storage, with cleanup in case of quota errors
583
+ * @param key
584
+ * @param value
585
+ * @param correlationId
586
+ */
587
+ async setUserData(key, value, correlationId, timestamp, kmsi) {
588
+ const tokenKeysCount = new Array(CREDENTIAL_SCHEMA_VERSION + 1).fill(0); // Array mapping schema version to number of token keys stored for that version
589
+ const accessTokenKeys = []; // Flat map of all access token keys stored, ordered by schema version
590
+ const maxRetries = 20;
591
+ for (let i = 0; i <= maxRetries; i++) {
592
+ try {
593
+ // Attempt to store item in cache, if cache is full this call will throw and we'll attempt to clear space by removing access tokens from the cache one by one, starting with tokens stored by previous versions of MSAL.js
594
+ await invokeAsync(this.browserStorage.setUserData.bind(this.browserStorage), PerformanceEvents.SetUserData, this.logger, this.performanceClient, correlationId)(key, value, correlationId, timestamp, kmsi);
595
+ if (i > 0) {
596
+ // If any tokens were removed in order to store this item update the token keys array with the tokens removed
597
+ for (let schemaVersion = 0; schemaVersion <= CREDENTIAL_SCHEMA_VERSION; schemaVersion++) {
598
+ // Get the sum of all previous token counts to use as start index for this schema version
599
+ const startIndex = tokenKeysCount
600
+ .slice(0, schemaVersion)
601
+ .reduce((sum, count) => sum + count, 0);
602
+ if (startIndex >= i) {
603
+ // Done removing tokens
604
+ break;
605
+ }
606
+ const endIndex = i > startIndex + tokenKeysCount[schemaVersion]
607
+ ? startIndex + tokenKeysCount[schemaVersion]
608
+ : i;
609
+ if (i > startIndex &&
610
+ tokenKeysCount[schemaVersion] > 0) {
611
+ this.removeAccessTokenKeys(accessTokenKeys.slice(startIndex, endIndex), correlationId, schemaVersion);
612
+ }
613
+ }
614
+ }
615
+ break; // If setItem succeeds, exit the loop
616
+ }
617
+ catch (e) {
618
+ const cacheError = createCacheError(e);
619
+ if (cacheError.errorCode ===
620
+ CacheErrorCodes.cacheQuotaExceeded &&
621
+ i < maxRetries) {
622
+ if (!accessTokenKeys.length) {
623
+ // If we are currently trying to set the token keys, use the value we're trying to set
624
+ for (let i = 0; i <= CREDENTIAL_SCHEMA_VERSION; i++) {
625
+ const tokenKeys = this.getTokenKeys(i).accessToken;
626
+ accessTokenKeys.push(...tokenKeys);
627
+ tokenKeysCount[i] = tokenKeys.length;
628
+ }
629
+ }
630
+ if (accessTokenKeys.length <= i) {
631
+ // Nothing left to remove, rethrow the error
632
+ throw cacheError;
633
+ }
634
+ // When cache quota is exceeded, start removing access tokens until we can successfully set the item
635
+ this.removeAccessToken(accessTokenKeys[i], correlationId, false // Don't save token keys yet, do it at the end
636
+ );
637
+ }
638
+ else {
639
+ // If the error is not a quota exceeded error, rethrow it
640
+ throw cacheError;
641
+ }
642
+ }
643
+ }
644
+ }
645
+ /**
646
+ * Reads account from cache, deserializes it into an account entity and returns it.
647
+ * If account is not found from the key, returns null and removes key from map.
648
+ * @param accountKey
649
+ * @returns
650
+ */
651
+ getAccount(accountKey, correlationId) {
652
+ this.logger.trace("1lfvm6", correlationId);
653
+ const serializedAccount = this.browserStorage.getUserData(accountKey);
654
+ if (!serializedAccount) {
655
+ this.removeAccountKeyFromMap(accountKey, correlationId);
656
+ return null;
657
+ }
658
+ const parsedAccount = this.validateAndParseJson(serializedAccount);
659
+ if (!parsedAccount ||
660
+ !AccountEntityUtils.isAccountEntity(parsedAccount)) {
661
+ return null;
662
+ }
663
+ const account = CacheManager.toObject({}, parsedAccount);
664
+ this.performanceClient.addFields({
665
+ accountCachedBy: apiIdToName(account.cachedByApiId),
666
+ }, correlationId);
667
+ return account;
668
+ }
669
+ /**
670
+ * set account entity in the platform cache
671
+ * @param account
672
+ */
673
+ async setAccount(account, correlationId, kmsi, apiId) {
674
+ this.logger.trace("1bz3wr", correlationId);
675
+ const key = this.generateAccountKey(AccountEntityUtils.getAccountInfo(account));
676
+ const timestamp = Date.now().toString();
677
+ account.lastUpdatedAt = timestamp;
678
+ account.cachedByApiId = apiId;
679
+ await this.setUserData(key, JSON.stringify(account), correlationId, timestamp, kmsi);
680
+ this.addAccountKeyToMap(key, correlationId);
681
+ this.performanceClient.addFields({ kmsi: kmsi }, correlationId);
682
+ }
683
+ setAccountKeys(accountKeys, correlationId, schemaVersion = ACCOUNT_SCHEMA_VERSION) {
684
+ if (accountKeys.length === 0) {
685
+ this.removeItem(getAccountKeysCacheKey(schemaVersion));
686
+ }
687
+ else {
688
+ this.setItem(getAccountKeysCacheKey(schemaVersion), JSON.stringify(accountKeys), correlationId);
689
+ }
690
+ }
691
+ /**
692
+ * Returns the array of account keys currently cached
693
+ * @returns
694
+ */
695
+ getAccountKeys() {
696
+ return getAccountKeys(this.browserStorage);
697
+ }
698
+ /**
699
+ * Add a new account to the key map
700
+ * @param key
701
+ */
702
+ addAccountKeyToMap(key, correlationId) {
703
+ this.logger.trace("0rb85k", correlationId);
704
+ this.logger.tracePii(`1l9bdo ${key}`, correlationId);
705
+ const accountKeys = this.getAccountKeys();
706
+ if (accountKeys.indexOf(key) === -1) {
707
+ // Only add key if it does not already exist in the map
708
+ accountKeys.push(key);
709
+ this.setItem(getAccountKeysCacheKey(), JSON.stringify(accountKeys), correlationId);
710
+ this.logger.verbose("0xia39", correlationId);
711
+ return true;
712
+ }
713
+ else {
714
+ this.logger.verbose("0161kk", correlationId);
715
+ return false;
716
+ }
717
+ }
718
+ /**
719
+ * Remove an account from the key map
720
+ * @param key
721
+ */
722
+ removeAccountKeyFromMap(key, correlationId) {
723
+ this.logger.trace("1jpigu", correlationId);
724
+ this.logger.tracePii(`1xzspl ${key}`, correlationId);
725
+ const accountKeys = this.getAccountKeys();
726
+ const removalIndex = accountKeys.indexOf(key);
727
+ if (removalIndex > -1) {
728
+ accountKeys.splice(removalIndex, 1);
729
+ this.setAccountKeys(accountKeys, correlationId);
730
+ }
731
+ else {
732
+ this.logger.trace("1dytu2", correlationId);
733
+ }
734
+ }
735
+ /**
736
+ * Extends inherited removeAccount function to include removal of the account key from the map
737
+ * @param key
738
+ */
739
+ removeAccount(account, correlationId) {
740
+ const activeAccount = this.getActiveAccount(correlationId);
741
+ if (activeAccount?.homeAccountId === account.homeAccountId &&
742
+ activeAccount?.environment === account.environment) {
743
+ this.setActiveAccount(null, correlationId);
744
+ }
745
+ super.removeAccount(account, correlationId);
746
+ this.removeAccountKeyFromMap(this.generateAccountKey(account), correlationId);
747
+ // Remove all other associated cache items
748
+ this.browserStorage.getKeys().forEach((key) => {
749
+ if (key.includes(account.homeAccountId) &&
750
+ key.includes(account.environment)) {
751
+ this.browserStorage.removeItem(key);
752
+ }
753
+ });
754
+ }
755
+ /**
756
+ * Removes given idToken from the cache and from the key map
757
+ * @param key
758
+ */
759
+ removeIdToken(key, correlationId) {
760
+ super.removeIdToken(key, correlationId);
761
+ const tokenKeys = this.getTokenKeys();
762
+ const idRemoval = tokenKeys.idToken.indexOf(key);
763
+ if (idRemoval > -1) {
764
+ this.logger.info("05udv9", correlationId);
765
+ tokenKeys.idToken.splice(idRemoval, 1);
766
+ this.setTokenKeys(tokenKeys, correlationId);
767
+ }
768
+ }
769
+ /**
770
+ * Removes given accessToken from the cache and from the key map
771
+ * @param key
772
+ */
773
+ removeAccessToken(key, correlationId, updateTokenKeys = true) {
774
+ super.removeAccessToken(key, correlationId);
775
+ updateTokenKeys && this.removeAccessTokenKeys([key], correlationId);
776
+ }
777
+ /**
778
+ * Remove access token key from the key map
779
+ * @param key
780
+ * @param correlationId
781
+ * @param tokenKeys
782
+ */
783
+ removeAccessTokenKeys(keys, correlationId, schemaVersion = CREDENTIAL_SCHEMA_VERSION) {
784
+ this.logger.trace("17o18n", correlationId);
785
+ const tokenKeys = this.getTokenKeys(schemaVersion);
786
+ let keysRemoved = 0;
787
+ keys.forEach((key) => {
788
+ const accessRemoval = tokenKeys.accessToken.indexOf(key);
789
+ if (accessRemoval > -1) {
790
+ tokenKeys.accessToken.splice(accessRemoval, 1);
791
+ keysRemoved++;
792
+ }
793
+ });
794
+ if (keysRemoved > 0) {
795
+ this.logger.info(`15i5d5 ${keysRemoved}`, correlationId);
796
+ this.setTokenKeys(tokenKeys, correlationId, schemaVersion);
797
+ return;
798
+ }
799
+ }
800
+ /**
801
+ * Removes given refreshToken from the cache and from the key map
802
+ * @param key
803
+ */
804
+ removeRefreshToken(key, correlationId) {
805
+ super.removeRefreshToken(key, correlationId);
806
+ const tokenKeys = this.getTokenKeys();
807
+ const refreshRemoval = tokenKeys.refreshToken.indexOf(key);
808
+ if (refreshRemoval > -1) {
809
+ this.logger.info("1f4fq3", correlationId);
810
+ tokenKeys.refreshToken.splice(refreshRemoval, 1);
811
+ this.setTokenKeys(tokenKeys, correlationId);
812
+ }
813
+ }
814
+ /**
815
+ * Gets the keys for the cached tokens associated with this clientId
816
+ * @returns
817
+ */
818
+ getTokenKeys(schemaVersion = CREDENTIAL_SCHEMA_VERSION) {
819
+ return getTokenKeys(this.clientId, this.browserStorage, schemaVersion);
820
+ }
821
+ /**
822
+ * Sets the token keys in the cache
823
+ * @param tokenKeys
824
+ * @param correlationId
825
+ * @returns
826
+ */
827
+ setTokenKeys(tokenKeys, correlationId, schemaVersion = CREDENTIAL_SCHEMA_VERSION) {
828
+ if (tokenKeys.idToken.length === 0 &&
829
+ tokenKeys.accessToken.length === 0 &&
830
+ tokenKeys.refreshToken.length === 0) {
831
+ // If no keys left, remove the map
832
+ this.removeItem(getTokenKeysCacheKey(this.clientId, schemaVersion));
833
+ return;
834
+ }
835
+ else {
836
+ this.setItem(getTokenKeysCacheKey(this.clientId, schemaVersion), JSON.stringify(tokenKeys), correlationId);
837
+ }
838
+ }
839
+ /**
840
+ * generates idToken entity from a string
841
+ * @param idTokenKey
842
+ */
843
+ getIdTokenCredential(idTokenKey, correlationId) {
844
+ const value = this.browserStorage.getUserData(idTokenKey);
845
+ if (!value) {
846
+ this.logger.trace("1jukz6", correlationId);
847
+ this.removeIdToken(idTokenKey, correlationId);
848
+ return null;
849
+ }
850
+ const parsedIdToken = this.validateAndParseJson(value);
851
+ if (!parsedIdToken || !CacheHelpers.isIdTokenEntity(parsedIdToken)) {
852
+ this.logger.trace("1jukz6", correlationId);
853
+ return null;
854
+ }
855
+ this.logger.trace("01ju66", correlationId);
856
+ return parsedIdToken;
857
+ }
858
+ /**
859
+ * set IdToken credential to the platform cache
860
+ * @param idToken
861
+ */
862
+ async setIdTokenCredential(idToken, correlationId, kmsi) {
863
+ this.logger.trace("13hjll", correlationId);
864
+ const idTokenKey = this.generateCredentialKey(idToken);
865
+ const timestamp = Date.now().toString();
866
+ idToken.lastUpdatedAt = timestamp;
867
+ await this.setUserData(idTokenKey, JSON.stringify(idToken), correlationId, timestamp, kmsi);
868
+ const tokenKeys = this.getTokenKeys();
869
+ if (tokenKeys.idToken.indexOf(idTokenKey) === -1) {
870
+ this.logger.info("07jy92", correlationId);
871
+ tokenKeys.idToken.push(idTokenKey);
872
+ this.setTokenKeys(tokenKeys, correlationId);
873
+ }
874
+ }
875
+ /**
876
+ * generates accessToken entity from a string
877
+ * @param key
878
+ */
879
+ getAccessTokenCredential(accessTokenKey, correlationId) {
880
+ const value = this.browserStorage.getUserData(accessTokenKey);
881
+ if (!value) {
882
+ this.logger.trace("0bqvx8", correlationId);
883
+ this.removeAccessTokenKeys([accessTokenKey], correlationId);
884
+ return null;
885
+ }
886
+ const parsedAccessToken = this.validateAndParseJson(value);
887
+ if (!parsedAccessToken ||
888
+ !CacheHelpers.isAccessTokenEntity(parsedAccessToken)) {
889
+ this.logger.trace("0bqvx8", correlationId);
890
+ return null;
891
+ }
892
+ this.logger.trace("1o81rl", correlationId);
893
+ return parsedAccessToken;
894
+ }
895
+ /**
896
+ * Set accessToken credential to the platform cache
897
+ * @param accessToken - the access token entity to cache
898
+ */
899
+ async setAccessTokenCredential(accessToken, correlationId, kmsi, additionalCacheKeyHash) {
900
+ this.logger.trace("1pondb", correlationId);
901
+ const accessTokenKey = this.generateCredentialKey(accessToken, additionalCacheKeyHash);
902
+ const timestamp = Date.now().toString();
903
+ accessToken.lastUpdatedAt = timestamp;
904
+ await this.setUserData(accessTokenKey, JSON.stringify(accessToken), correlationId, timestamp, kmsi);
905
+ const tokenKeys = this.getTokenKeys();
906
+ const index = tokenKeys.accessToken.indexOf(accessTokenKey);
907
+ if (index !== -1) {
908
+ tokenKeys.accessToken.splice(index, 1); // Remove existing key before pushing to the end
909
+ }
910
+ this.logger.trace(`1onhey ${index === -1 ? "added to" : "updated in"}`, correlationId);
911
+ tokenKeys.accessToken.push(accessTokenKey);
912
+ this.setTokenKeys(tokenKeys, correlationId);
913
+ }
914
+ /**
915
+ * generates refreshToken entity from a string
916
+ * @param refreshTokenKey
917
+ */
918
+ getRefreshTokenCredential(refreshTokenKey, correlationId) {
919
+ const value = this.browserStorage.getUserData(refreshTokenKey);
920
+ if (!value) {
921
+ this.logger.trace("0jlizt", correlationId);
922
+ this.removeRefreshToken(refreshTokenKey, correlationId);
923
+ return null;
924
+ }
925
+ const parsedRefreshToken = this.validateAndParseJson(value);
926
+ if (!parsedRefreshToken ||
927
+ !CacheHelpers.isRefreshTokenEntity(parsedRefreshToken)) {
928
+ this.logger.trace("0jlizt", correlationId);
929
+ return null;
930
+ }
931
+ this.logger.trace("0nokxi", correlationId);
932
+ return parsedRefreshToken;
933
+ }
934
+ /**
935
+ * set refreshToken credential to the platform cache
936
+ * @param refreshToken
937
+ */
938
+ async setRefreshTokenCredential(refreshToken, correlationId, kmsi) {
939
+ this.logger.trace("0tcg8d", correlationId);
940
+ const refreshTokenKey = this.generateCredentialKey(refreshToken);
941
+ const timestamp = Date.now().toString();
942
+ refreshToken.lastUpdatedAt = timestamp;
943
+ await this.setUserData(refreshTokenKey, JSON.stringify(refreshToken), correlationId, timestamp, kmsi);
944
+ const tokenKeys = this.getTokenKeys();
945
+ if (tokenKeys.refreshToken.indexOf(refreshTokenKey) === -1) {
946
+ this.logger.info("0eckjs", correlationId);
947
+ tokenKeys.refreshToken.push(refreshTokenKey);
948
+ this.setTokenKeys(tokenKeys, correlationId);
949
+ }
950
+ }
951
+ /**
952
+ * fetch appMetadata entity from the platform cache
953
+ * @param appMetadataKey
954
+ * @param correlationId
955
+ */
956
+ getAppMetadata(appMetadataKey, correlationId) {
957
+ const value = this.browserStorage.getItem(appMetadataKey);
958
+ if (!value) {
959
+ this.logger.trace("1q101h", correlationId);
960
+ return null;
961
+ }
962
+ const parsedMetadata = this.validateAndParseJson(value);
963
+ if (!parsedMetadata ||
964
+ !CacheHelpers.isAppMetadataEntity(appMetadataKey, parsedMetadata)) {
965
+ this.logger.trace("1q101h", correlationId);
966
+ return null;
967
+ }
968
+ this.logger.trace("19pvg2", correlationId);
969
+ return parsedMetadata;
970
+ }
971
+ /**
972
+ * set appMetadata entity to the platform cache
973
+ * @param appMetadata
974
+ * @param correlationId
975
+ */
976
+ setAppMetadata(appMetadata, correlationId) {
977
+ this.logger.trace("0cyma6", correlationId);
978
+ const appMetadataKey = CacheHelpers.generateAppMetadataKey(appMetadata);
979
+ this.setItem(appMetadataKey, JSON.stringify(appMetadata), correlationId);
980
+ }
981
+ /**
982
+ * fetch server telemetry entity from the platform cache
983
+ * @param serverTelemetryKey
984
+ * @param correlationId
985
+ */
986
+ getServerTelemetry(serverTelemetryKey, correlationId) {
987
+ const value = this.browserStorage.getItem(serverTelemetryKey);
988
+ if (!value) {
989
+ this.logger.trace("0jk19c", correlationId);
990
+ return null;
991
+ }
992
+ const parsedEntity = this.validateAndParseJson(value);
993
+ if (!parsedEntity ||
994
+ !CacheHelpers.isServerTelemetryEntity(serverTelemetryKey, parsedEntity)) {
995
+ this.logger.trace("0jk19c", correlationId);
996
+ return null;
997
+ }
998
+ this.logger.trace("12jguk", correlationId);
999
+ return parsedEntity;
1000
+ }
1001
+ /**
1002
+ * set server telemetry entity to the platform cache
1003
+ * @param serverTelemetryKey
1004
+ * @param serverTelemetry
1005
+ */
1006
+ setServerTelemetry(serverTelemetryKey, serverTelemetry, correlationId) {
1007
+ this.logger.trace("1poh61", correlationId);
1008
+ this.setItem(serverTelemetryKey, JSON.stringify(serverTelemetry), correlationId);
1009
+ }
1010
+ /**
1011
+ *
1012
+ */
1013
+ getAuthorityMetadata(key, correlationId) {
1014
+ const value = this.internalStorage.getItem(key);
1015
+ if (!value) {
1016
+ this.logger.trace("1r39oe", correlationId);
1017
+ return null;
1018
+ }
1019
+ const parsedMetadata = this.validateAndParseJson(value);
1020
+ if (parsedMetadata &&
1021
+ CacheHelpers.isAuthorityMetadataEntity(key, parsedMetadata)) {
1022
+ this.logger.trace("1ohvk3", correlationId);
1023
+ return parsedMetadata;
1024
+ }
1025
+ return null;
1026
+ }
1027
+ /**
1028
+ *
1029
+ */
1030
+ getAuthorityMetadataKeys() {
1031
+ const allKeys = this.internalStorage.getKeys();
1032
+ return allKeys.filter((key) => {
1033
+ return this.isAuthorityMetadata(key);
1034
+ });
1035
+ }
1036
+ /**
1037
+ * Sets wrapper metadata in memory
1038
+ * @param wrapperSKU
1039
+ * @param wrapperVersion
1040
+ */
1041
+ setWrapperMetadata(wrapperSKU, wrapperVersion) {
1042
+ this.internalStorage.setItem(InMemoryCacheKeys.WRAPPER_SKU, wrapperSKU);
1043
+ this.internalStorage.setItem(InMemoryCacheKeys.WRAPPER_VER, wrapperVersion);
1044
+ }
1045
+ /**
1046
+ * Returns wrapper metadata from in-memory storage
1047
+ */
1048
+ getWrapperMetadata() {
1049
+ const sku = this.internalStorage.getItem(InMemoryCacheKeys.WRAPPER_SKU) || "";
1050
+ const version = this.internalStorage.getItem(InMemoryCacheKeys.WRAPPER_VER) || "";
1051
+ return [sku, version];
1052
+ }
1053
+ /**
1054
+ *
1055
+ * @param key
1056
+ * @param entity
1057
+ * @param correlationId
1058
+ */
1059
+ setAuthorityMetadata(key, entity, correlationId) {
1060
+ this.logger.trace("07w8n2", correlationId);
1061
+ this.internalStorage.setItem(key, JSON.stringify(entity));
1062
+ }
1063
+ /**
1064
+ * Gets the active account
1065
+ */
1066
+ getActiveAccount(correlationId) {
1067
+ const activeAccountKeyFilters = this.generateCacheKey(Constants.PersistentCacheKeys.ACTIVE_ACCOUNT_FILTERS);
1068
+ const activeAccountValueFilters = this.browserStorage.getItem(activeAccountKeyFilters);
1069
+ if (!activeAccountValueFilters) {
1070
+ this.logger.trace("08gw0e", correlationId);
1071
+ return null;
1072
+ }
1073
+ const activeAccountValueObj = this.validateAndParseJson(activeAccountValueFilters);
1074
+ if (activeAccountValueObj) {
1075
+ this.logger.trace("1t3ch7", correlationId);
1076
+ return this.getAccountInfoFilteredBy({
1077
+ homeAccountId: activeAccountValueObj.homeAccountId,
1078
+ localAccountId: activeAccountValueObj.localAccountId,
1079
+ tenantId: activeAccountValueObj.tenantId,
1080
+ }, correlationId);
1081
+ }
1082
+ this.logger.trace("0me1up", correlationId);
1083
+ return null;
1084
+ }
1085
+ /**
1086
+ * Sets the active account's localAccountId in cache
1087
+ * @param account
1088
+ */
1089
+ setActiveAccount(account, correlationId) {
1090
+ const activeAccountKey = this.generateCacheKey(Constants.PersistentCacheKeys.ACTIVE_ACCOUNT_FILTERS);
1091
+ if (account) {
1092
+ this.logger.verbose("0rsj80", correlationId);
1093
+ const activeAccountValue = {
1094
+ homeAccountId: account.homeAccountId,
1095
+ localAccountId: account.localAccountId,
1096
+ tenantId: account.tenantId,
1097
+ };
1098
+ this.setItem(activeAccountKey, JSON.stringify(activeAccountValue), correlationId);
1099
+ }
1100
+ else {
1101
+ this.logger.verbose("1bp5z5", correlationId);
1102
+ this.browserStorage.removeItem(activeAccountKey);
1103
+ }
1104
+ this.eventHandler.emitEvent(EventType.ACTIVE_ACCOUNT_CHANGED, correlationId);
1105
+ }
1106
+ /**
1107
+ * fetch throttling entity from the platform cache
1108
+ * @param throttlingCacheKey
1109
+ * @param correlationId
1110
+ */
1111
+ getThrottlingCache(throttlingCacheKey, correlationId) {
1112
+ const value = this.browserStorage.getItem(throttlingCacheKey);
1113
+ if (!value) {
1114
+ this.logger.trace("1h4wa6", correlationId);
1115
+ return null;
1116
+ }
1117
+ const parsedThrottlingCache = this.validateAndParseJson(value);
1118
+ if (!parsedThrottlingCache ||
1119
+ !CacheHelpers.isThrottlingEntity(throttlingCacheKey, parsedThrottlingCache)) {
1120
+ this.logger.trace("1h4wa6", correlationId);
1121
+ return null;
1122
+ }
1123
+ this.logger.trace("0of6n8", correlationId);
1124
+ return parsedThrottlingCache;
1125
+ }
1126
+ /**
1127
+ * set throttling entity to the platform cache
1128
+ * @param throttlingCacheKey
1129
+ * @param throttlingCache
1130
+ */
1131
+ setThrottlingCache(throttlingCacheKey, throttlingCache, correlationId) {
1132
+ this.logger.trace("0wfgh6", correlationId);
1133
+ this.setItem(throttlingCacheKey, JSON.stringify(throttlingCache), correlationId);
1134
+ }
1135
+ /**
1136
+ * Gets cache item with given key.
1137
+ * @param cacheKey
1138
+ * @param correlationId
1139
+ * @param generateKey
1140
+ */
1141
+ getTemporaryCache(cacheKey, correlationId, generateKey) {
1142
+ this.logger.trace("1ordf8", correlationId);
1143
+ const key = generateKey ? this.generateCacheKey(cacheKey) : cacheKey;
1144
+ return this.temporaryCacheStorage.getItem(key);
1145
+ }
1146
+ /**
1147
+ * Sets the cache item with the key and value given.
1148
+ * @param key
1149
+ * @param value
1150
+ */
1151
+ setTemporaryCache(cacheKey, value, generateKey) {
1152
+ const key = generateKey ? this.generateCacheKey(cacheKey) : cacheKey;
1153
+ this.temporaryCacheStorage.setItem(key, value);
1154
+ }
1155
+ /**
1156
+ * Removes the cache item with the given key.
1157
+ * @param key
1158
+ */
1159
+ removeItem(key) {
1160
+ this.browserStorage.removeItem(key);
1161
+ }
1162
+ /**
1163
+ * Removes the temporary cache item with the given key.
1164
+ * @param key
1165
+ */
1166
+ removeTemporaryItem(key) {
1167
+ this.temporaryCacheStorage.removeItem(key);
1168
+ }
1169
+ /**
1170
+ * Gets all keys in window.
1171
+ */
1172
+ getKeys() {
1173
+ return this.browserStorage.getKeys();
1174
+ }
1175
+ /**
1176
+ * Clears all cache entries created by MSAL.
1177
+ */
1178
+ clear(correlationId) {
1179
+ // Removes all accounts and their credentials
1180
+ this.removeAllAccounts(correlationId);
1181
+ this.removeAppMetadata(correlationId);
1182
+ // Remove temp storage first to make sure any cookies are cleared
1183
+ this.temporaryCacheStorage.getKeys().forEach((cacheKey) => {
1184
+ if (cacheKey.indexOf(PREFIX) !== -1 ||
1185
+ cacheKey.indexOf(this.clientId) !== -1) {
1186
+ this.removeTemporaryItem(cacheKey);
1187
+ }
1188
+ });
1189
+ // Removes all remaining MSAL cache items
1190
+ this.browserStorage.getKeys().forEach((cacheKey) => {
1191
+ if (cacheKey.indexOf(PREFIX) !== -1 ||
1192
+ cacheKey.indexOf(this.clientId) !== -1) {
1193
+ this.browserStorage.removeItem(cacheKey);
1194
+ }
1195
+ });
1196
+ this.internalStorage.clear();
1197
+ }
1198
+ /**
1199
+ * Prepend msal.<client-id> to each key
1200
+ * @param key
1201
+ * @param addInstanceId
1202
+ */
1203
+ generateCacheKey(key) {
1204
+ if (StringUtils.startsWith(key, PREFIX)) {
1205
+ return key;
1206
+ }
1207
+ return `${PREFIX}.${this.clientId}.${key}`;
1208
+ }
1209
+ /**
1210
+ * Generate Credential Key. All changes to the key REQUIRE a schema version update.
1211
+ * Cache Key: msal.<schema_version>|<home_account_id>|<environment>|<credential_type>|<client_id or familyId>|<realm>|<scopes>|<scheme>|<additional_cache_key_components_hash>
1212
+ *
1213
+ * @param credentialEntity
1214
+ * @param hash - optional precomputed hash of additionalCacheKeyComponents
1215
+ * @returns
1216
+ */
1217
+ generateCredentialKey(credential, additionalCacheKeyHash) {
1218
+ const familyId = (credential.credentialType ===
1219
+ Constants.CredentialType.REFRESH_TOKEN &&
1220
+ credential.familyId) ||
1221
+ credential.clientId;
1222
+ const scheme = credential.tokenType &&
1223
+ credential.tokenType.toLowerCase() !==
1224
+ Constants.AuthenticationScheme.BEARER.toLowerCase()
1225
+ ? credential.tokenType.toLowerCase()
1226
+ : "";
1227
+ const credentialKey = [
1228
+ `${PREFIX}.${CREDENTIAL_SCHEMA_VERSION}`,
1229
+ credential.homeAccountId,
1230
+ credential.environment,
1231
+ credential.credentialType,
1232
+ familyId,
1233
+ credential.realm || "",
1234
+ credential.target || "",
1235
+ scheme,
1236
+ ];
1237
+ // Append precomputed component-hash segment.
1238
+ if (credential.additionalCacheKeyComponents &&
1239
+ Object.keys(credential.additionalCacheKeyComponents).length > 0 &&
1240
+ additionalCacheKeyHash) {
1241
+ credentialKey.push(additionalCacheKeyHash);
1242
+ }
1243
+ return credentialKey.join(CACHE_KEY_SEPARATOR).toLowerCase();
1244
+ }
1245
+ /**
1246
+ * Cache Key: msal.<schema_version>.<home_account_id>.<environment>.<tenant_id>
1247
+ * @param account
1248
+ * @returns
1249
+ */
1250
+ generateAccountKey(account) {
1251
+ const homeTenantId = account.homeAccountId.split(".")[1];
1252
+ const accountKey = [
1253
+ `${PREFIX}.${ACCOUNT_SCHEMA_VERSION}`,
1254
+ account.homeAccountId,
1255
+ account.environment,
1256
+ homeTenantId || account.tenantId || "",
1257
+ ];
1258
+ return accountKey.join(CACHE_KEY_SEPARATOR).toLowerCase();
1259
+ }
1260
+ /**
1261
+ * Reset all temporary cache items
1262
+ * @param correlationId
1263
+ */
1264
+ resetRequestCache(correlationId) {
1265
+ this.logger.trace("0h0ynu", correlationId);
1266
+ this.removeTemporaryItem(this.generateCacheKey(TemporaryCacheKeys.REQUEST_PARAMS));
1267
+ this.removeTemporaryItem(this.generateCacheKey(TemporaryCacheKeys.VERIFIER));
1268
+ this.removeTemporaryItem(this.generateCacheKey(TemporaryCacheKeys.ORIGIN_URI));
1269
+ this.removeTemporaryItem(this.generateCacheKey(TemporaryCacheKeys.URL_HASH));
1270
+ this.removeTemporaryItem(this.generateCacheKey(TemporaryCacheKeys.NATIVE_REQUEST));
1271
+ this.setInteractionInProgress(false, undefined);
1272
+ }
1273
+ cacheAuthorizeRequest(authCodeRequest, correlationId, codeVerifier) {
1274
+ this.logger.trace("1tzef5", correlationId);
1275
+ const encodedValue = base64Encode(JSON.stringify(authCodeRequest));
1276
+ this.setTemporaryCache(TemporaryCacheKeys.REQUEST_PARAMS, encodedValue, true);
1277
+ if (codeVerifier) {
1278
+ const encodedVerifier = base64Encode(codeVerifier);
1279
+ this.setTemporaryCache(TemporaryCacheKeys.VERIFIER, encodedVerifier, true);
1280
+ }
1281
+ }
1282
+ /**
1283
+ * Gets the token exchange parameters from the cache. Throws an error if nothing is found.
1284
+ * @param correlationId
1285
+ */
1286
+ getCachedRequest(correlationId) {
1287
+ this.logger.trace("0uen20", correlationId);
1288
+ // Get token request from cache and parse as TokenExchangeParameters.
1289
+ const encodedTokenRequest = this.getTemporaryCache(TemporaryCacheKeys.REQUEST_PARAMS, correlationId, true);
1290
+ if (!encodedTokenRequest) {
1291
+ throw createBrowserAuthError(noTokenRequestCacheError, "");
1292
+ }
1293
+ const encodedVerifier = this.getTemporaryCache(TemporaryCacheKeys.VERIFIER, correlationId, true);
1294
+ let parsedRequest;
1295
+ let verifier = "";
1296
+ try {
1297
+ parsedRequest = JSON.parse(base64Decode(encodedTokenRequest));
1298
+ if (encodedVerifier) {
1299
+ verifier = base64Decode(encodedVerifier);
1300
+ }
1301
+ }
1302
+ catch (e) {
1303
+ this.logger.errorPii(`0ewsey ${encodedTokenRequest}`, correlationId);
1304
+ this.logger.error(`0tvdic ${e}`, correlationId);
1305
+ throw createBrowserAuthError(unableToParseTokenRequestCacheError, "");
1306
+ }
1307
+ return [parsedRequest, verifier];
1308
+ }
1309
+ /**
1310
+ * Gets cached native request for redirect flows
1311
+ * @param correlationId
1312
+ */
1313
+ getCachedNativeRequest() {
1314
+ this.logger.trace("1yxcdm", "");
1315
+ const cachedRequest = this.getTemporaryCache(TemporaryCacheKeys.NATIVE_REQUEST, "", true);
1316
+ if (!cachedRequest) {
1317
+ this.logger.trace("0mnxd4", "");
1318
+ return null;
1319
+ }
1320
+ const parsedRequest = this.validateAndParseJson(cachedRequest);
1321
+ if (!parsedRequest) {
1322
+ this.logger.error("0rrkip", "");
1323
+ return null;
1324
+ }
1325
+ return parsedRequest;
1326
+ }
1327
+ isInteractionInProgress(matchClientId) {
1328
+ const clientId = this.getInteractionInProgress()?.clientId;
1329
+ if (matchClientId) {
1330
+ return clientId === this.clientId;
1331
+ }
1332
+ else {
1333
+ return !!clientId;
1334
+ }
1335
+ }
1336
+ getInteractionInProgress() {
1337
+ const key = `${PREFIX}.${TemporaryCacheKeys.INTERACTION_STATUS_KEY}`;
1338
+ const value = this.getTemporaryCache(key, "", false);
1339
+ try {
1340
+ return value ? JSON.parse(value) : null;
1341
+ }
1342
+ catch (e) {
1343
+ // Remove interaction and other temp keys if interaction status can't be parsed
1344
+ this.logger.error("0jjyys", "");
1345
+ this.removeTemporaryItem(key);
1346
+ this.resetRequestCache("");
1347
+ clearHash(window);
1348
+ return null;
1349
+ }
1350
+ }
1351
+ setInteractionInProgress(inProgress, type = INTERACTION_TYPE.SIGNIN, allowOverride = false, correlationId = "") {
1352
+ // Ensure we don't overwrite interaction in progress for a different clientId
1353
+ const key = `${PREFIX}.${TemporaryCacheKeys.INTERACTION_STATUS_KEY}`;
1354
+ if (inProgress) {
1355
+ const existingInteraction = this.getInteractionInProgress();
1356
+ if (existingInteraction) {
1357
+ if (allowOverride) {
1358
+ this.logger.warning(`1pmscr ${existingInteraction.clientId} ${existingInteraction.type}`, correlationId);
1359
+ // Cancel any active bridge monitor from the previous interaction
1360
+ cancelPendingBridgeResponse(this.logger, correlationId);
1361
+ // Clear existing interaction to allow new one
1362
+ this.removeTemporaryItem(key);
1363
+ }
1364
+ else {
1365
+ throw createBrowserAuthError(interactionInProgress, "");
1366
+ }
1367
+ }
1368
+ // Set new interaction
1369
+ this.setTemporaryCache(key, JSON.stringify({ clientId: this.clientId, type }), false);
1370
+ }
1371
+ else if (!inProgress &&
1372
+ this.getInteractionInProgress()?.clientId === this.clientId) {
1373
+ this.removeTemporaryItem(key);
1374
+ }
1375
+ }
1376
+ /**
1377
+ * Builds credential entities from AuthenticationResult object and saves the resulting credentials to the cache
1378
+ * @param result
1379
+ * @param request
1380
+ */
1381
+ async hydrateCache(result, request) {
1382
+ const idTokenEntity = CacheHelpers.createIdTokenEntity(result.account.homeAccountId, result.account.environment, result.idToken, this.clientId, result.tenantId);
1383
+ /**
1384
+ * meta data for cache stores time in seconds from epoch
1385
+ * AuthenticationResult returns expiresOn and extExpiresOn in milliseconds (as a Date object which is in ms)
1386
+ * We need to map these for the cache when building tokens from AuthenticationResult
1387
+ *
1388
+ * The next MSAL VFuture should map these both to same value if possible
1389
+ */
1390
+ const accessTokenEntity = CacheHelpers.createAccessTokenEntity(result.account.homeAccountId, result.account.environment, result.accessToken, this.clientId, result.tenantId, result.scopes.join(" "),
1391
+ // Access token expiresOn stored in seconds, converting from AuthenticationResult expiresOn stored as Date
1392
+ result.expiresOn
1393
+ ? TimeUtils.toSecondsFromDate(result.expiresOn)
1394
+ : 0, result.extExpiresOn
1395
+ ? TimeUtils.toSecondsFromDate(result.extExpiresOn)
1396
+ : 0, base64Decode, request.correlationId || "", undefined, // refreshOn
1397
+ result.tokenType, undefined, // userAssertionHash
1398
+ request.sshKid);
1399
+ if (request.resource) {
1400
+ accessTokenEntity.resource = request.resource;
1401
+ }
1402
+ const cacheRecord = {
1403
+ idToken: idTokenEntity,
1404
+ accessToken: accessTokenEntity,
1405
+ };
1406
+ return this.saveCacheRecord(cacheRecord, result.correlationId, AuthToken.isKmsi(AuthToken.extractTokenClaims(result.idToken, base64Decode, result.correlationId)), ApiId.hydrateCache);
1407
+ }
1408
+ /**
1409
+ * saves a cache record
1410
+ * @param cacheRecord {CacheRecord}
1411
+ * @param storeInCache {?StoreInCache}
1412
+ * @param correlationId {?string} correlation id
1413
+ */
1414
+ async saveCacheRecord(cacheRecord, correlationId, kmsi, apiId, storeInCache) {
1415
+ try {
1416
+ await super.saveCacheRecord(cacheRecord, correlationId, kmsi, apiId, storeInCache);
1417
+ }
1418
+ catch (e) {
1419
+ if (e instanceof CacheError &&
1420
+ this.performanceClient &&
1421
+ correlationId) {
1422
+ try {
1423
+ const tokenKeys = this.getTokenKeys();
1424
+ this.performanceClient.addFields({
1425
+ cacheRtCount: tokenKeys.refreshToken.length,
1426
+ cacheIdCount: tokenKeys.idToken.length,
1427
+ cacheAtCount: tokenKeys.accessToken.length,
1428
+ }, correlationId);
1429
+ }
1430
+ catch (e) { }
1431
+ }
1432
+ throw e;
1433
+ }
1434
+ }
1435
+ }
1436
+ /**
1437
+ * Returns a window storage class implementing the IWindowStorage interface that corresponds to the configured cacheLocation.
1438
+ * @param cacheLocation
1439
+ */
1440
+ function getStorageImplementation(clientId, cacheLocation, logger, performanceClient) {
1441
+ try {
1442
+ switch (cacheLocation) {
1443
+ case BrowserCacheLocation.LocalStorage:
1444
+ return new LocalStorage(clientId, logger, performanceClient);
1445
+ case BrowserCacheLocation.SessionStorage:
1446
+ return new SessionStorage();
1447
+ case BrowserCacheLocation.MemoryStorage:
1448
+ default:
1449
+ break;
1450
+ }
1451
+ }
1452
+ catch (e) {
1453
+ logger.error(e, "");
1454
+ }
1455
+ return new MemoryStorage();
1456
+ }
1457
+ const DEFAULT_BROWSER_CACHE_MANAGER = (clientId, logger, performanceClient, eventHandler, staticAuthorityOptions, tokenBindingKeyManager = DEFAULT_TOKEN_BINDING_KEY_MANAGER) => {
1458
+ const cacheOptions = {
1459
+ cacheLocation: BrowserCacheLocation.MemoryStorage,
1460
+ cacheRetentionDays: 5,
1461
+ };
1462
+ return new BrowserCacheManager(clientId, cacheOptions, DEFAULT_CRYPTO_IMPLEMENTATION, logger, performanceClient, eventHandler, staticAuthorityOptions, tokenBindingKeyManager);
1463
+ };
1464
+
1465
+ export { BrowserCacheManager, DEFAULT_BROWSER_CACHE_MANAGER };