@azure/msal-browser 3.20.0 → 3.22.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 (187) hide show
  1. package/dist/app/IPublicClientApplication.d.ts +53 -53
  2. package/dist/app/IPublicClientApplication.mjs +105 -105
  3. package/dist/app/PublicClientApplication.d.ts +293 -293
  4. package/dist/app/PublicClientApplication.mjs +364 -364
  5. package/dist/app/PublicClientNext.d.ts +276 -276
  6. package/dist/app/PublicClientNext.mjs +354 -354
  7. package/dist/broker/nativeBroker/NativeMessageHandler.d.ts +62 -62
  8. package/dist/broker/nativeBroker/NativeMessageHandler.mjs +254 -254
  9. package/dist/broker/nativeBroker/NativeRequest.d.ts +45 -45
  10. package/dist/broker/nativeBroker/NativeResponse.d.ts +48 -48
  11. package/dist/broker/nativeBroker/NativeStatusCodes.d.ts +7 -7
  12. package/dist/broker/nativeBroker/NativeStatusCodes.mjs +11 -11
  13. package/dist/cache/AccountManager.d.ts +48 -48
  14. package/dist/cache/AccountManager.mjs +126 -126
  15. package/dist/cache/AsyncMemoryStorage.d.ts +50 -50
  16. package/dist/cache/AsyncMemoryStorage.mjs +131 -131
  17. package/dist/cache/BrowserCacheManager.d.ts +385 -385
  18. package/dist/cache/BrowserCacheManager.mjs +1294 -1294
  19. package/dist/cache/BrowserStorage.d.ts +11 -11
  20. package/dist/cache/BrowserStorage.mjs +32 -32
  21. package/dist/cache/DatabaseStorage.d.ts +56 -56
  22. package/dist/cache/DatabaseStorage.mjs +200 -200
  23. package/dist/cache/IAsyncStorage.d.ts +27 -27
  24. package/dist/cache/ITokenCache.d.ts +11 -11
  25. package/dist/cache/IWindowStorage.d.ts +27 -27
  26. package/dist/cache/MemoryStorage.d.ts +11 -11
  27. package/dist/cache/MemoryStorage.mjs +31 -31
  28. package/dist/cache/TokenCache.d.ts +77 -77
  29. package/dist/cache/TokenCache.mjs +195 -195
  30. package/dist/config/Configuration.d.ts +213 -208
  31. package/dist/config/Configuration.d.ts.map +1 -1
  32. package/dist/config/Configuration.mjs +128 -128
  33. package/dist/config/Configuration.mjs.map +1 -1
  34. package/dist/controllers/ControllerFactory.d.ts +5 -5
  35. package/dist/controllers/ControllerFactory.mjs +25 -25
  36. package/dist/controllers/IController.d.ts +60 -60
  37. package/dist/controllers/NestedAppAuthController.d.ts +202 -202
  38. package/dist/controllers/NestedAppAuthController.mjs +473 -473
  39. package/dist/controllers/StandardController.d.ts +405 -405
  40. package/dist/controllers/StandardController.d.ts.map +1 -1
  41. package/dist/controllers/StandardController.mjs +1334 -1316
  42. package/dist/controllers/StandardController.mjs.map +1 -1
  43. package/dist/controllers/UnknownOperatingContextController.d.ts +86 -86
  44. package/dist/controllers/UnknownOperatingContextController.mjs +256 -256
  45. package/dist/crypto/BrowserCrypto.d.ts +52 -52
  46. package/dist/crypto/BrowserCrypto.mjs +151 -151
  47. package/dist/crypto/CryptoOps.d.ts +74 -74
  48. package/dist/crypto/CryptoOps.mjs +176 -176
  49. package/dist/crypto/PkceGenerator.d.ts +8 -8
  50. package/dist/crypto/PkceGenerator.mjs +54 -54
  51. package/dist/crypto/SignedHttpRequest.d.ts +30 -30
  52. package/dist/crypto/SignedHttpRequest.mjs +39 -39
  53. package/dist/encode/Base64Decode.d.ts +9 -9
  54. package/dist/encode/Base64Decode.mjs +36 -36
  55. package/dist/encode/Base64Encode.d.ts +19 -19
  56. package/dist/encode/Base64Encode.mjs +43 -43
  57. package/dist/error/BrowserAuthError.d.ts +255 -255
  58. package/dist/error/BrowserAuthError.mjs +263 -263
  59. package/dist/error/BrowserAuthErrorCodes.d.ts +46 -46
  60. package/dist/error/BrowserAuthErrorCodes.mjs +50 -50
  61. package/dist/error/BrowserConfigurationAuthError.d.ts +33 -33
  62. package/dist/error/BrowserConfigurationAuthError.mjs +40 -40
  63. package/dist/error/BrowserConfigurationAuthError.mjs.map +1 -1
  64. package/dist/error/BrowserConfigurationAuthErrorCodes.d.ts +3 -3
  65. package/dist/error/BrowserConfigurationAuthErrorCodes.mjs +7 -7
  66. package/dist/error/NativeAuthError.d.ts +29 -29
  67. package/dist/error/NativeAuthError.mjs +60 -60
  68. package/dist/error/NativeAuthErrorCodes.d.ts +2 -2
  69. package/dist/error/NativeAuthErrorCodes.mjs +6 -6
  70. package/dist/error/NestedAppAuthError.d.ts +14 -14
  71. package/dist/error/NestedAppAuthError.mjs +23 -23
  72. package/dist/event/EventHandler.d.ts +41 -41
  73. package/dist/event/EventHandler.mjs +125 -125
  74. package/dist/event/EventMessage.d.ts +25 -25
  75. package/dist/event/EventMessage.mjs +68 -68
  76. package/dist/event/EventType.d.ts +29 -29
  77. package/dist/event/EventType.mjs +32 -32
  78. package/dist/index.d.ts +40 -40
  79. package/dist/index.mjs +1 -1
  80. package/dist/interaction_client/BaseInteractionClient.d.ts +50 -50
  81. package/dist/interaction_client/BaseInteractionClient.mjs +106 -106
  82. package/dist/interaction_client/HybridSpaAuthorizationCodeClient.d.ts +4 -4
  83. package/dist/interaction_client/HybridSpaAuthorizationCodeClient.mjs +10 -10
  84. package/dist/interaction_client/NativeInteractionClient.d.ts +151 -151
  85. package/dist/interaction_client/NativeInteractionClient.mjs +621 -621
  86. package/dist/interaction_client/PopupClient.d.ts +105 -105
  87. package/dist/interaction_client/PopupClient.d.ts.map +1 -1
  88. package/dist/interaction_client/PopupClient.mjs +433 -433
  89. package/dist/interaction_client/PopupClient.mjs.map +1 -1
  90. package/dist/interaction_client/RedirectClient.d.ts +50 -50
  91. package/dist/interaction_client/RedirectClient.d.ts.map +1 -1
  92. package/dist/interaction_client/RedirectClient.mjs +315 -314
  93. package/dist/interaction_client/RedirectClient.mjs.map +1 -1
  94. package/dist/interaction_client/SilentAuthCodeClient.d.ts +23 -23
  95. package/dist/interaction_client/SilentAuthCodeClient.mjs +57 -57
  96. package/dist/interaction_client/SilentCacheClient.d.ts +16 -16
  97. package/dist/interaction_client/SilentCacheClient.mjs +42 -42
  98. package/dist/interaction_client/SilentIframeClient.d.ts +32 -32
  99. package/dist/interaction_client/SilentIframeClient.d.ts.map +1 -1
  100. package/dist/interaction_client/SilentIframeClient.mjs +110 -100
  101. package/dist/interaction_client/SilentIframeClient.mjs.map +1 -1
  102. package/dist/interaction_client/SilentRefreshClient.d.ts +20 -20
  103. package/dist/interaction_client/SilentRefreshClient.mjs +47 -47
  104. package/dist/interaction_client/StandardInteractionClient.d.ts +48 -48
  105. package/dist/interaction_client/StandardInteractionClient.mjs +199 -199
  106. package/dist/interaction_handler/InteractionHandler.d.ts +33 -33
  107. package/dist/interaction_handler/InteractionHandler.mjs +93 -93
  108. package/dist/interaction_handler/RedirectHandler.d.ts +32 -32
  109. package/dist/interaction_handler/RedirectHandler.mjs +134 -134
  110. package/dist/interaction_handler/SilentHandler.d.ts +13 -13
  111. package/dist/interaction_handler/SilentHandler.mjs +134 -134
  112. package/dist/naa/AccountInfo.d.ts +11 -11
  113. package/dist/naa/AuthBridge.d.ts +8 -8
  114. package/dist/naa/AuthResult.d.ts +6 -6
  115. package/dist/naa/BridgeAccountContext.d.ts +12 -12
  116. package/dist/naa/BridgeCapabilities.d.ts +3 -3
  117. package/dist/naa/BridgeError.d.ts +9 -9
  118. package/dist/naa/BridgeError.mjs +7 -7
  119. package/dist/naa/BridgeProxy.d.ts +67 -67
  120. package/dist/naa/BridgeProxy.mjs +148 -148
  121. package/dist/naa/BridgeRequest.d.ts +7 -7
  122. package/dist/naa/BridgeRequestEnvelope.d.ts +12 -12
  123. package/dist/naa/BridgeResponseEnvelope.d.ts +13 -13
  124. package/dist/naa/BridgeStatusCode.d.ts +11 -11
  125. package/dist/naa/BridgeStatusCode.mjs +14 -14
  126. package/dist/naa/IBridgeProxy.d.ts +10 -10
  127. package/dist/naa/InitContext.d.ts +8 -8
  128. package/dist/naa/TokenRequest.d.ts +18 -18
  129. package/dist/naa/TokenResponse.d.ts +13 -13
  130. package/dist/naa/mapping/NestedAppAuthAdapter.d.ts +35 -35
  131. package/dist/naa/mapping/NestedAppAuthAdapter.mjs +179 -179
  132. package/dist/navigation/INavigationClient.d.ts +16 -16
  133. package/dist/navigation/NavigationClient.d.ts +22 -22
  134. package/dist/navigation/NavigationClient.mjs +40 -40
  135. package/dist/navigation/NavigationOptions.d.ts +12 -12
  136. package/dist/network/FetchClient.d.ts +26 -26
  137. package/dist/network/FetchClient.mjs +99 -99
  138. package/dist/operatingcontext/BaseOperatingContext.d.ts +41 -41
  139. package/dist/operatingcontext/BaseOperatingContext.mjs +94 -94
  140. package/dist/operatingcontext/NestedAppOperatingContext.d.ts +34 -34
  141. package/dist/operatingcontext/NestedAppOperatingContext.mjs +71 -71
  142. package/dist/operatingcontext/StandardOperatingContext.d.ts +25 -25
  143. package/dist/operatingcontext/StandardOperatingContext.mjs +43 -43
  144. package/dist/operatingcontext/UnknownOperatingContext.d.ts +25 -25
  145. package/dist/operatingcontext/UnknownOperatingContext.mjs +42 -42
  146. package/dist/packageMetadata.d.ts +2 -2
  147. package/dist/packageMetadata.mjs +4 -4
  148. package/dist/request/AuthorizationCodeRequest.d.ts +8 -8
  149. package/dist/request/AuthorizationUrlRequest.d.ts +8 -8
  150. package/dist/request/ClearCacheRequest.d.ts +10 -10
  151. package/dist/request/EndSessionPopupRequest.d.ts +18 -18
  152. package/dist/request/EndSessionRequest.d.ts +15 -15
  153. package/dist/request/InitializeApplicationRequest.d.ts +8 -8
  154. package/dist/request/PopupRequest.d.ts +34 -34
  155. package/dist/request/PopupWindowAttributes.d.ts +15 -15
  156. package/dist/request/RedirectRequest.d.ts +40 -35
  157. package/dist/request/RedirectRequest.d.ts.map +1 -1
  158. package/dist/request/RequestHelpers.d.ts +13 -13
  159. package/dist/request/RequestHelpers.mjs +53 -53
  160. package/dist/request/SilentRequest.d.ts +33 -33
  161. package/dist/request/SsoSilentRequest.d.ts +29 -29
  162. package/dist/response/AuthenticationResult.d.ts +4 -4
  163. package/dist/response/ResponseHandler.d.ts +7 -7
  164. package/dist/response/ResponseHandler.mjs +36 -36
  165. package/dist/telemetry/BrowserPerformanceClient.d.ts +34 -34
  166. package/dist/telemetry/BrowserPerformanceClient.mjs +162 -162
  167. package/dist/telemetry/BrowserPerformanceMeasurement.d.ts +21 -21
  168. package/dist/telemetry/BrowserPerformanceMeasurement.mjs +92 -92
  169. package/dist/utils/BrowserConstants.d.ts +180 -180
  170. package/dist/utils/BrowserConstants.mjs +212 -212
  171. package/dist/utils/BrowserProtocolUtils.d.ts +11 -11
  172. package/dist/utils/BrowserProtocolUtils.mjs +21 -21
  173. package/dist/utils/BrowserUtils.d.ts +75 -75
  174. package/dist/utils/BrowserUtils.mjs +157 -157
  175. package/lib/msal-browser.cjs +18884 -18855
  176. package/lib/msal-browser.cjs.map +1 -1
  177. package/lib/msal-browser.js +18884 -18855
  178. package/lib/msal-browser.js.map +1 -1
  179. package/lib/msal-browser.min.js +59 -59
  180. package/package.json +2 -2
  181. package/src/config/Configuration.ts +9 -1
  182. package/src/controllers/StandardController.ts +30 -12
  183. package/src/interaction_client/PopupClient.ts +1 -0
  184. package/src/interaction_client/RedirectClient.ts +4 -1
  185. package/src/interaction_client/SilentIframeClient.ts +40 -3
  186. package/src/packageMetadata.ts +1 -1
  187. package/src/request/RedirectRequest.ts +5 -0
@@ -1,4 +1,4 @@
1
- /*! @azure/msal-browser v3.20.0 2024-07-23 */
1
+ /*! @azure/msal-browser v3.22.0 2024-08-28 */
2
2
  'use strict';
3
3
  import { ServerTelemetryManager, AADServerParamKeys, PerformanceEvents, TimeUtils, ScopeSet, createClientAuthError, ClientAuthErrorCodes, AuthToken, buildAccountToCache, AccountEntity, Constants, AuthorityType, AuthenticationScheme, PopTokenGenerator, updateAccountTenantProfileData, CacheHelpers, createAuthError, AuthErrorCodes, UrlString, OIDC_DEFAULT_SCOPES, invokeAsync, PromptValue } from '@azure/msal-common';
4
4
  import { BaseInteractionClient } from './BaseInteractionClient.mjs';
@@ -11,626 +11,626 @@ import { version } from '../packageMetadata.mjs';
11
11
  import { invalidPopTokenRequest, nativePromptNotSupported } from '../error/BrowserAuthErrorCodes.mjs';
12
12
  import { userSwitch } from '../error/NativeAuthErrorCodes.mjs';
13
13
 
14
- /*
15
- * Copyright (c) Microsoft Corporation. All rights reserved.
16
- * Licensed under the MIT License.
17
- */
18
- const BrokerServerParamKeys = {
19
- BROKER_CLIENT_ID: "brk_client_id",
20
- BROKER_REDIRECT_URI: "brk_redirect_uri",
21
- };
22
- class NativeInteractionClient extends BaseInteractionClient {
23
- constructor(config, browserStorage, browserCrypto, logger, eventHandler, navigationClient, apiId, performanceClient, provider, accountId, nativeStorageImpl, correlationId) {
24
- super(config, browserStorage, browserCrypto, logger, eventHandler, navigationClient, performanceClient, provider, correlationId);
25
- this.apiId = apiId;
26
- this.accountId = accountId;
27
- this.nativeMessageHandler = provider;
28
- this.nativeStorageManager = nativeStorageImpl;
29
- this.silentCacheClient = new SilentCacheClient(config, this.nativeStorageManager, browserCrypto, logger, eventHandler, navigationClient, performanceClient, provider, correlationId);
30
- this.serverTelemetryManager = this.initializeServerTelemetryManager(this.apiId);
31
- const extensionName = this.nativeMessageHandler.getExtensionId() ===
32
- NativeConstants.PREFERRED_EXTENSION_ID
33
- ? "chrome"
34
- : this.nativeMessageHandler.getExtensionId()?.length
35
- ? "unknown"
36
- : undefined;
37
- this.skus = ServerTelemetryManager.makeExtraSkuString({
38
- libraryName: BrowserConstants.MSAL_SKU,
39
- libraryVersion: version,
40
- extensionName: extensionName,
41
- extensionVersion: this.nativeMessageHandler.getExtensionVersion(),
42
- });
43
- }
44
- /**
45
- * Adds SKUs to request extra query parameters
46
- * @param request {NativeTokenRequest}
47
- * @private
48
- */
49
- addRequestSKUs(request) {
50
- request.extraParameters = {
51
- ...request.extraParameters,
52
- [AADServerParamKeys.X_CLIENT_EXTRA_SKU]: this.skus,
53
- };
54
- }
55
- /**
56
- * Acquire token from native platform via browser extension
57
- * @param request
58
- */
59
- async acquireToken(request) {
60
- this.performanceClient.addQueueMeasurement(PerformanceEvents.NativeInteractionClientAcquireToken, request.correlationId);
61
- this.logger.trace("NativeInteractionClient - acquireToken called.");
62
- // start the perf measurement
63
- const nativeATMeasurement = this.performanceClient.startMeasurement(PerformanceEvents.NativeInteractionClientAcquireToken, request.correlationId);
64
- const reqTimestamp = TimeUtils.nowSeconds();
65
- try {
66
- // initialize native request
67
- const nativeRequest = await this.initializeNativeRequest(request);
68
- // check if the tokens can be retrieved from internal cache
69
- try {
70
- const result = await this.acquireTokensFromCache(this.accountId, nativeRequest);
71
- nativeATMeasurement.end({
72
- success: true,
73
- isNativeBroker: false,
74
- fromCache: true,
75
- });
76
- return result;
77
- }
78
- catch (e) {
79
- // continue with a native call for any and all errors
80
- this.logger.info("MSAL internal Cache does not contain tokens, proceed to make a native call");
81
- }
82
- const { ...nativeTokenRequest } = nativeRequest;
83
- // fall back to native calls
84
- const messageBody = {
85
- method: NativeExtensionMethod.GetToken,
86
- request: nativeTokenRequest,
87
- };
88
- const response = await this.nativeMessageHandler.sendMessage(messageBody);
89
- const validatedResponse = this.validateNativeResponse(response);
90
- return await this.handleNativeResponse(validatedResponse, nativeRequest, reqTimestamp)
91
- .then((result) => {
92
- nativeATMeasurement.end({
93
- success: true,
94
- isNativeBroker: true,
95
- requestId: result.requestId,
96
- });
97
- this.serverTelemetryManager.clearNativeBrokerErrorCode();
98
- return result;
99
- })
100
- .catch((error) => {
101
- nativeATMeasurement.end({
102
- success: false,
103
- errorCode: error.errorCode,
104
- subErrorCode: error.subError,
105
- isNativeBroker: true,
106
- });
107
- throw error;
108
- });
109
- }
110
- catch (e) {
111
- if (e instanceof NativeAuthError) {
112
- this.serverTelemetryManager.setNativeBrokerErrorCode(e.errorCode);
113
- }
114
- throw e;
115
- }
116
- }
117
- /**
118
- * Creates silent flow request
119
- * @param request
120
- * @param cachedAccount
121
- * @returns CommonSilentFlowRequest
122
- */
123
- createSilentCacheRequest(request, cachedAccount) {
124
- return {
125
- authority: request.authority,
126
- correlationId: this.correlationId,
127
- scopes: ScopeSet.fromString(request.scope).asArray(),
128
- account: cachedAccount,
129
- forceRefresh: false,
130
- };
131
- }
132
- /**
133
- * Fetches the tokens from the cache if un-expired
134
- * @param nativeAccountId
135
- * @param request
136
- * @returns authenticationResult
137
- */
138
- async acquireTokensFromCache(nativeAccountId, request) {
139
- if (!nativeAccountId) {
140
- this.logger.warning("NativeInteractionClient:acquireTokensFromCache - No nativeAccountId provided");
141
- throw createClientAuthError(ClientAuthErrorCodes.noAccountFound);
142
- }
143
- // fetch the account from browser cache
144
- const account = this.browserStorage.getBaseAccountInfo({
145
- nativeAccountId,
146
- });
147
- if (!account) {
148
- throw createClientAuthError(ClientAuthErrorCodes.noAccountFound);
149
- }
150
- // leverage silent flow for cached tokens retrieval
151
- try {
152
- const silentRequest = this.createSilentCacheRequest(request, account);
153
- const result = await this.silentCacheClient.acquireToken(silentRequest);
154
- const fullAccount = {
155
- ...account,
156
- idTokenClaims: result?.idTokenClaims,
157
- idToken: result?.idToken,
158
- };
159
- return {
160
- ...result,
161
- account: fullAccount,
162
- };
163
- }
164
- catch (e) {
165
- throw e;
166
- }
167
- }
168
- /**
169
- * Acquires a token from native platform then redirects to the redirectUri instead of returning the response
170
- * @param {RedirectRequest} request
171
- * @param {InProgressPerformanceEvent} rootMeasurement
172
- */
173
- async acquireTokenRedirect(request, rootMeasurement) {
174
- this.logger.trace("NativeInteractionClient - acquireTokenRedirect called.");
175
- const { ...remainingParameters } = request;
176
- delete remainingParameters.onRedirectNavigate;
177
- const nativeRequest = await this.initializeNativeRequest(remainingParameters);
178
- const messageBody = {
179
- method: NativeExtensionMethod.GetToken,
180
- request: nativeRequest,
181
- };
182
- try {
183
- const response = await this.nativeMessageHandler.sendMessage(messageBody);
184
- this.validateNativeResponse(response);
185
- }
186
- catch (e) {
187
- // Only throw fatal errors here to allow application to fallback to regular redirect. Otherwise proceed and the error will be thrown in handleRedirectPromise
188
- if (e instanceof NativeAuthError) {
189
- this.serverTelemetryManager.setNativeBrokerErrorCode(e.errorCode);
190
- if (isFatalNativeAuthError(e)) {
191
- throw e;
192
- }
193
- }
194
- }
195
- this.browserStorage.setTemporaryCache(TemporaryCacheKeys.NATIVE_REQUEST, JSON.stringify(nativeRequest), true);
196
- const navigationOptions = {
197
- apiId: ApiId.acquireTokenRedirect,
198
- timeout: this.config.system.redirectNavigationTimeout,
199
- noHistory: false,
200
- };
201
- const redirectUri = this.config.auth.navigateToLoginRequestUrl
202
- ? window.location.href
203
- : this.getRedirectUri(request.redirectUri);
204
- rootMeasurement.end({ success: true });
205
- await this.navigationClient.navigateExternal(redirectUri, navigationOptions); // Need to treat this as external to ensure handleRedirectPromise is run again
206
- }
207
- /**
208
- * If the previous page called native platform for a token using redirect APIs, send the same request again and return the response
209
- * @param performanceClient {IPerformanceClient?}
210
- * @param correlationId {string?} correlation identifier
211
- */
212
- async handleRedirectPromise(performanceClient, correlationId) {
213
- this.logger.trace("NativeInteractionClient - handleRedirectPromise called.");
214
- if (!this.browserStorage.isInteractionInProgress(true)) {
215
- this.logger.info("handleRedirectPromise called but there is no interaction in progress, returning null.");
216
- return null;
217
- }
218
- // remove prompt from the request to prevent WAM from prompting twice
219
- const cachedRequest = this.browserStorage.getCachedNativeRequest();
220
- if (!cachedRequest) {
221
- this.logger.verbose("NativeInteractionClient - handleRedirectPromise called but there is no cached request, returning null.");
222
- if (performanceClient && correlationId) {
223
- performanceClient?.addFields({ errorCode: "no_cached_request" }, correlationId);
224
- }
225
- return null;
226
- }
227
- const { prompt, ...request } = cachedRequest;
228
- if (prompt) {
229
- this.logger.verbose("NativeInteractionClient - handleRedirectPromise called and prompt was included in the original request, removing prompt from cached request to prevent second interaction with native broker window.");
230
- }
231
- this.browserStorage.removeItem(this.browserStorage.generateCacheKey(TemporaryCacheKeys.NATIVE_REQUEST));
232
- const messageBody = {
233
- method: NativeExtensionMethod.GetToken,
234
- request: request,
235
- };
236
- const reqTimestamp = TimeUtils.nowSeconds();
237
- try {
238
- this.logger.verbose("NativeInteractionClient - handleRedirectPromise sending message to native broker.");
239
- const response = await this.nativeMessageHandler.sendMessage(messageBody);
240
- this.validateNativeResponse(response);
241
- const result = this.handleNativeResponse(response, request, reqTimestamp);
242
- this.browserStorage.setInteractionInProgress(false);
243
- const res = await result;
244
- this.serverTelemetryManager.clearNativeBrokerErrorCode();
245
- return res;
246
- }
247
- catch (e) {
248
- this.browserStorage.setInteractionInProgress(false);
249
- throw e;
250
- }
251
- }
252
- /**
253
- * Logout from native platform via browser extension
254
- * @param request
255
- */
256
- logout() {
257
- this.logger.trace("NativeInteractionClient - logout called.");
258
- return Promise.reject("Logout not implemented yet");
259
- }
260
- /**
261
- * Transform response from native platform into AuthenticationResult object which will be returned to the end user
262
- * @param response
263
- * @param request
264
- * @param reqTimestamp
265
- */
266
- async handleNativeResponse(response, request, reqTimestamp) {
267
- this.logger.trace("NativeInteractionClient - handleNativeResponse called.");
268
- // generate identifiers
269
- const idTokenClaims = AuthToken.extractTokenClaims(response.id_token, base64Decode);
270
- const homeAccountIdentifier = this.createHomeAccountIdentifier(response, idTokenClaims);
271
- const cachedhomeAccountId = this.browserStorage.getAccountInfoFilteredBy({
272
- nativeAccountId: request.accountId,
273
- })?.homeAccountId;
274
- if (homeAccountIdentifier !== cachedhomeAccountId &&
275
- response.account.id !== request.accountId) {
276
- // User switch in native broker prompt is not supported. All users must first sign in through web flow to ensure server state is in sync
277
- throw createNativeAuthError(userSwitch);
278
- }
279
- // Get the preferred_cache domain for the given authority
280
- const authority = await this.getDiscoveredAuthority(request.authority);
281
- const baseAccount = buildAccountToCache(this.browserStorage, authority, homeAccountIdentifier, base64Decode, idTokenClaims, response.client_info, undefined, // environment
282
- idTokenClaims.tid, undefined, // auth code payload
283
- response.account.id, this.logger);
284
- // generate authenticationResult
285
- const result = await this.generateAuthenticationResult(response, request, idTokenClaims, baseAccount, authority.canonicalAuthority, reqTimestamp);
286
- // cache accounts and tokens in the appropriate storage
287
- this.cacheAccount(baseAccount);
288
- this.cacheNativeTokens(response, request, homeAccountIdentifier, idTokenClaims, response.access_token, result.tenantId, reqTimestamp);
289
- return result;
290
- }
291
- /**
292
- * creates an homeAccountIdentifier for the account
293
- * @param response
294
- * @param idTokenObj
295
- * @returns
296
- */
297
- createHomeAccountIdentifier(response, idTokenClaims) {
298
- // Save account in browser storage
299
- const homeAccountIdentifier = AccountEntity.generateHomeAccountId(response.client_info || Constants.EMPTY_STRING, AuthorityType.Default, this.logger, this.browserCrypto, idTokenClaims);
300
- return homeAccountIdentifier;
301
- }
302
- /**
303
- * Helper to generate scopes
304
- * @param response
305
- * @param request
306
- * @returns
307
- */
308
- generateScopes(response, request) {
309
- return response.scope
310
- ? ScopeSet.fromString(response.scope)
311
- : ScopeSet.fromString(request.scope);
312
- }
313
- /**
314
- * If PoP token is requesred, records the PoP token if returned from the WAM, else generates one in the browser
315
- * @param request
316
- * @param response
317
- */
318
- async generatePopAccessToken(response, request) {
319
- if (request.tokenType === AuthenticationScheme.POP &&
320
- request.signPopToken) {
321
- /**
322
- * This code prioritizes SHR returned from the native layer. In case of error/SHR not calculated from WAM and the AT
323
- * is still received, SHR is calculated locally
324
- */
325
- // Check if native layer returned an SHR token
326
- if (response.shr) {
327
- this.logger.trace("handleNativeServerResponse: SHR is enabled in native layer");
328
- return response.shr;
329
- }
330
- // Generate SHR in msal js if WAM does not compute it when POP is enabled
331
- const popTokenGenerator = new PopTokenGenerator(this.browserCrypto);
332
- const shrParameters = {
333
- resourceRequestMethod: request.resourceRequestMethod,
334
- resourceRequestUri: request.resourceRequestUri,
335
- shrClaims: request.shrClaims,
336
- shrNonce: request.shrNonce,
337
- };
338
- /**
339
- * KeyID must be present in the native request from when the PoP key was generated in order for
340
- * PopTokenGenerator to query the full key for signing
341
- */
342
- if (!request.keyId) {
343
- throw createClientAuthError(ClientAuthErrorCodes.keyIdMissing);
344
- }
345
- return popTokenGenerator.signPopToken(response.access_token, request.keyId, shrParameters);
346
- }
347
- else {
348
- return response.access_token;
349
- }
350
- }
351
- /**
352
- * Generates authentication result
353
- * @param response
354
- * @param request
355
- * @param idTokenObj
356
- * @param accountEntity
357
- * @param authority
358
- * @param reqTimestamp
359
- * @returns
360
- */
361
- async generateAuthenticationResult(response, request, idTokenClaims, accountEntity, authority, reqTimestamp) {
362
- // Add Native Broker fields to Telemetry
363
- const mats = this.addTelemetryFromNativeResponse(response);
364
- // If scopes not returned in server response, use request scopes
365
- const responseScopes = response.scope
366
- ? ScopeSet.fromString(response.scope)
367
- : ScopeSet.fromString(request.scope);
368
- const accountProperties = response.account.properties || {};
369
- const uid = accountProperties["UID"] ||
370
- idTokenClaims.oid ||
371
- idTokenClaims.sub ||
372
- Constants.EMPTY_STRING;
373
- const tid = accountProperties["TenantId"] ||
374
- idTokenClaims.tid ||
375
- Constants.EMPTY_STRING;
376
- const accountInfo = updateAccountTenantProfileData(accountEntity.getAccountInfo(), undefined, // tenantProfile optional
377
- idTokenClaims, response.id_token);
378
- /**
379
- * In pairwise broker flows, this check prevents the broker's native account id
380
- * from being returned over the embedded app's account id.
381
- */
382
- if (accountInfo.nativeAccountId !== response.account.id) {
383
- accountInfo.nativeAccountId = response.account.id;
384
- }
385
- // generate PoP token as needed
386
- const responseAccessToken = await this.generatePopAccessToken(response, request);
387
- const tokenType = request.tokenType === AuthenticationScheme.POP
388
- ? AuthenticationScheme.POP
389
- : AuthenticationScheme.BEARER;
390
- const result = {
391
- authority: authority,
392
- uniqueId: uid,
393
- tenantId: tid,
394
- scopes: responseScopes.asArray(),
395
- account: accountInfo,
396
- idToken: response.id_token,
397
- idTokenClaims: idTokenClaims,
398
- accessToken: responseAccessToken,
399
- fromCache: mats ? this.isResponseFromCache(mats) : false,
400
- expiresOn: new Date(Number(reqTimestamp + response.expires_in) * 1000),
401
- tokenType: tokenType,
402
- correlationId: this.correlationId,
403
- state: response.state,
404
- fromNativeBroker: true,
405
- };
406
- return result;
407
- }
408
- /**
409
- * cache the account entity in browser storage
410
- * @param accountEntity
411
- */
412
- cacheAccount(accountEntity) {
413
- // Store the account info and hence `nativeAccountId` in browser cache
414
- this.browserStorage.setAccount(accountEntity);
415
- // Remove any existing cached tokens for this account in browser storage
416
- this.browserStorage.removeAccountContext(accountEntity).catch((e) => {
417
- this.logger.error(`Error occurred while removing account context from browser storage. ${e}`);
418
- });
419
- }
420
- /**
421
- * Stores the access_token and id_token in inmemory storage
422
- * @param response
423
- * @param request
424
- * @param homeAccountIdentifier
425
- * @param idTokenObj
426
- * @param responseAccessToken
427
- * @param tenantId
428
- * @param reqTimestamp
429
- */
430
- cacheNativeTokens(response, request, homeAccountIdentifier, idTokenClaims, responseAccessToken, tenantId, reqTimestamp) {
431
- const cachedIdToken = CacheHelpers.createIdTokenEntity(homeAccountIdentifier, request.authority, response.id_token || "", request.clientId, idTokenClaims.tid || "");
432
- // cache accessToken in inmemory storage
433
- const expiresIn = request.tokenType === AuthenticationScheme.POP
434
- ? Constants.SHR_NONCE_VALIDITY
435
- : (typeof response.expires_in === "string"
436
- ? parseInt(response.expires_in, 10)
437
- : response.expires_in) || 0;
438
- const tokenExpirationSeconds = reqTimestamp + expiresIn;
439
- const responseScopes = this.generateScopes(response, request);
440
- const cachedAccessToken = CacheHelpers.createAccessTokenEntity(homeAccountIdentifier, request.authority, responseAccessToken, request.clientId, idTokenClaims.tid || tenantId, responseScopes.printScopes(), tokenExpirationSeconds, 0, base64Decode, undefined, request.tokenType, undefined, request.keyId);
441
- const nativeCacheRecord = {
442
- idToken: cachedIdToken,
443
- accessToken: cachedAccessToken,
444
- };
445
- void this.nativeStorageManager.saveCacheRecord(nativeCacheRecord, request.storeInCache);
446
- }
447
- addTelemetryFromNativeResponse(response) {
448
- const mats = this.getMATSFromResponse(response);
449
- if (!mats) {
450
- return null;
451
- }
452
- this.performanceClient.addFields({
453
- extensionId: this.nativeMessageHandler.getExtensionId(),
454
- extensionVersion: this.nativeMessageHandler.getExtensionVersion(),
455
- matsBrokerVersion: mats.broker_version,
456
- matsAccountJoinOnStart: mats.account_join_on_start,
457
- matsAccountJoinOnEnd: mats.account_join_on_end,
458
- matsDeviceJoin: mats.device_join,
459
- matsPromptBehavior: mats.prompt_behavior,
460
- matsApiErrorCode: mats.api_error_code,
461
- matsUiVisible: mats.ui_visible,
462
- matsSilentCode: mats.silent_code,
463
- matsSilentBiSubCode: mats.silent_bi_sub_code,
464
- matsSilentMessage: mats.silent_message,
465
- matsSilentStatus: mats.silent_status,
466
- matsHttpStatus: mats.http_status,
467
- matsHttpEventCount: mats.http_event_count,
468
- }, this.correlationId);
469
- return mats;
470
- }
471
- /**
472
- * Validates native platform response before processing
473
- * @param response
474
- */
475
- validateNativeResponse(response) {
476
- if (response.hasOwnProperty("access_token") &&
477
- response.hasOwnProperty("id_token") &&
478
- response.hasOwnProperty("client_info") &&
479
- response.hasOwnProperty("account") &&
480
- response.hasOwnProperty("scope") &&
481
- response.hasOwnProperty("expires_in")) {
482
- return response;
483
- }
484
- else {
485
- throw createAuthError(AuthErrorCodes.unexpectedError, "Response missing expected properties.");
486
- }
487
- }
488
- /**
489
- * Gets MATS telemetry from native response
490
- * @param response
491
- * @returns
492
- */
493
- getMATSFromResponse(response) {
494
- if (response.properties.MATS) {
495
- try {
496
- return JSON.parse(response.properties.MATS);
497
- }
498
- catch (e) {
499
- this.logger.error("NativeInteractionClient - Error parsing MATS telemetry, returning null instead");
500
- }
501
- }
502
- return null;
503
- }
504
- /**
505
- * Returns whether or not response came from native cache
506
- * @param response
507
- * @returns
508
- */
509
- isResponseFromCache(mats) {
510
- if (typeof mats.is_cached === "undefined") {
511
- this.logger.verbose("NativeInteractionClient - MATS telemetry does not contain field indicating if response was served from cache. Returning false.");
512
- return false;
513
- }
514
- return !!mats.is_cached;
515
- }
516
- /**
517
- * Translates developer provided request object into NativeRequest object
518
- * @param request
519
- */
520
- async initializeNativeRequest(request) {
521
- this.logger.trace("NativeInteractionClient - initializeNativeRequest called");
522
- const authority = request.authority || this.config.auth.authority;
523
- if (request.account) {
524
- // validate authority
525
- await this.getDiscoveredAuthority(authority, request.azureCloudOptions, request.account);
526
- }
527
- const canonicalAuthority = new UrlString(authority);
528
- canonicalAuthority.validateAsUri();
529
- // scopes are expected to be received by the native broker as "scope" and will be added to the request below. Other properties that should be dropped from the request to the native broker can be included in the object destructuring here.
530
- const { scopes, ...remainingProperties } = request;
531
- const scopeSet = new ScopeSet(scopes || []);
532
- scopeSet.appendScopes(OIDC_DEFAULT_SCOPES);
533
- const getPrompt = () => {
534
- // If request is silent, prompt is always none
535
- switch (this.apiId) {
536
- case ApiId.ssoSilent:
537
- case ApiId.acquireTokenSilent_silentFlow:
538
- this.logger.trace("initializeNativeRequest: silent request sets prompt to none");
539
- return PromptValue.NONE;
540
- }
541
- // Prompt not provided, request may proceed and native broker decides if it needs to prompt
542
- if (!request.prompt) {
543
- this.logger.trace("initializeNativeRequest: prompt was not provided");
544
- return undefined;
545
- }
546
- // If request is interactive, check if prompt provided is allowed to go directly to native broker
547
- switch (request.prompt) {
548
- case PromptValue.NONE:
549
- case PromptValue.CONSENT:
550
- case PromptValue.LOGIN:
551
- this.logger.trace("initializeNativeRequest: prompt is compatible with native flow");
552
- return request.prompt;
553
- default:
554
- this.logger.trace(`initializeNativeRequest: prompt = ${request.prompt} is not compatible with native flow`);
555
- throw createBrowserAuthError(nativePromptNotSupported);
556
- }
557
- };
558
- const validatedRequest = {
559
- ...remainingProperties,
560
- accountId: this.accountId,
561
- clientId: this.config.auth.clientId,
562
- authority: canonicalAuthority.urlString,
563
- scope: scopeSet.printScopes(),
564
- redirectUri: this.getRedirectUri(request.redirectUri),
565
- prompt: getPrompt(),
566
- correlationId: this.correlationId,
567
- tokenType: request.authenticationScheme,
568
- windowTitleSubstring: document.title,
569
- extraParameters: {
570
- ...request.extraQueryParameters,
571
- ...request.tokenQueryParameters,
572
- },
573
- extendedExpiryToken: false,
574
- keyId: request.popKid,
575
- };
576
- // Check for PoP token requests: signPopToken should only be set to true if popKid is not set
577
- if (validatedRequest.signPopToken && !!request.popKid) {
578
- throw createBrowserAuthError(invalidPopTokenRequest);
579
- }
580
- this.handleExtraBrokerParams(validatedRequest);
581
- validatedRequest.extraParameters =
582
- validatedRequest.extraParameters || {};
583
- validatedRequest.extraParameters.telemetry =
584
- NativeConstants.MATS_TELEMETRY;
585
- if (request.authenticationScheme === AuthenticationScheme.POP) {
586
- // add POP request type
587
- const shrParameters = {
588
- resourceRequestUri: request.resourceRequestUri,
589
- resourceRequestMethod: request.resourceRequestMethod,
590
- shrClaims: request.shrClaims,
591
- shrNonce: request.shrNonce,
592
- };
593
- const popTokenGenerator = new PopTokenGenerator(this.browserCrypto);
594
- // generate reqCnf if not provided in the request
595
- let reqCnfData;
596
- if (!validatedRequest.keyId) {
597
- const generatedReqCnfData = await invokeAsync(popTokenGenerator.generateCnf.bind(popTokenGenerator), PerformanceEvents.PopTokenGenerateCnf, this.logger, this.performanceClient, request.correlationId)(shrParameters, this.logger);
598
- reqCnfData = generatedReqCnfData.reqCnfString;
599
- validatedRequest.keyId = generatedReqCnfData.kid;
600
- validatedRequest.signPopToken = true;
601
- }
602
- else {
603
- reqCnfData = this.browserCrypto.base64UrlEncode(JSON.stringify({ kid: validatedRequest.keyId }));
604
- validatedRequest.signPopToken = false;
605
- }
606
- // SPAs require whole string to be passed to broker
607
- validatedRequest.reqCnf = reqCnfData;
608
- }
609
- this.addRequestSKUs(validatedRequest);
610
- return validatedRequest;
611
- }
612
- /**
613
- * Handles extra broker request parameters
614
- * @param request {NativeTokenRequest}
615
- * @private
616
- */
617
- handleExtraBrokerParams(request) {
618
- if (!request.extraParameters) {
619
- return;
620
- }
621
- if (request.extraParameters.hasOwnProperty(BrokerServerParamKeys.BROKER_CLIENT_ID) &&
622
- request.extraParameters.hasOwnProperty(BrokerServerParamKeys.BROKER_REDIRECT_URI) &&
623
- request.extraParameters.hasOwnProperty(AADServerParamKeys.CLIENT_ID)) {
624
- const child_client_id = request.extraParameters[AADServerParamKeys.CLIENT_ID];
625
- const child_redirect_uri = request.redirectUri;
626
- const brk_redirect_uri = request.extraParameters[BrokerServerParamKeys.BROKER_REDIRECT_URI];
627
- request.extraParameters = {
628
- child_client_id,
629
- child_redirect_uri,
630
- };
631
- request.redirectUri = brk_redirect_uri;
632
- }
633
- }
14
+ /*
15
+ * Copyright (c) Microsoft Corporation. All rights reserved.
16
+ * Licensed under the MIT License.
17
+ */
18
+ const BrokerServerParamKeys = {
19
+ BROKER_CLIENT_ID: "brk_client_id",
20
+ BROKER_REDIRECT_URI: "brk_redirect_uri",
21
+ };
22
+ class NativeInteractionClient extends BaseInteractionClient {
23
+ constructor(config, browserStorage, browserCrypto, logger, eventHandler, navigationClient, apiId, performanceClient, provider, accountId, nativeStorageImpl, correlationId) {
24
+ super(config, browserStorage, browserCrypto, logger, eventHandler, navigationClient, performanceClient, provider, correlationId);
25
+ this.apiId = apiId;
26
+ this.accountId = accountId;
27
+ this.nativeMessageHandler = provider;
28
+ this.nativeStorageManager = nativeStorageImpl;
29
+ this.silentCacheClient = new SilentCacheClient(config, this.nativeStorageManager, browserCrypto, logger, eventHandler, navigationClient, performanceClient, provider, correlationId);
30
+ this.serverTelemetryManager = this.initializeServerTelemetryManager(this.apiId);
31
+ const extensionName = this.nativeMessageHandler.getExtensionId() ===
32
+ NativeConstants.PREFERRED_EXTENSION_ID
33
+ ? "chrome"
34
+ : this.nativeMessageHandler.getExtensionId()?.length
35
+ ? "unknown"
36
+ : undefined;
37
+ this.skus = ServerTelemetryManager.makeExtraSkuString({
38
+ libraryName: BrowserConstants.MSAL_SKU,
39
+ libraryVersion: version,
40
+ extensionName: extensionName,
41
+ extensionVersion: this.nativeMessageHandler.getExtensionVersion(),
42
+ });
43
+ }
44
+ /**
45
+ * Adds SKUs to request extra query parameters
46
+ * @param request {NativeTokenRequest}
47
+ * @private
48
+ */
49
+ addRequestSKUs(request) {
50
+ request.extraParameters = {
51
+ ...request.extraParameters,
52
+ [AADServerParamKeys.X_CLIENT_EXTRA_SKU]: this.skus,
53
+ };
54
+ }
55
+ /**
56
+ * Acquire token from native platform via browser extension
57
+ * @param request
58
+ */
59
+ async acquireToken(request) {
60
+ this.performanceClient.addQueueMeasurement(PerformanceEvents.NativeInteractionClientAcquireToken, request.correlationId);
61
+ this.logger.trace("NativeInteractionClient - acquireToken called.");
62
+ // start the perf measurement
63
+ const nativeATMeasurement = this.performanceClient.startMeasurement(PerformanceEvents.NativeInteractionClientAcquireToken, request.correlationId);
64
+ const reqTimestamp = TimeUtils.nowSeconds();
65
+ try {
66
+ // initialize native request
67
+ const nativeRequest = await this.initializeNativeRequest(request);
68
+ // check if the tokens can be retrieved from internal cache
69
+ try {
70
+ const result = await this.acquireTokensFromCache(this.accountId, nativeRequest);
71
+ nativeATMeasurement.end({
72
+ success: true,
73
+ isNativeBroker: false,
74
+ fromCache: true,
75
+ });
76
+ return result;
77
+ }
78
+ catch (e) {
79
+ // continue with a native call for any and all errors
80
+ this.logger.info("MSAL internal Cache does not contain tokens, proceed to make a native call");
81
+ }
82
+ const { ...nativeTokenRequest } = nativeRequest;
83
+ // fall back to native calls
84
+ const messageBody = {
85
+ method: NativeExtensionMethod.GetToken,
86
+ request: nativeTokenRequest,
87
+ };
88
+ const response = await this.nativeMessageHandler.sendMessage(messageBody);
89
+ const validatedResponse = this.validateNativeResponse(response);
90
+ return await this.handleNativeResponse(validatedResponse, nativeRequest, reqTimestamp)
91
+ .then((result) => {
92
+ nativeATMeasurement.end({
93
+ success: true,
94
+ isNativeBroker: true,
95
+ requestId: result.requestId,
96
+ });
97
+ this.serverTelemetryManager.clearNativeBrokerErrorCode();
98
+ return result;
99
+ })
100
+ .catch((error) => {
101
+ nativeATMeasurement.end({
102
+ success: false,
103
+ errorCode: error.errorCode,
104
+ subErrorCode: error.subError,
105
+ isNativeBroker: true,
106
+ });
107
+ throw error;
108
+ });
109
+ }
110
+ catch (e) {
111
+ if (e instanceof NativeAuthError) {
112
+ this.serverTelemetryManager.setNativeBrokerErrorCode(e.errorCode);
113
+ }
114
+ throw e;
115
+ }
116
+ }
117
+ /**
118
+ * Creates silent flow request
119
+ * @param request
120
+ * @param cachedAccount
121
+ * @returns CommonSilentFlowRequest
122
+ */
123
+ createSilentCacheRequest(request, cachedAccount) {
124
+ return {
125
+ authority: request.authority,
126
+ correlationId: this.correlationId,
127
+ scopes: ScopeSet.fromString(request.scope).asArray(),
128
+ account: cachedAccount,
129
+ forceRefresh: false,
130
+ };
131
+ }
132
+ /**
133
+ * Fetches the tokens from the cache if un-expired
134
+ * @param nativeAccountId
135
+ * @param request
136
+ * @returns authenticationResult
137
+ */
138
+ async acquireTokensFromCache(nativeAccountId, request) {
139
+ if (!nativeAccountId) {
140
+ this.logger.warning("NativeInteractionClient:acquireTokensFromCache - No nativeAccountId provided");
141
+ throw createClientAuthError(ClientAuthErrorCodes.noAccountFound);
142
+ }
143
+ // fetch the account from browser cache
144
+ const account = this.browserStorage.getBaseAccountInfo({
145
+ nativeAccountId,
146
+ });
147
+ if (!account) {
148
+ throw createClientAuthError(ClientAuthErrorCodes.noAccountFound);
149
+ }
150
+ // leverage silent flow for cached tokens retrieval
151
+ try {
152
+ const silentRequest = this.createSilentCacheRequest(request, account);
153
+ const result = await this.silentCacheClient.acquireToken(silentRequest);
154
+ const fullAccount = {
155
+ ...account,
156
+ idTokenClaims: result?.idTokenClaims,
157
+ idToken: result?.idToken,
158
+ };
159
+ return {
160
+ ...result,
161
+ account: fullAccount,
162
+ };
163
+ }
164
+ catch (e) {
165
+ throw e;
166
+ }
167
+ }
168
+ /**
169
+ * Acquires a token from native platform then redirects to the redirectUri instead of returning the response
170
+ * @param {RedirectRequest} request
171
+ * @param {InProgressPerformanceEvent} rootMeasurement
172
+ */
173
+ async acquireTokenRedirect(request, rootMeasurement) {
174
+ this.logger.trace("NativeInteractionClient - acquireTokenRedirect called.");
175
+ const { ...remainingParameters } = request;
176
+ delete remainingParameters.onRedirectNavigate;
177
+ const nativeRequest = await this.initializeNativeRequest(remainingParameters);
178
+ const messageBody = {
179
+ method: NativeExtensionMethod.GetToken,
180
+ request: nativeRequest,
181
+ };
182
+ try {
183
+ const response = await this.nativeMessageHandler.sendMessage(messageBody);
184
+ this.validateNativeResponse(response);
185
+ }
186
+ catch (e) {
187
+ // Only throw fatal errors here to allow application to fallback to regular redirect. Otherwise proceed and the error will be thrown in handleRedirectPromise
188
+ if (e instanceof NativeAuthError) {
189
+ this.serverTelemetryManager.setNativeBrokerErrorCode(e.errorCode);
190
+ if (isFatalNativeAuthError(e)) {
191
+ throw e;
192
+ }
193
+ }
194
+ }
195
+ this.browserStorage.setTemporaryCache(TemporaryCacheKeys.NATIVE_REQUEST, JSON.stringify(nativeRequest), true);
196
+ const navigationOptions = {
197
+ apiId: ApiId.acquireTokenRedirect,
198
+ timeout: this.config.system.redirectNavigationTimeout,
199
+ noHistory: false,
200
+ };
201
+ const redirectUri = this.config.auth.navigateToLoginRequestUrl
202
+ ? window.location.href
203
+ : this.getRedirectUri(request.redirectUri);
204
+ rootMeasurement.end({ success: true });
205
+ await this.navigationClient.navigateExternal(redirectUri, navigationOptions); // Need to treat this as external to ensure handleRedirectPromise is run again
206
+ }
207
+ /**
208
+ * If the previous page called native platform for a token using redirect APIs, send the same request again and return the response
209
+ * @param performanceClient {IPerformanceClient?}
210
+ * @param correlationId {string?} correlation identifier
211
+ */
212
+ async handleRedirectPromise(performanceClient, correlationId) {
213
+ this.logger.trace("NativeInteractionClient - handleRedirectPromise called.");
214
+ if (!this.browserStorage.isInteractionInProgress(true)) {
215
+ this.logger.info("handleRedirectPromise called but there is no interaction in progress, returning null.");
216
+ return null;
217
+ }
218
+ // remove prompt from the request to prevent WAM from prompting twice
219
+ const cachedRequest = this.browserStorage.getCachedNativeRequest();
220
+ if (!cachedRequest) {
221
+ this.logger.verbose("NativeInteractionClient - handleRedirectPromise called but there is no cached request, returning null.");
222
+ if (performanceClient && correlationId) {
223
+ performanceClient?.addFields({ errorCode: "no_cached_request" }, correlationId);
224
+ }
225
+ return null;
226
+ }
227
+ const { prompt, ...request } = cachedRequest;
228
+ if (prompt) {
229
+ this.logger.verbose("NativeInteractionClient - handleRedirectPromise called and prompt was included in the original request, removing prompt from cached request to prevent second interaction with native broker window.");
230
+ }
231
+ this.browserStorage.removeItem(this.browserStorage.generateCacheKey(TemporaryCacheKeys.NATIVE_REQUEST));
232
+ const messageBody = {
233
+ method: NativeExtensionMethod.GetToken,
234
+ request: request,
235
+ };
236
+ const reqTimestamp = TimeUtils.nowSeconds();
237
+ try {
238
+ this.logger.verbose("NativeInteractionClient - handleRedirectPromise sending message to native broker.");
239
+ const response = await this.nativeMessageHandler.sendMessage(messageBody);
240
+ this.validateNativeResponse(response);
241
+ const result = this.handleNativeResponse(response, request, reqTimestamp);
242
+ this.browserStorage.setInteractionInProgress(false);
243
+ const res = await result;
244
+ this.serverTelemetryManager.clearNativeBrokerErrorCode();
245
+ return res;
246
+ }
247
+ catch (e) {
248
+ this.browserStorage.setInteractionInProgress(false);
249
+ throw e;
250
+ }
251
+ }
252
+ /**
253
+ * Logout from native platform via browser extension
254
+ * @param request
255
+ */
256
+ logout() {
257
+ this.logger.trace("NativeInteractionClient - logout called.");
258
+ return Promise.reject("Logout not implemented yet");
259
+ }
260
+ /**
261
+ * Transform response from native platform into AuthenticationResult object which will be returned to the end user
262
+ * @param response
263
+ * @param request
264
+ * @param reqTimestamp
265
+ */
266
+ async handleNativeResponse(response, request, reqTimestamp) {
267
+ this.logger.trace("NativeInteractionClient - handleNativeResponse called.");
268
+ // generate identifiers
269
+ const idTokenClaims = AuthToken.extractTokenClaims(response.id_token, base64Decode);
270
+ const homeAccountIdentifier = this.createHomeAccountIdentifier(response, idTokenClaims);
271
+ const cachedhomeAccountId = this.browserStorage.getAccountInfoFilteredBy({
272
+ nativeAccountId: request.accountId,
273
+ })?.homeAccountId;
274
+ if (homeAccountIdentifier !== cachedhomeAccountId &&
275
+ response.account.id !== request.accountId) {
276
+ // User switch in native broker prompt is not supported. All users must first sign in through web flow to ensure server state is in sync
277
+ throw createNativeAuthError(userSwitch);
278
+ }
279
+ // Get the preferred_cache domain for the given authority
280
+ const authority = await this.getDiscoveredAuthority(request.authority);
281
+ const baseAccount = buildAccountToCache(this.browserStorage, authority, homeAccountIdentifier, base64Decode, idTokenClaims, response.client_info, undefined, // environment
282
+ idTokenClaims.tid, undefined, // auth code payload
283
+ response.account.id, this.logger);
284
+ // generate authenticationResult
285
+ const result = await this.generateAuthenticationResult(response, request, idTokenClaims, baseAccount, authority.canonicalAuthority, reqTimestamp);
286
+ // cache accounts and tokens in the appropriate storage
287
+ this.cacheAccount(baseAccount);
288
+ this.cacheNativeTokens(response, request, homeAccountIdentifier, idTokenClaims, response.access_token, result.tenantId, reqTimestamp);
289
+ return result;
290
+ }
291
+ /**
292
+ * creates an homeAccountIdentifier for the account
293
+ * @param response
294
+ * @param idTokenObj
295
+ * @returns
296
+ */
297
+ createHomeAccountIdentifier(response, idTokenClaims) {
298
+ // Save account in browser storage
299
+ const homeAccountIdentifier = AccountEntity.generateHomeAccountId(response.client_info || Constants.EMPTY_STRING, AuthorityType.Default, this.logger, this.browserCrypto, idTokenClaims);
300
+ return homeAccountIdentifier;
301
+ }
302
+ /**
303
+ * Helper to generate scopes
304
+ * @param response
305
+ * @param request
306
+ * @returns
307
+ */
308
+ generateScopes(response, request) {
309
+ return response.scope
310
+ ? ScopeSet.fromString(response.scope)
311
+ : ScopeSet.fromString(request.scope);
312
+ }
313
+ /**
314
+ * If PoP token is requesred, records the PoP token if returned from the WAM, else generates one in the browser
315
+ * @param request
316
+ * @param response
317
+ */
318
+ async generatePopAccessToken(response, request) {
319
+ if (request.tokenType === AuthenticationScheme.POP &&
320
+ request.signPopToken) {
321
+ /**
322
+ * This code prioritizes SHR returned from the native layer. In case of error/SHR not calculated from WAM and the AT
323
+ * is still received, SHR is calculated locally
324
+ */
325
+ // Check if native layer returned an SHR token
326
+ if (response.shr) {
327
+ this.logger.trace("handleNativeServerResponse: SHR is enabled in native layer");
328
+ return response.shr;
329
+ }
330
+ // Generate SHR in msal js if WAM does not compute it when POP is enabled
331
+ const popTokenGenerator = new PopTokenGenerator(this.browserCrypto);
332
+ const shrParameters = {
333
+ resourceRequestMethod: request.resourceRequestMethod,
334
+ resourceRequestUri: request.resourceRequestUri,
335
+ shrClaims: request.shrClaims,
336
+ shrNonce: request.shrNonce,
337
+ };
338
+ /**
339
+ * KeyID must be present in the native request from when the PoP key was generated in order for
340
+ * PopTokenGenerator to query the full key for signing
341
+ */
342
+ if (!request.keyId) {
343
+ throw createClientAuthError(ClientAuthErrorCodes.keyIdMissing);
344
+ }
345
+ return popTokenGenerator.signPopToken(response.access_token, request.keyId, shrParameters);
346
+ }
347
+ else {
348
+ return response.access_token;
349
+ }
350
+ }
351
+ /**
352
+ * Generates authentication result
353
+ * @param response
354
+ * @param request
355
+ * @param idTokenObj
356
+ * @param accountEntity
357
+ * @param authority
358
+ * @param reqTimestamp
359
+ * @returns
360
+ */
361
+ async generateAuthenticationResult(response, request, idTokenClaims, accountEntity, authority, reqTimestamp) {
362
+ // Add Native Broker fields to Telemetry
363
+ const mats = this.addTelemetryFromNativeResponse(response);
364
+ // If scopes not returned in server response, use request scopes
365
+ const responseScopes = response.scope
366
+ ? ScopeSet.fromString(response.scope)
367
+ : ScopeSet.fromString(request.scope);
368
+ const accountProperties = response.account.properties || {};
369
+ const uid = accountProperties["UID"] ||
370
+ idTokenClaims.oid ||
371
+ idTokenClaims.sub ||
372
+ Constants.EMPTY_STRING;
373
+ const tid = accountProperties["TenantId"] ||
374
+ idTokenClaims.tid ||
375
+ Constants.EMPTY_STRING;
376
+ const accountInfo = updateAccountTenantProfileData(accountEntity.getAccountInfo(), undefined, // tenantProfile optional
377
+ idTokenClaims, response.id_token);
378
+ /**
379
+ * In pairwise broker flows, this check prevents the broker's native account id
380
+ * from being returned over the embedded app's account id.
381
+ */
382
+ if (accountInfo.nativeAccountId !== response.account.id) {
383
+ accountInfo.nativeAccountId = response.account.id;
384
+ }
385
+ // generate PoP token as needed
386
+ const responseAccessToken = await this.generatePopAccessToken(response, request);
387
+ const tokenType = request.tokenType === AuthenticationScheme.POP
388
+ ? AuthenticationScheme.POP
389
+ : AuthenticationScheme.BEARER;
390
+ const result = {
391
+ authority: authority,
392
+ uniqueId: uid,
393
+ tenantId: tid,
394
+ scopes: responseScopes.asArray(),
395
+ account: accountInfo,
396
+ idToken: response.id_token,
397
+ idTokenClaims: idTokenClaims,
398
+ accessToken: responseAccessToken,
399
+ fromCache: mats ? this.isResponseFromCache(mats) : false,
400
+ expiresOn: new Date(Number(reqTimestamp + response.expires_in) * 1000),
401
+ tokenType: tokenType,
402
+ correlationId: this.correlationId,
403
+ state: response.state,
404
+ fromNativeBroker: true,
405
+ };
406
+ return result;
407
+ }
408
+ /**
409
+ * cache the account entity in browser storage
410
+ * @param accountEntity
411
+ */
412
+ cacheAccount(accountEntity) {
413
+ // Store the account info and hence `nativeAccountId` in browser cache
414
+ this.browserStorage.setAccount(accountEntity);
415
+ // Remove any existing cached tokens for this account in browser storage
416
+ this.browserStorage.removeAccountContext(accountEntity).catch((e) => {
417
+ this.logger.error(`Error occurred while removing account context from browser storage. ${e}`);
418
+ });
419
+ }
420
+ /**
421
+ * Stores the access_token and id_token in inmemory storage
422
+ * @param response
423
+ * @param request
424
+ * @param homeAccountIdentifier
425
+ * @param idTokenObj
426
+ * @param responseAccessToken
427
+ * @param tenantId
428
+ * @param reqTimestamp
429
+ */
430
+ cacheNativeTokens(response, request, homeAccountIdentifier, idTokenClaims, responseAccessToken, tenantId, reqTimestamp) {
431
+ const cachedIdToken = CacheHelpers.createIdTokenEntity(homeAccountIdentifier, request.authority, response.id_token || "", request.clientId, idTokenClaims.tid || "");
432
+ // cache accessToken in inmemory storage
433
+ const expiresIn = request.tokenType === AuthenticationScheme.POP
434
+ ? Constants.SHR_NONCE_VALIDITY
435
+ : (typeof response.expires_in === "string"
436
+ ? parseInt(response.expires_in, 10)
437
+ : response.expires_in) || 0;
438
+ const tokenExpirationSeconds = reqTimestamp + expiresIn;
439
+ const responseScopes = this.generateScopes(response, request);
440
+ const cachedAccessToken = CacheHelpers.createAccessTokenEntity(homeAccountIdentifier, request.authority, responseAccessToken, request.clientId, idTokenClaims.tid || tenantId, responseScopes.printScopes(), tokenExpirationSeconds, 0, base64Decode, undefined, request.tokenType, undefined, request.keyId);
441
+ const nativeCacheRecord = {
442
+ idToken: cachedIdToken,
443
+ accessToken: cachedAccessToken,
444
+ };
445
+ void this.nativeStorageManager.saveCacheRecord(nativeCacheRecord, request.storeInCache);
446
+ }
447
+ addTelemetryFromNativeResponse(response) {
448
+ const mats = this.getMATSFromResponse(response);
449
+ if (!mats) {
450
+ return null;
451
+ }
452
+ this.performanceClient.addFields({
453
+ extensionId: this.nativeMessageHandler.getExtensionId(),
454
+ extensionVersion: this.nativeMessageHandler.getExtensionVersion(),
455
+ matsBrokerVersion: mats.broker_version,
456
+ matsAccountJoinOnStart: mats.account_join_on_start,
457
+ matsAccountJoinOnEnd: mats.account_join_on_end,
458
+ matsDeviceJoin: mats.device_join,
459
+ matsPromptBehavior: mats.prompt_behavior,
460
+ matsApiErrorCode: mats.api_error_code,
461
+ matsUiVisible: mats.ui_visible,
462
+ matsSilentCode: mats.silent_code,
463
+ matsSilentBiSubCode: mats.silent_bi_sub_code,
464
+ matsSilentMessage: mats.silent_message,
465
+ matsSilentStatus: mats.silent_status,
466
+ matsHttpStatus: mats.http_status,
467
+ matsHttpEventCount: mats.http_event_count,
468
+ }, this.correlationId);
469
+ return mats;
470
+ }
471
+ /**
472
+ * Validates native platform response before processing
473
+ * @param response
474
+ */
475
+ validateNativeResponse(response) {
476
+ if (response.hasOwnProperty("access_token") &&
477
+ response.hasOwnProperty("id_token") &&
478
+ response.hasOwnProperty("client_info") &&
479
+ response.hasOwnProperty("account") &&
480
+ response.hasOwnProperty("scope") &&
481
+ response.hasOwnProperty("expires_in")) {
482
+ return response;
483
+ }
484
+ else {
485
+ throw createAuthError(AuthErrorCodes.unexpectedError, "Response missing expected properties.");
486
+ }
487
+ }
488
+ /**
489
+ * Gets MATS telemetry from native response
490
+ * @param response
491
+ * @returns
492
+ */
493
+ getMATSFromResponse(response) {
494
+ if (response.properties.MATS) {
495
+ try {
496
+ return JSON.parse(response.properties.MATS);
497
+ }
498
+ catch (e) {
499
+ this.logger.error("NativeInteractionClient - Error parsing MATS telemetry, returning null instead");
500
+ }
501
+ }
502
+ return null;
503
+ }
504
+ /**
505
+ * Returns whether or not response came from native cache
506
+ * @param response
507
+ * @returns
508
+ */
509
+ isResponseFromCache(mats) {
510
+ if (typeof mats.is_cached === "undefined") {
511
+ this.logger.verbose("NativeInteractionClient - MATS telemetry does not contain field indicating if response was served from cache. Returning false.");
512
+ return false;
513
+ }
514
+ return !!mats.is_cached;
515
+ }
516
+ /**
517
+ * Translates developer provided request object into NativeRequest object
518
+ * @param request
519
+ */
520
+ async initializeNativeRequest(request) {
521
+ this.logger.trace("NativeInteractionClient - initializeNativeRequest called");
522
+ const authority = request.authority || this.config.auth.authority;
523
+ if (request.account) {
524
+ // validate authority
525
+ await this.getDiscoveredAuthority(authority, request.azureCloudOptions, request.account);
526
+ }
527
+ const canonicalAuthority = new UrlString(authority);
528
+ canonicalAuthority.validateAsUri();
529
+ // scopes are expected to be received by the native broker as "scope" and will be added to the request below. Other properties that should be dropped from the request to the native broker can be included in the object destructuring here.
530
+ const { scopes, ...remainingProperties } = request;
531
+ const scopeSet = new ScopeSet(scopes || []);
532
+ scopeSet.appendScopes(OIDC_DEFAULT_SCOPES);
533
+ const getPrompt = () => {
534
+ // If request is silent, prompt is always none
535
+ switch (this.apiId) {
536
+ case ApiId.ssoSilent:
537
+ case ApiId.acquireTokenSilent_silentFlow:
538
+ this.logger.trace("initializeNativeRequest: silent request sets prompt to none");
539
+ return PromptValue.NONE;
540
+ }
541
+ // Prompt not provided, request may proceed and native broker decides if it needs to prompt
542
+ if (!request.prompt) {
543
+ this.logger.trace("initializeNativeRequest: prompt was not provided");
544
+ return undefined;
545
+ }
546
+ // If request is interactive, check if prompt provided is allowed to go directly to native broker
547
+ switch (request.prompt) {
548
+ case PromptValue.NONE:
549
+ case PromptValue.CONSENT:
550
+ case PromptValue.LOGIN:
551
+ this.logger.trace("initializeNativeRequest: prompt is compatible with native flow");
552
+ return request.prompt;
553
+ default:
554
+ this.logger.trace(`initializeNativeRequest: prompt = ${request.prompt} is not compatible with native flow`);
555
+ throw createBrowserAuthError(nativePromptNotSupported);
556
+ }
557
+ };
558
+ const validatedRequest = {
559
+ ...remainingProperties,
560
+ accountId: this.accountId,
561
+ clientId: this.config.auth.clientId,
562
+ authority: canonicalAuthority.urlString,
563
+ scope: scopeSet.printScopes(),
564
+ redirectUri: this.getRedirectUri(request.redirectUri),
565
+ prompt: getPrompt(),
566
+ correlationId: this.correlationId,
567
+ tokenType: request.authenticationScheme,
568
+ windowTitleSubstring: document.title,
569
+ extraParameters: {
570
+ ...request.extraQueryParameters,
571
+ ...request.tokenQueryParameters,
572
+ },
573
+ extendedExpiryToken: false,
574
+ keyId: request.popKid,
575
+ };
576
+ // Check for PoP token requests: signPopToken should only be set to true if popKid is not set
577
+ if (validatedRequest.signPopToken && !!request.popKid) {
578
+ throw createBrowserAuthError(invalidPopTokenRequest);
579
+ }
580
+ this.handleExtraBrokerParams(validatedRequest);
581
+ validatedRequest.extraParameters =
582
+ validatedRequest.extraParameters || {};
583
+ validatedRequest.extraParameters.telemetry =
584
+ NativeConstants.MATS_TELEMETRY;
585
+ if (request.authenticationScheme === AuthenticationScheme.POP) {
586
+ // add POP request type
587
+ const shrParameters = {
588
+ resourceRequestUri: request.resourceRequestUri,
589
+ resourceRequestMethod: request.resourceRequestMethod,
590
+ shrClaims: request.shrClaims,
591
+ shrNonce: request.shrNonce,
592
+ };
593
+ const popTokenGenerator = new PopTokenGenerator(this.browserCrypto);
594
+ // generate reqCnf if not provided in the request
595
+ let reqCnfData;
596
+ if (!validatedRequest.keyId) {
597
+ const generatedReqCnfData = await invokeAsync(popTokenGenerator.generateCnf.bind(popTokenGenerator), PerformanceEvents.PopTokenGenerateCnf, this.logger, this.performanceClient, request.correlationId)(shrParameters, this.logger);
598
+ reqCnfData = generatedReqCnfData.reqCnfString;
599
+ validatedRequest.keyId = generatedReqCnfData.kid;
600
+ validatedRequest.signPopToken = true;
601
+ }
602
+ else {
603
+ reqCnfData = this.browserCrypto.base64UrlEncode(JSON.stringify({ kid: validatedRequest.keyId }));
604
+ validatedRequest.signPopToken = false;
605
+ }
606
+ // SPAs require whole string to be passed to broker
607
+ validatedRequest.reqCnf = reqCnfData;
608
+ }
609
+ this.addRequestSKUs(validatedRequest);
610
+ return validatedRequest;
611
+ }
612
+ /**
613
+ * Handles extra broker request parameters
614
+ * @param request {NativeTokenRequest}
615
+ * @private
616
+ */
617
+ handleExtraBrokerParams(request) {
618
+ if (!request.extraParameters) {
619
+ return;
620
+ }
621
+ if (request.extraParameters.hasOwnProperty(BrokerServerParamKeys.BROKER_CLIENT_ID) &&
622
+ request.extraParameters.hasOwnProperty(BrokerServerParamKeys.BROKER_REDIRECT_URI) &&
623
+ request.extraParameters.hasOwnProperty(AADServerParamKeys.CLIENT_ID)) {
624
+ const child_client_id = request.extraParameters[AADServerParamKeys.CLIENT_ID];
625
+ const child_redirect_uri = request.redirectUri;
626
+ const brk_redirect_uri = request.extraParameters[BrokerServerParamKeys.BROKER_REDIRECT_URI];
627
+ request.extraParameters = {
628
+ child_client_id,
629
+ child_redirect_uri,
630
+ };
631
+ request.redirectUri = brk_redirect_uri;
632
+ }
633
+ }
634
634
  }
635
635
 
636
636
  export { NativeInteractionClient };