@azure/msal-browser 3.0.0-alpha.1 → 3.0.0-alpha.2

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 (142) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +213 -213
  3. package/dist/app/IPublicClientApplication.d.ts +45 -45
  4. package/dist/app/IPublicClientApplication.js +96 -96
  5. package/dist/app/PublicClientApplication.d.ts +244 -244
  6. package/dist/app/PublicClientApplication.js +307 -307
  7. package/dist/broker/nativeBroker/NativeMessageHandler.d.ts +63 -63
  8. package/dist/broker/nativeBroker/NativeMessageHandler.js +255 -255
  9. package/dist/broker/nativeBroker/NativeRequest.d.ts +43 -43
  10. package/dist/broker/nativeBroker/NativeResponse.d.ts +48 -48
  11. package/dist/cache/AsyncMemoryStorage.d.ts +51 -51
  12. package/dist/cache/AsyncMemoryStorage.js +132 -132
  13. package/dist/cache/BrowserCacheManager.d.ts +377 -377
  14. package/dist/cache/BrowserCacheManager.js +1276 -1276
  15. package/dist/cache/BrowserStorage.d.ts +11 -11
  16. package/dist/cache/BrowserStorage.js +35 -35
  17. package/dist/cache/CryptoKeyStore.d.ts +17 -17
  18. package/dist/cache/CryptoKeyStore.js +41 -41
  19. package/dist/cache/DatabaseStorage.d.ts +56 -56
  20. package/dist/cache/DatabaseStorage.js +190 -190
  21. package/dist/cache/IAsyncMemoryStorage.d.ts +27 -27
  22. package/dist/cache/ITokenCache.d.ts +10 -10
  23. package/dist/cache/IWindowStorage.d.ts +27 -27
  24. package/dist/cache/MemoryStorage.d.ts +11 -11
  25. package/dist/cache/MemoryStorage.js +31 -31
  26. package/dist/cache/TokenCache.d.ts +76 -76
  27. package/dist/cache/TokenCache.js +225 -225
  28. package/dist/config/Configuration.d.ts +203 -203
  29. package/dist/config/Configuration.js +101 -101
  30. package/dist/controllers/ControllerFactory.d.ts +9 -9
  31. package/dist/controllers/ControllerFactory.js +37 -37
  32. package/dist/controllers/IController.d.ts +66 -66
  33. package/dist/controllers/StandardController.d.ts +413 -413
  34. package/dist/controllers/StandardController.js +1272 -1272
  35. package/dist/crypto/BrowserCrypto.d.ts +61 -61
  36. package/dist/crypto/BrowserCrypto.js +131 -131
  37. package/dist/crypto/CryptoOps.d.ts +73 -73
  38. package/dist/crypto/CryptoOps.js +150 -150
  39. package/dist/crypto/GuidGenerator.d.ts +12 -12
  40. package/dist/crypto/GuidGenerator.js +96 -96
  41. package/dist/crypto/ISubtleCrypto.d.ts +9 -9
  42. package/dist/crypto/ModernBrowserCrypto.d.ts +9 -9
  43. package/dist/crypto/ModernBrowserCrypto.js +24 -24
  44. package/dist/crypto/MsBrowserCrypto.d.ts +9 -9
  45. package/dist/crypto/MsBrowserCrypto.js +79 -79
  46. package/dist/crypto/MsrBrowserCrypto.d.ts +17 -17
  47. package/dist/crypto/MsrBrowserCrypto.js +28 -28
  48. package/dist/crypto/PkceGenerator.d.ts +24 -24
  49. package/dist/crypto/PkceGenerator.js +58 -58
  50. package/dist/crypto/SignedHttpRequest.d.ts +30 -30
  51. package/dist/crypto/SignedHttpRequest.js +39 -39
  52. package/dist/encode/Base64Decode.d.ts +22 -22
  53. package/dist/encode/Base64Decode.js +73 -73
  54. package/dist/encode/Base64Encode.d.ts +31 -31
  55. package/dist/encode/Base64Encode.js +79 -79
  56. package/dist/error/BrowserAuthError.d.ts +382 -382
  57. package/dist/error/BrowserAuthError.js +483 -483
  58. package/dist/error/BrowserConfigurationAuthError.d.ts +70 -70
  59. package/dist/error/BrowserConfigurationAuthError.js +96 -96
  60. package/dist/error/NativeAuthError.d.ts +56 -56
  61. package/dist/error/NativeAuthError.js +88 -88
  62. package/dist/event/EventHandler.d.ts +41 -41
  63. package/dist/event/EventHandler.js +119 -119
  64. package/dist/event/EventMessage.d.ts +25 -25
  65. package/dist/event/EventMessage.js +67 -67
  66. package/dist/event/EventType.d.ts +26 -26
  67. package/dist/event/EventType.js +31 -31
  68. package/dist/index.d.ts +35 -35
  69. package/dist/index.js +1 -1
  70. package/dist/interaction_client/BaseInteractionClient.d.ts +52 -52
  71. package/dist/interaction_client/BaseInteractionClient.js +138 -138
  72. package/dist/interaction_client/HybridSpaAuthorizationCodeClient.d.ts +4 -4
  73. package/dist/interaction_client/HybridSpaAuthorizationCodeClient.js +10 -10
  74. package/dist/interaction_client/NativeInteractionClient.d.ts +148 -148
  75. package/dist/interaction_client/NativeInteractionClient.js +516 -516
  76. package/dist/interaction_client/PopupClient.d.ts +111 -111
  77. package/dist/interaction_client/PopupClient.js +476 -476
  78. package/dist/interaction_client/RedirectClient.d.ts +48 -48
  79. package/dist/interaction_client/RedirectClient.js +290 -290
  80. package/dist/interaction_client/SilentAuthCodeClient.d.ts +22 -22
  81. package/dist/interaction_client/SilentAuthCodeClient.js +62 -62
  82. package/dist/interaction_client/SilentCacheClient.d.ts +21 -21
  83. package/dist/interaction_client/SilentCacheClient.js +67 -67
  84. package/dist/interaction_client/SilentIframeClient.d.ts +31 -31
  85. package/dist/interaction_client/SilentIframeClient.js +127 -127
  86. package/dist/interaction_client/SilentRefreshClient.d.ts +19 -19
  87. package/dist/interaction_client/SilentRefreshClient.js +62 -62
  88. package/dist/interaction_client/StandardInteractionClient.d.ts +59 -59
  89. package/dist/interaction_client/StandardInteractionClient.js +259 -259
  90. package/dist/interaction_handler/InteractionHandler.d.ts +39 -39
  91. package/dist/interaction_handler/InteractionHandler.js +127 -127
  92. package/dist/interaction_handler/RedirectHandler.d.ts +24 -24
  93. package/dist/interaction_handler/RedirectHandler.js +118 -118
  94. package/dist/interaction_handler/SilentHandler.d.ts +47 -47
  95. package/dist/interaction_handler/SilentHandler.js +162 -162
  96. package/dist/internals.d.ts +23 -23
  97. package/dist/internals.js +4 -4
  98. package/dist/navigation/INavigationClient.d.ts +16 -16
  99. package/dist/navigation/NavigationClient.d.ts +22 -22
  100. package/dist/navigation/NavigationClient.js +40 -40
  101. package/dist/navigation/NavigationOptions.d.ts +12 -12
  102. package/dist/network/FetchClient.d.ts +26 -26
  103. package/dist/network/FetchClient.js +99 -99
  104. package/dist/network/XhrClient.d.ts +40 -40
  105. package/dist/network/XhrClient.js +117 -117
  106. package/dist/operatingcontext/BaseOperatingContext.d.ts +40 -40
  107. package/dist/operatingcontext/BaseOperatingContext.js +44 -44
  108. package/dist/operatingcontext/StandardOperatingContext.d.ts +25 -25
  109. package/dist/operatingcontext/StandardOperatingContext.js +43 -43
  110. package/dist/operatingcontext/TeamsAppOperatingContext.d.ts +25 -25
  111. package/dist/operatingcontext/TeamsAppOperatingContext.js +42 -42
  112. package/dist/packageMetadata.d.ts +2 -2
  113. package/dist/packageMetadata.js +4 -4
  114. package/dist/request/AuthorizationCodeRequest.d.ts +8 -8
  115. package/dist/request/AuthorizationUrlRequest.d.ts +8 -8
  116. package/dist/request/EndSessionPopupRequest.d.ts +18 -18
  117. package/dist/request/EndSessionRequest.d.ts +15 -15
  118. package/dist/request/PopupRequest.d.ts +32 -32
  119. package/dist/request/PopupWindowAttributes.d.ts +15 -15
  120. package/dist/request/RedirectRequest.d.ts +33 -33
  121. package/dist/request/SilentRequest.d.ts +30 -30
  122. package/dist/request/SsoSilentRequest.d.ts +26 -26
  123. package/dist/telemetry/BrowserPerformanceClient.d.ts +38 -38
  124. package/dist/telemetry/BrowserPerformanceClient.js +124 -124
  125. package/dist/telemetry/BrowserPerformanceMeasurement.d.ts +21 -21
  126. package/dist/telemetry/BrowserPerformanceMeasurement.js +92 -92
  127. package/dist/utils/BrowserConstants.d.ts +166 -166
  128. package/dist/utils/BrowserConstants.js +214 -214
  129. package/dist/utils/BrowserProtocolUtils.d.ts +18 -18
  130. package/dist/utils/BrowserProtocolUtils.js +34 -34
  131. package/dist/utils/BrowserStringUtils.d.ts +26 -26
  132. package/dist/utils/BrowserStringUtils.js +149 -149
  133. package/dist/utils/BrowserUtils.d.ts +65 -65
  134. package/dist/utils/BrowserUtils.js +138 -138
  135. package/dist/utils/MathUtils.d.ts +11 -11
  136. package/dist/utils/MathUtils.js +21 -21
  137. package/lib/msal-browser.cjs.js +18383 -0
  138. package/lib/msal-browser.cjs.js.map +1 -0
  139. package/lib/msal-browser.js +18389 -0
  140. package/lib/msal-browser.js.map +1 -0
  141. package/lib/msal-browser.min.js +74 -0
  142. package/package.json +97 -95
@@ -1,4 +1,4 @@
1
- /*! @azure/msal-browser v3.0.0-alpha.1 2023-05-08 */
1
+ /*! @azure/msal-browser v3.0.0-alpha.2 2023-05-17 */
2
2
  'use strict';
3
3
  import { PerformanceEvents, TimeUtils, ScopeSet, ClientAuthError, AuthToken, Constants, AccountEntity, AuthorityType, AuthenticationScheme, PopTokenGenerator, IdTokenEntity, AccessTokenEntity, UrlString, OIDC_DEFAULT_SCOPES, PromptValue } from '@azure/msal-common';
4
4
  import { BaseInteractionClient } from './BaseInteractionClient.js';
@@ -7,521 +7,521 @@ import { NativeAuthError } from '../error/NativeAuthError.js';
7
7
  import { BrowserAuthError } from '../error/BrowserAuthError.js';
8
8
  import { SilentCacheClient } from './SilentCacheClient.js';
9
9
 
10
- /*
11
- * Copyright (c) Microsoft Corporation. All rights reserved.
12
- * Licensed under the MIT License.
13
- */
14
- class NativeInteractionClient extends BaseInteractionClient {
15
- constructor(config, browserStorage, browserCrypto, logger, eventHandler, navigationClient, apiId, performanceClient, provider, accountId, nativeStorageImpl, correlationId) {
16
- super(config, browserStorage, browserCrypto, logger, eventHandler, navigationClient, performanceClient, provider, correlationId);
17
- this.apiId = apiId;
18
- this.accountId = accountId;
19
- this.nativeMessageHandler = provider;
20
- this.nativeStorageManager = nativeStorageImpl;
21
- this.silentCacheClient = new SilentCacheClient(config, this.nativeStorageManager, browserCrypto, logger, eventHandler, navigationClient, performanceClient, provider, correlationId);
22
- }
23
- /**
24
- * Acquire token from native platform via browser extension
25
- * @param request
26
- */
27
- async acquireToken(request) {
28
- this.logger.trace("NativeInteractionClient - acquireToken called.");
29
- // start the perf measurement
30
- const nativeATMeasurement = this.performanceClient.startMeasurement(PerformanceEvents.NativeInteractionClientAcquireToken, request.correlationId);
31
- const reqTimestamp = TimeUtils.nowSeconds();
32
- // initialize native request
33
- const nativeRequest = await this.initializeNativeRequest(request);
34
- // check if the tokens can be retrieved from internal cache
35
- try {
36
- const result = await this.acquireTokensFromCache(this.accountId, nativeRequest);
37
- nativeATMeasurement.endMeasurement({
38
- success: true,
39
- isNativeBroker: false,
40
- fromCache: true,
41
- });
42
- return result;
43
- }
44
- catch (e) {
45
- // continue with a native call for any and all errors
46
- this.logger.info("MSAL internal Cache does not contain tokens, proceed to make a native call");
47
- }
48
- // fall back to native calls
49
- const messageBody = {
50
- method: NativeExtensionMethod.GetToken,
51
- request: nativeRequest,
52
- };
53
- const response = await this.nativeMessageHandler.sendMessage(messageBody);
54
- const validatedResponse = this.validateNativeResponse(response);
55
- return this.handleNativeResponse(validatedResponse, nativeRequest, reqTimestamp)
56
- .then((result) => {
57
- nativeATMeasurement.endMeasurement({
58
- success: true,
59
- isNativeBroker: true,
60
- requestId: result.requestId,
61
- });
62
- return result;
63
- })
64
- .catch((error) => {
65
- nativeATMeasurement.endMeasurement({
66
- success: false,
67
- errorCode: error.errorCode,
68
- subErrorCode: error.subError,
69
- isNativeBroker: true,
70
- });
71
- throw error;
72
- });
73
- }
74
- /**
75
- * Creates silent flow request
76
- * @param request
77
- * @param cachedAccount
78
- * @returns CommonSilentFlowRequest
79
- */
80
- createSilentCacheRequest(request, cachedAccount) {
81
- return {
82
- authority: request.authority,
83
- correlationId: this.correlationId,
84
- scopes: ScopeSet.fromString(request.scope).asArray(),
85
- account: cachedAccount,
86
- forceRefresh: false,
87
- };
88
- }
89
- /**
90
- * Fetches the tokens from the cache if un-expired
91
- * @param nativeAccountId
92
- * @param request
93
- * @returns authenticationResult
94
- */
95
- async acquireTokensFromCache(nativeAccountId, request) {
96
- if (!nativeAccountId) {
97
- this.logger.warning("NativeInteractionClient:acquireTokensFromCache - No nativeAccountId provided");
98
- throw ClientAuthError.createNoAccountFoundError();
99
- }
100
- // fetch the account from in-memory cache
101
- const account = this.browserStorage.getAccountInfoFilteredBy({
102
- nativeAccountId,
103
- });
104
- if (!account) {
105
- throw ClientAuthError.createNoAccountFoundError();
106
- }
107
- // leverage silent flow for cached tokens retrieval
108
- try {
109
- const silentRequest = this.createSilentCacheRequest(request, account);
110
- const result = await this.silentCacheClient.acquireToken(silentRequest);
111
- return result;
112
- }
113
- catch (e) {
114
- throw e;
115
- }
116
- }
117
- /**
118
- * Acquires a token from native platform then redirects to the redirectUri instead of returning the response
119
- * @param request
120
- */
121
- async acquireTokenRedirect(request) {
122
- this.logger.trace("NativeInteractionClient - acquireTokenRedirect called.");
123
- const nativeRequest = await this.initializeNativeRequest(request);
124
- const messageBody = {
125
- method: NativeExtensionMethod.GetToken,
126
- request: nativeRequest,
127
- };
128
- try {
129
- const response = await this.nativeMessageHandler.sendMessage(messageBody);
130
- this.validateNativeResponse(response);
131
- }
132
- catch (e) {
133
- // Only throw fatal errors here to allow application to fallback to regular redirect. Otherwise proceed and the error will be thrown in handleRedirectPromise
134
- if (e instanceof NativeAuthError && e.isFatal()) {
135
- throw e;
136
- }
137
- }
138
- this.browserStorage.setTemporaryCache(TemporaryCacheKeys.NATIVE_REQUEST, JSON.stringify(nativeRequest), true);
139
- const navigationOptions = {
140
- apiId: ApiId.acquireTokenRedirect,
141
- timeout: this.config.system.redirectNavigationTimeout,
142
- noHistory: false,
143
- };
144
- const redirectUri = this.config.auth.navigateToLoginRequestUrl
145
- ? window.location.href
146
- : this.getRedirectUri(request.redirectUri);
147
- await this.navigationClient.navigateExternal(redirectUri, navigationOptions); // Need to treat this as external to ensure handleRedirectPromise is run again
148
- }
149
- /**
150
- * If the previous page called native platform for a token using redirect APIs, send the same request again and return the response
151
- */
152
- async handleRedirectPromise() {
153
- this.logger.trace("NativeInteractionClient - handleRedirectPromise called.");
154
- if (!this.browserStorage.isInteractionInProgress(true)) {
155
- this.logger.info("handleRedirectPromise called but there is no interaction in progress, returning null.");
156
- return null;
157
- }
158
- // remove prompt from the request to prevent WAM from prompting twice
159
- const cachedRequest = this.browserStorage.getCachedNativeRequest();
160
- if (!cachedRequest) {
161
- this.logger.verbose("NativeInteractionClient - handleRedirectPromise called but there is no cached request, returning null.");
162
- return null;
163
- }
164
- const { prompt, ...request } = cachedRequest;
165
- if (prompt) {
166
- 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.");
167
- }
168
- this.browserStorage.removeItem(this.browserStorage.generateCacheKey(TemporaryCacheKeys.NATIVE_REQUEST));
169
- const messageBody = {
170
- method: NativeExtensionMethod.GetToken,
171
- request: request,
172
- };
173
- const reqTimestamp = TimeUtils.nowSeconds();
174
- try {
175
- this.logger.verbose("NativeInteractionClient - handleRedirectPromise sending message to native broker.");
176
- const response = await this.nativeMessageHandler.sendMessage(messageBody);
177
- this.validateNativeResponse(response);
178
- const result = this.handleNativeResponse(response, request, reqTimestamp);
179
- this.browserStorage.setInteractionInProgress(false);
180
- return result;
181
- }
182
- catch (e) {
183
- this.browserStorage.setInteractionInProgress(false);
184
- throw e;
185
- }
186
- }
187
- /**
188
- * Logout from native platform via browser extension
189
- * @param request
190
- */
191
- logout() {
192
- this.logger.trace("NativeInteractionClient - logout called.");
193
- return Promise.reject("Logout not implemented yet");
194
- }
195
- /**
196
- * Transform response from native platform into AuthenticationResult object which will be returned to the end user
197
- * @param response
198
- * @param request
199
- * @param reqTimestamp
200
- */
201
- async handleNativeResponse(response, request, reqTimestamp) {
202
- this.logger.trace("NativeInteractionClient - handleNativeResponse called.");
203
- if (response.account.id !== request.accountId) {
204
- // 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
205
- throw NativeAuthError.createUserSwitchError();
206
- }
207
- // Get the preferred_cache domain for the given authority
208
- const authority = await this.getDiscoveredAuthority(request.authority);
209
- const authorityPreferredCache = authority.getPreferredCache();
210
- // generate identifiers
211
- const idTokenObj = this.createIdTokenObj(response);
212
- const homeAccountIdentifier = this.createHomeAccountIdentifier(response, idTokenObj);
213
- const accountEntity = this.createAccountEntity(response, homeAccountIdentifier, idTokenObj, authorityPreferredCache);
214
- // generate authenticationResult
215
- const result = await this.generateAuthenticationResult(response, request, idTokenObj, accountEntity, authority.canonicalAuthority, reqTimestamp);
216
- // cache accounts and tokens in the appropriate storage
217
- this.cacheAccount(accountEntity);
218
- this.cacheNativeTokens(response, request, homeAccountIdentifier, idTokenObj, result.accessToken, result.tenantId, reqTimestamp);
219
- return result;
220
- }
221
- /**
222
- * Create an idToken Object (not entity)
223
- * @param response
224
- * @returns
225
- */
226
- createIdTokenObj(response) {
227
- return new AuthToken(response.id_token || Constants.EMPTY_STRING, this.browserCrypto);
228
- }
229
- /**
230
- * creates an homeAccountIdentifier for the account
231
- * @param response
232
- * @param idTokenObj
233
- * @returns
234
- */
235
- createHomeAccountIdentifier(response, idTokenObj) {
236
- // Save account in browser storage
237
- const homeAccountIdentifier = AccountEntity.generateHomeAccountId(response.client_info || Constants.EMPTY_STRING, AuthorityType.Default, this.logger, this.browserCrypto, idTokenObj);
238
- return homeAccountIdentifier;
239
- }
240
- /**
241
- * Creates account entity
242
- * @param response
243
- * @param homeAccountIdentifier
244
- * @param idTokenObj
245
- * @param authority
246
- * @returns
247
- */
248
- createAccountEntity(response, homeAccountIdentifier, idTokenObj, authority) {
249
- return AccountEntity.createAccount(response.client_info, homeAccountIdentifier, idTokenObj, undefined, undefined, undefined, authority, response.account.id);
250
- }
251
- /**
252
- * Helper to generate scopes
253
- * @param response
254
- * @param request
255
- * @returns
256
- */
257
- generateScopes(response, request) {
258
- return response.scope
259
- ? ScopeSet.fromString(response.scope)
260
- : ScopeSet.fromString(request.scope);
261
- }
262
- /**
263
- * If PoP token is requesred, records the PoP token if returned from the WAM, else generates one in the browser
264
- * @param request
265
- * @param response
266
- */
267
- async generatePopAccessToken(response, request) {
268
- if (request.tokenType === AuthenticationScheme.POP) {
269
- /**
270
- * This code prioritizes SHR returned from the native layer. In case of error/SHR not calculated from WAM and the AT
271
- * is still received, SHR is calculated locally
272
- */
273
- // Check if native layer returned an SHR token
274
- if (response.shr) {
275
- this.logger.trace("handleNativeServerResponse: SHR is enabled in native layer");
276
- return response.shr;
277
- }
278
- // Generate SHR in msal js if WAM does not compute it when POP is enabled
279
- const popTokenGenerator = new PopTokenGenerator(this.browserCrypto);
280
- const shrParameters = {
281
- resourceRequestMethod: request.resourceRequestMethod,
282
- resourceRequestUri: request.resourceRequestUri,
283
- shrClaims: request.shrClaims,
284
- shrNonce: request.shrNonce,
285
- };
286
- /**
287
- * KeyID must be present in the native request from when the PoP key was generated in order for
288
- * PopTokenGenerator to query the full key for signing
289
- */
290
- if (!request.keyId) {
291
- throw ClientAuthError.createKeyIdMissingError();
292
- }
293
- return await popTokenGenerator.signPopToken(response.access_token, request.keyId, shrParameters);
294
- }
295
- else {
296
- return response.access_token;
297
- }
298
- }
299
- /**
300
- * Generates authentication result
301
- * @param response
302
- * @param request
303
- * @param idTokenObj
304
- * @param accountEntity
305
- * @param authority
306
- * @param reqTimestamp
307
- * @returns
308
- */
309
- async generateAuthenticationResult(response, request, idTokenObj, accountEntity, authority, reqTimestamp) {
310
- // Add Native Broker fields to Telemetry
311
- const mats = this.addTelemetryFromNativeResponse(response);
312
- // If scopes not returned in server response, use request scopes
313
- const responseScopes = response.scope
314
- ? ScopeSet.fromString(response.scope)
315
- : ScopeSet.fromString(request.scope);
316
- const accountProperties = response.account.properties || {};
317
- const uid = accountProperties["UID"] ||
318
- idTokenObj.claims.oid ||
319
- idTokenObj.claims.sub ||
320
- Constants.EMPTY_STRING;
321
- const tid = accountProperties["TenantId"] ||
322
- idTokenObj.claims.tid ||
323
- Constants.EMPTY_STRING;
324
- // generate PoP token as needed
325
- const responseAccessToken = await this.generatePopAccessToken(response, request);
326
- const tokenType = request.tokenType === AuthenticationScheme.POP
327
- ? AuthenticationScheme.POP
328
- : AuthenticationScheme.BEARER;
329
- const result = {
330
- authority: authority,
331
- uniqueId: uid,
332
- tenantId: tid,
333
- scopes: responseScopes.asArray(),
334
- account: accountEntity.getAccountInfo(),
335
- idToken: response.id_token,
336
- idTokenClaims: idTokenObj.claims,
337
- accessToken: responseAccessToken,
338
- fromCache: mats ? this.isResponseFromCache(mats) : false,
339
- expiresOn: new Date(Number(reqTimestamp + response.expires_in) * 1000),
340
- tokenType: tokenType,
341
- correlationId: this.correlationId,
342
- state: response.state,
343
- fromNativeBroker: true,
344
- };
345
- return result;
346
- }
347
- /**
348
- * cache the account entity in browser storage
349
- * @param accountEntity
350
- */
351
- cacheAccount(accountEntity) {
352
- // Store the account info and hence `nativeAccountId` in browser cache
353
- this.browserStorage.setAccount(accountEntity);
354
- // Remove any existing cached tokens for this account in browser storage
355
- this.browserStorage.removeAccountContext(accountEntity).catch((e) => {
356
- this.logger.error(`Error occurred while removing account context from browser storage. ${e}`);
357
- });
358
- }
359
- /**
360
- * Stores the access_token and id_token in inmemory storage
361
- * @param response
362
- * @param request
363
- * @param homeAccountIdentifier
364
- * @param idTokenObj
365
- * @param responseAccessToken
366
- * @param tenantId
367
- * @param reqTimestamp
368
- */
369
- cacheNativeTokens(response, request, homeAccountIdentifier, idTokenObj, responseAccessToken, tenantId, reqTimestamp) {
370
- // cache idToken in inmemory storage
371
- const idTokenEntity = IdTokenEntity.createIdTokenEntity(homeAccountIdentifier, request.authority, response.id_token || Constants.EMPTY_STRING, request.clientId, idTokenObj.claims.tid || Constants.EMPTY_STRING);
372
- this.nativeStorageManager.setIdTokenCredential(idTokenEntity);
373
- // cache accessToken in inmemory storage
374
- const expiresIn = request.tokenType === AuthenticationScheme.POP
375
- ? Constants.SHR_NONCE_VALIDITY
376
- : (typeof response.expires_in === "string"
377
- ? parseInt(response.expires_in, 10)
378
- : response.expires_in) || 0;
379
- const tokenExpirationSeconds = reqTimestamp + expiresIn;
380
- const responseScopes = this.generateScopes(response, request);
381
- const accessTokenEntity = AccessTokenEntity.createAccessTokenEntity(homeAccountIdentifier, request.authority, responseAccessToken, request.clientId, tenantId, responseScopes.printScopes(), tokenExpirationSeconds, 0, this.browserCrypto);
382
- this.nativeStorageManager.setAccessTokenCredential(accessTokenEntity);
383
- }
384
- addTelemetryFromNativeResponse(response) {
385
- const mats = this.getMATSFromResponse(response);
386
- if (!mats) {
387
- return null;
388
- }
389
- this.performanceClient.addStaticFields({
390
- extensionId: this.nativeMessageHandler.getExtensionId(),
391
- extensionVersion: this.nativeMessageHandler.getExtensionVersion(),
392
- matsBrokerVersion: mats.broker_version,
393
- matsAccountJoinOnStart: mats.account_join_on_start,
394
- matsAccountJoinOnEnd: mats.account_join_on_end,
395
- matsDeviceJoin: mats.device_join,
396
- matsPromptBehavior: mats.prompt_behavior,
397
- matsApiErrorCode: mats.api_error_code,
398
- matsUiVisible: mats.ui_visible,
399
- matsSilentCode: mats.silent_code,
400
- matsSilentBiSubCode: mats.silent_bi_sub_code,
401
- matsSilentMessage: mats.silent_message,
402
- matsSilentStatus: mats.silent_status,
403
- matsHttpStatus: mats.http_status,
404
- matsHttpEventCount: mats.http_event_count,
405
- }, this.correlationId);
406
- return mats;
407
- }
408
- /**
409
- * Validates native platform response before processing
410
- * @param response
411
- */
412
- validateNativeResponse(response) {
413
- if (response.hasOwnProperty("access_token") &&
414
- response.hasOwnProperty("id_token") &&
415
- response.hasOwnProperty("client_info") &&
416
- response.hasOwnProperty("account") &&
417
- response.hasOwnProperty("scope") &&
418
- response.hasOwnProperty("expires_in")) {
419
- return response;
420
- }
421
- else {
422
- throw NativeAuthError.createUnexpectedError("Response missing expected properties.");
423
- }
424
- }
425
- /**
426
- * Gets MATS telemetry from native response
427
- * @param response
428
- * @returns
429
- */
430
- getMATSFromResponse(response) {
431
- if (response.properties.MATS) {
432
- try {
433
- return JSON.parse(response.properties.MATS);
434
- }
435
- catch (e) {
436
- this.logger.error("NativeInteractionClient - Error parsing MATS telemetry, returning null instead");
437
- }
438
- }
439
- return null;
440
- }
441
- /**
442
- * Returns whether or not response came from native cache
443
- * @param response
444
- * @returns
445
- */
446
- isResponseFromCache(mats) {
447
- if (typeof mats.is_cached === "undefined") {
448
- this.logger.verbose("NativeInteractionClient - MATS telemetry does not contain field indicating if response was served from cache. Returning false.");
449
- return false;
450
- }
451
- return !!mats.is_cached;
452
- }
453
- /**
454
- * Translates developer provided request object into NativeRequest object
455
- * @param request
456
- */
457
- async initializeNativeRequest(request) {
458
- this.logger.trace("NativeInteractionClient - initializeNativeRequest called");
459
- const authority = request.authority || this.config.auth.authority;
460
- const canonicalAuthority = new UrlString(authority);
461
- canonicalAuthority.validateAsUri();
462
- // 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.
463
- const { scopes, ...remainingProperties } = request;
464
- const scopeSet = new ScopeSet(scopes || []);
465
- scopeSet.appendScopes(OIDC_DEFAULT_SCOPES);
466
- const getPrompt = () => {
467
- // If request is silent, prompt is always none
468
- switch (this.apiId) {
469
- case ApiId.ssoSilent:
470
- case ApiId.acquireTokenSilent_silentFlow:
471
- this.logger.trace("initializeNativeRequest: silent request sets prompt to none");
472
- return PromptValue.NONE;
473
- }
474
- // Prompt not provided, request may proceed and native broker decides if it needs to prompt
475
- if (!request.prompt) {
476
- this.logger.trace("initializeNativeRequest: prompt was not provided");
477
- return undefined;
478
- }
479
- // If request is interactive, check if prompt provided is allowed to go directly to native broker
480
- switch (request.prompt) {
481
- case PromptValue.NONE:
482
- case PromptValue.CONSENT:
483
- case PromptValue.LOGIN:
484
- this.logger.trace("initializeNativeRequest: prompt is compatible with native flow");
485
- return request.prompt;
486
- default:
487
- this.logger.trace(`initializeNativeRequest: prompt = ${request.prompt} is not compatible with native flow`);
488
- throw BrowserAuthError.createNativePromptParameterNotSupportedError();
489
- }
490
- };
491
- const validatedRequest = {
492
- ...remainingProperties,
493
- accountId: this.accountId,
494
- clientId: this.config.auth.clientId,
495
- authority: canonicalAuthority.urlString,
496
- scope: scopeSet.printScopes(),
497
- redirectUri: this.getRedirectUri(request.redirectUri),
498
- prompt: getPrompt(),
499
- correlationId: this.correlationId,
500
- tokenType: request.authenticationScheme,
501
- windowTitleSubstring: document.title,
502
- extraParameters: {
503
- ...request.extraQueryParameters,
504
- ...request.tokenQueryParameters,
505
- telemetry: NativeConstants.MATS_TELEMETRY,
506
- },
507
- extendedExpiryToken: false, // Make this configurable?
508
- };
509
- if (request.authenticationScheme === AuthenticationScheme.POP) {
510
- // add POP request type
511
- const shrParameters = {
512
- resourceRequestUri: request.resourceRequestUri,
513
- resourceRequestMethod: request.resourceRequestMethod,
514
- shrClaims: request.shrClaims,
515
- shrNonce: request.shrNonce,
516
- };
517
- const popTokenGenerator = new PopTokenGenerator(this.browserCrypto);
518
- const reqCnfData = await popTokenGenerator.generateCnf(shrParameters);
519
- // to reduce the URL length, it is recommended to send the hash of the req_cnf instead of the whole string
520
- validatedRequest.reqCnf = reqCnfData.reqCnfHash;
521
- validatedRequest.keyId = reqCnfData.kid;
522
- }
523
- return validatedRequest;
524
- }
10
+ /*
11
+ * Copyright (c) Microsoft Corporation. All rights reserved.
12
+ * Licensed under the MIT License.
13
+ */
14
+ class NativeInteractionClient extends BaseInteractionClient {
15
+ constructor(config, browserStorage, browserCrypto, logger, eventHandler, navigationClient, apiId, performanceClient, provider, accountId, nativeStorageImpl, correlationId) {
16
+ super(config, browserStorage, browserCrypto, logger, eventHandler, navigationClient, performanceClient, provider, correlationId);
17
+ this.apiId = apiId;
18
+ this.accountId = accountId;
19
+ this.nativeMessageHandler = provider;
20
+ this.nativeStorageManager = nativeStorageImpl;
21
+ this.silentCacheClient = new SilentCacheClient(config, this.nativeStorageManager, browserCrypto, logger, eventHandler, navigationClient, performanceClient, provider, correlationId);
22
+ }
23
+ /**
24
+ * Acquire token from native platform via browser extension
25
+ * @param request
26
+ */
27
+ async acquireToken(request) {
28
+ this.logger.trace("NativeInteractionClient - acquireToken called.");
29
+ // start the perf measurement
30
+ const nativeATMeasurement = this.performanceClient.startMeasurement(PerformanceEvents.NativeInteractionClientAcquireToken, request.correlationId);
31
+ const reqTimestamp = TimeUtils.nowSeconds();
32
+ // initialize native request
33
+ const nativeRequest = await this.initializeNativeRequest(request);
34
+ // check if the tokens can be retrieved from internal cache
35
+ try {
36
+ const result = await this.acquireTokensFromCache(this.accountId, nativeRequest);
37
+ nativeATMeasurement.endMeasurement({
38
+ success: true,
39
+ isNativeBroker: false,
40
+ fromCache: true,
41
+ });
42
+ return result;
43
+ }
44
+ catch (e) {
45
+ // continue with a native call for any and all errors
46
+ this.logger.info("MSAL internal Cache does not contain tokens, proceed to make a native call");
47
+ }
48
+ // fall back to native calls
49
+ const messageBody = {
50
+ method: NativeExtensionMethod.GetToken,
51
+ request: nativeRequest,
52
+ };
53
+ const response = await this.nativeMessageHandler.sendMessage(messageBody);
54
+ const validatedResponse = this.validateNativeResponse(response);
55
+ return this.handleNativeResponse(validatedResponse, nativeRequest, reqTimestamp)
56
+ .then((result) => {
57
+ nativeATMeasurement.endMeasurement({
58
+ success: true,
59
+ isNativeBroker: true,
60
+ requestId: result.requestId,
61
+ });
62
+ return result;
63
+ })
64
+ .catch((error) => {
65
+ nativeATMeasurement.endMeasurement({
66
+ success: false,
67
+ errorCode: error.errorCode,
68
+ subErrorCode: error.subError,
69
+ isNativeBroker: true,
70
+ });
71
+ throw error;
72
+ });
73
+ }
74
+ /**
75
+ * Creates silent flow request
76
+ * @param request
77
+ * @param cachedAccount
78
+ * @returns CommonSilentFlowRequest
79
+ */
80
+ createSilentCacheRequest(request, cachedAccount) {
81
+ return {
82
+ authority: request.authority,
83
+ correlationId: this.correlationId,
84
+ scopes: ScopeSet.fromString(request.scope).asArray(),
85
+ account: cachedAccount,
86
+ forceRefresh: false,
87
+ };
88
+ }
89
+ /**
90
+ * Fetches the tokens from the cache if un-expired
91
+ * @param nativeAccountId
92
+ * @param request
93
+ * @returns authenticationResult
94
+ */
95
+ async acquireTokensFromCache(nativeAccountId, request) {
96
+ if (!nativeAccountId) {
97
+ this.logger.warning("NativeInteractionClient:acquireTokensFromCache - No nativeAccountId provided");
98
+ throw ClientAuthError.createNoAccountFoundError();
99
+ }
100
+ // fetch the account from in-memory cache
101
+ const account = this.browserStorage.getAccountInfoFilteredBy({
102
+ nativeAccountId,
103
+ });
104
+ if (!account) {
105
+ throw ClientAuthError.createNoAccountFoundError();
106
+ }
107
+ // leverage silent flow for cached tokens retrieval
108
+ try {
109
+ const silentRequest = this.createSilentCacheRequest(request, account);
110
+ const result = await this.silentCacheClient.acquireToken(silentRequest);
111
+ return result;
112
+ }
113
+ catch (e) {
114
+ throw e;
115
+ }
116
+ }
117
+ /**
118
+ * Acquires a token from native platform then redirects to the redirectUri instead of returning the response
119
+ * @param request
120
+ */
121
+ async acquireTokenRedirect(request) {
122
+ this.logger.trace("NativeInteractionClient - acquireTokenRedirect called.");
123
+ const nativeRequest = await this.initializeNativeRequest(request);
124
+ const messageBody = {
125
+ method: NativeExtensionMethod.GetToken,
126
+ request: nativeRequest,
127
+ };
128
+ try {
129
+ const response = await this.nativeMessageHandler.sendMessage(messageBody);
130
+ this.validateNativeResponse(response);
131
+ }
132
+ catch (e) {
133
+ // Only throw fatal errors here to allow application to fallback to regular redirect. Otherwise proceed and the error will be thrown in handleRedirectPromise
134
+ if (e instanceof NativeAuthError && e.isFatal()) {
135
+ throw e;
136
+ }
137
+ }
138
+ this.browserStorage.setTemporaryCache(TemporaryCacheKeys.NATIVE_REQUEST, JSON.stringify(nativeRequest), true);
139
+ const navigationOptions = {
140
+ apiId: ApiId.acquireTokenRedirect,
141
+ timeout: this.config.system.redirectNavigationTimeout,
142
+ noHistory: false,
143
+ };
144
+ const redirectUri = this.config.auth.navigateToLoginRequestUrl
145
+ ? window.location.href
146
+ : this.getRedirectUri(request.redirectUri);
147
+ await this.navigationClient.navigateExternal(redirectUri, navigationOptions); // Need to treat this as external to ensure handleRedirectPromise is run again
148
+ }
149
+ /**
150
+ * If the previous page called native platform for a token using redirect APIs, send the same request again and return the response
151
+ */
152
+ async handleRedirectPromise() {
153
+ this.logger.trace("NativeInteractionClient - handleRedirectPromise called.");
154
+ if (!this.browserStorage.isInteractionInProgress(true)) {
155
+ this.logger.info("handleRedirectPromise called but there is no interaction in progress, returning null.");
156
+ return null;
157
+ }
158
+ // remove prompt from the request to prevent WAM from prompting twice
159
+ const cachedRequest = this.browserStorage.getCachedNativeRequest();
160
+ if (!cachedRequest) {
161
+ this.logger.verbose("NativeInteractionClient - handleRedirectPromise called but there is no cached request, returning null.");
162
+ return null;
163
+ }
164
+ const { prompt, ...request } = cachedRequest;
165
+ if (prompt) {
166
+ 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.");
167
+ }
168
+ this.browserStorage.removeItem(this.browserStorage.generateCacheKey(TemporaryCacheKeys.NATIVE_REQUEST));
169
+ const messageBody = {
170
+ method: NativeExtensionMethod.GetToken,
171
+ request: request,
172
+ };
173
+ const reqTimestamp = TimeUtils.nowSeconds();
174
+ try {
175
+ this.logger.verbose("NativeInteractionClient - handleRedirectPromise sending message to native broker.");
176
+ const response = await this.nativeMessageHandler.sendMessage(messageBody);
177
+ this.validateNativeResponse(response);
178
+ const result = this.handleNativeResponse(response, request, reqTimestamp);
179
+ this.browserStorage.setInteractionInProgress(false);
180
+ return result;
181
+ }
182
+ catch (e) {
183
+ this.browserStorage.setInteractionInProgress(false);
184
+ throw e;
185
+ }
186
+ }
187
+ /**
188
+ * Logout from native platform via browser extension
189
+ * @param request
190
+ */
191
+ logout() {
192
+ this.logger.trace("NativeInteractionClient - logout called.");
193
+ return Promise.reject("Logout not implemented yet");
194
+ }
195
+ /**
196
+ * Transform response from native platform into AuthenticationResult object which will be returned to the end user
197
+ * @param response
198
+ * @param request
199
+ * @param reqTimestamp
200
+ */
201
+ async handleNativeResponse(response, request, reqTimestamp) {
202
+ this.logger.trace("NativeInteractionClient - handleNativeResponse called.");
203
+ if (response.account.id !== request.accountId) {
204
+ // 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
205
+ throw NativeAuthError.createUserSwitchError();
206
+ }
207
+ // Get the preferred_cache domain for the given authority
208
+ const authority = await this.getDiscoveredAuthority(request.authority);
209
+ const authorityPreferredCache = authority.getPreferredCache();
210
+ // generate identifiers
211
+ const idTokenObj = this.createIdTokenObj(response);
212
+ const homeAccountIdentifier = this.createHomeAccountIdentifier(response, idTokenObj);
213
+ const accountEntity = this.createAccountEntity(response, homeAccountIdentifier, idTokenObj, authorityPreferredCache);
214
+ // generate authenticationResult
215
+ const result = await this.generateAuthenticationResult(response, request, idTokenObj, accountEntity, authority.canonicalAuthority, reqTimestamp);
216
+ // cache accounts and tokens in the appropriate storage
217
+ this.cacheAccount(accountEntity);
218
+ this.cacheNativeTokens(response, request, homeAccountIdentifier, idTokenObj, result.accessToken, result.tenantId, reqTimestamp);
219
+ return result;
220
+ }
221
+ /**
222
+ * Create an idToken Object (not entity)
223
+ * @param response
224
+ * @returns
225
+ */
226
+ createIdTokenObj(response) {
227
+ return new AuthToken(response.id_token || Constants.EMPTY_STRING, this.browserCrypto);
228
+ }
229
+ /**
230
+ * creates an homeAccountIdentifier for the account
231
+ * @param response
232
+ * @param idTokenObj
233
+ * @returns
234
+ */
235
+ createHomeAccountIdentifier(response, idTokenObj) {
236
+ // Save account in browser storage
237
+ const homeAccountIdentifier = AccountEntity.generateHomeAccountId(response.client_info || Constants.EMPTY_STRING, AuthorityType.Default, this.logger, this.browserCrypto, idTokenObj);
238
+ return homeAccountIdentifier;
239
+ }
240
+ /**
241
+ * Creates account entity
242
+ * @param response
243
+ * @param homeAccountIdentifier
244
+ * @param idTokenObj
245
+ * @param authority
246
+ * @returns
247
+ */
248
+ createAccountEntity(response, homeAccountIdentifier, idTokenObj, authority) {
249
+ return AccountEntity.createAccount(response.client_info, homeAccountIdentifier, idTokenObj, undefined, undefined, undefined, authority, response.account.id);
250
+ }
251
+ /**
252
+ * Helper to generate scopes
253
+ * @param response
254
+ * @param request
255
+ * @returns
256
+ */
257
+ generateScopes(response, request) {
258
+ return response.scope
259
+ ? ScopeSet.fromString(response.scope)
260
+ : ScopeSet.fromString(request.scope);
261
+ }
262
+ /**
263
+ * If PoP token is requesred, records the PoP token if returned from the WAM, else generates one in the browser
264
+ * @param request
265
+ * @param response
266
+ */
267
+ async generatePopAccessToken(response, request) {
268
+ if (request.tokenType === AuthenticationScheme.POP) {
269
+ /**
270
+ * This code prioritizes SHR returned from the native layer. In case of error/SHR not calculated from WAM and the AT
271
+ * is still received, SHR is calculated locally
272
+ */
273
+ // Check if native layer returned an SHR token
274
+ if (response.shr) {
275
+ this.logger.trace("handleNativeServerResponse: SHR is enabled in native layer");
276
+ return response.shr;
277
+ }
278
+ // Generate SHR in msal js if WAM does not compute it when POP is enabled
279
+ const popTokenGenerator = new PopTokenGenerator(this.browserCrypto);
280
+ const shrParameters = {
281
+ resourceRequestMethod: request.resourceRequestMethod,
282
+ resourceRequestUri: request.resourceRequestUri,
283
+ shrClaims: request.shrClaims,
284
+ shrNonce: request.shrNonce,
285
+ };
286
+ /**
287
+ * KeyID must be present in the native request from when the PoP key was generated in order for
288
+ * PopTokenGenerator to query the full key for signing
289
+ */
290
+ if (!request.keyId) {
291
+ throw ClientAuthError.createKeyIdMissingError();
292
+ }
293
+ return await popTokenGenerator.signPopToken(response.access_token, request.keyId, shrParameters);
294
+ }
295
+ else {
296
+ return response.access_token;
297
+ }
298
+ }
299
+ /**
300
+ * Generates authentication result
301
+ * @param response
302
+ * @param request
303
+ * @param idTokenObj
304
+ * @param accountEntity
305
+ * @param authority
306
+ * @param reqTimestamp
307
+ * @returns
308
+ */
309
+ async generateAuthenticationResult(response, request, idTokenObj, accountEntity, authority, reqTimestamp) {
310
+ // Add Native Broker fields to Telemetry
311
+ const mats = this.addTelemetryFromNativeResponse(response);
312
+ // If scopes not returned in server response, use request scopes
313
+ const responseScopes = response.scope
314
+ ? ScopeSet.fromString(response.scope)
315
+ : ScopeSet.fromString(request.scope);
316
+ const accountProperties = response.account.properties || {};
317
+ const uid = accountProperties["UID"] ||
318
+ idTokenObj.claims.oid ||
319
+ idTokenObj.claims.sub ||
320
+ Constants.EMPTY_STRING;
321
+ const tid = accountProperties["TenantId"] ||
322
+ idTokenObj.claims.tid ||
323
+ Constants.EMPTY_STRING;
324
+ // generate PoP token as needed
325
+ const responseAccessToken = await this.generatePopAccessToken(response, request);
326
+ const tokenType = request.tokenType === AuthenticationScheme.POP
327
+ ? AuthenticationScheme.POP
328
+ : AuthenticationScheme.BEARER;
329
+ const result = {
330
+ authority: authority,
331
+ uniqueId: uid,
332
+ tenantId: tid,
333
+ scopes: responseScopes.asArray(),
334
+ account: accountEntity.getAccountInfo(),
335
+ idToken: response.id_token,
336
+ idTokenClaims: idTokenObj.claims,
337
+ accessToken: responseAccessToken,
338
+ fromCache: mats ? this.isResponseFromCache(mats) : false,
339
+ expiresOn: new Date(Number(reqTimestamp + response.expires_in) * 1000),
340
+ tokenType: tokenType,
341
+ correlationId: this.correlationId,
342
+ state: response.state,
343
+ fromNativeBroker: true,
344
+ };
345
+ return result;
346
+ }
347
+ /**
348
+ * cache the account entity in browser storage
349
+ * @param accountEntity
350
+ */
351
+ cacheAccount(accountEntity) {
352
+ // Store the account info and hence `nativeAccountId` in browser cache
353
+ this.browserStorage.setAccount(accountEntity);
354
+ // Remove any existing cached tokens for this account in browser storage
355
+ this.browserStorage.removeAccountContext(accountEntity).catch((e) => {
356
+ this.logger.error(`Error occurred while removing account context from browser storage. ${e}`);
357
+ });
358
+ }
359
+ /**
360
+ * Stores the access_token and id_token in inmemory storage
361
+ * @param response
362
+ * @param request
363
+ * @param homeAccountIdentifier
364
+ * @param idTokenObj
365
+ * @param responseAccessToken
366
+ * @param tenantId
367
+ * @param reqTimestamp
368
+ */
369
+ cacheNativeTokens(response, request, homeAccountIdentifier, idTokenObj, responseAccessToken, tenantId, reqTimestamp) {
370
+ // cache idToken in inmemory storage
371
+ const idTokenEntity = IdTokenEntity.createIdTokenEntity(homeAccountIdentifier, request.authority, response.id_token || Constants.EMPTY_STRING, request.clientId, idTokenObj.claims.tid || Constants.EMPTY_STRING);
372
+ this.nativeStorageManager.setIdTokenCredential(idTokenEntity);
373
+ // cache accessToken in inmemory storage
374
+ const expiresIn = request.tokenType === AuthenticationScheme.POP
375
+ ? Constants.SHR_NONCE_VALIDITY
376
+ : (typeof response.expires_in === "string"
377
+ ? parseInt(response.expires_in, 10)
378
+ : response.expires_in) || 0;
379
+ const tokenExpirationSeconds = reqTimestamp + expiresIn;
380
+ const responseScopes = this.generateScopes(response, request);
381
+ const accessTokenEntity = AccessTokenEntity.createAccessTokenEntity(homeAccountIdentifier, request.authority, responseAccessToken, request.clientId, tenantId, responseScopes.printScopes(), tokenExpirationSeconds, 0, this.browserCrypto);
382
+ this.nativeStorageManager.setAccessTokenCredential(accessTokenEntity);
383
+ }
384
+ addTelemetryFromNativeResponse(response) {
385
+ const mats = this.getMATSFromResponse(response);
386
+ if (!mats) {
387
+ return null;
388
+ }
389
+ this.performanceClient.addStaticFields({
390
+ extensionId: this.nativeMessageHandler.getExtensionId(),
391
+ extensionVersion: this.nativeMessageHandler.getExtensionVersion(),
392
+ matsBrokerVersion: mats.broker_version,
393
+ matsAccountJoinOnStart: mats.account_join_on_start,
394
+ matsAccountJoinOnEnd: mats.account_join_on_end,
395
+ matsDeviceJoin: mats.device_join,
396
+ matsPromptBehavior: mats.prompt_behavior,
397
+ matsApiErrorCode: mats.api_error_code,
398
+ matsUiVisible: mats.ui_visible,
399
+ matsSilentCode: mats.silent_code,
400
+ matsSilentBiSubCode: mats.silent_bi_sub_code,
401
+ matsSilentMessage: mats.silent_message,
402
+ matsSilentStatus: mats.silent_status,
403
+ matsHttpStatus: mats.http_status,
404
+ matsHttpEventCount: mats.http_event_count,
405
+ }, this.correlationId);
406
+ return mats;
407
+ }
408
+ /**
409
+ * Validates native platform response before processing
410
+ * @param response
411
+ */
412
+ validateNativeResponse(response) {
413
+ if (response.hasOwnProperty("access_token") &&
414
+ response.hasOwnProperty("id_token") &&
415
+ response.hasOwnProperty("client_info") &&
416
+ response.hasOwnProperty("account") &&
417
+ response.hasOwnProperty("scope") &&
418
+ response.hasOwnProperty("expires_in")) {
419
+ return response;
420
+ }
421
+ else {
422
+ throw NativeAuthError.createUnexpectedError("Response missing expected properties.");
423
+ }
424
+ }
425
+ /**
426
+ * Gets MATS telemetry from native response
427
+ * @param response
428
+ * @returns
429
+ */
430
+ getMATSFromResponse(response) {
431
+ if (response.properties.MATS) {
432
+ try {
433
+ return JSON.parse(response.properties.MATS);
434
+ }
435
+ catch (e) {
436
+ this.logger.error("NativeInteractionClient - Error parsing MATS telemetry, returning null instead");
437
+ }
438
+ }
439
+ return null;
440
+ }
441
+ /**
442
+ * Returns whether or not response came from native cache
443
+ * @param response
444
+ * @returns
445
+ */
446
+ isResponseFromCache(mats) {
447
+ if (typeof mats.is_cached === "undefined") {
448
+ this.logger.verbose("NativeInteractionClient - MATS telemetry does not contain field indicating if response was served from cache. Returning false.");
449
+ return false;
450
+ }
451
+ return !!mats.is_cached;
452
+ }
453
+ /**
454
+ * Translates developer provided request object into NativeRequest object
455
+ * @param request
456
+ */
457
+ async initializeNativeRequest(request) {
458
+ this.logger.trace("NativeInteractionClient - initializeNativeRequest called");
459
+ const authority = request.authority || this.config.auth.authority;
460
+ const canonicalAuthority = new UrlString(authority);
461
+ canonicalAuthority.validateAsUri();
462
+ // 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.
463
+ const { scopes, ...remainingProperties } = request;
464
+ const scopeSet = new ScopeSet(scopes || []);
465
+ scopeSet.appendScopes(OIDC_DEFAULT_SCOPES);
466
+ const getPrompt = () => {
467
+ // If request is silent, prompt is always none
468
+ switch (this.apiId) {
469
+ case ApiId.ssoSilent:
470
+ case ApiId.acquireTokenSilent_silentFlow:
471
+ this.logger.trace("initializeNativeRequest: silent request sets prompt to none");
472
+ return PromptValue.NONE;
473
+ }
474
+ // Prompt not provided, request may proceed and native broker decides if it needs to prompt
475
+ if (!request.prompt) {
476
+ this.logger.trace("initializeNativeRequest: prompt was not provided");
477
+ return undefined;
478
+ }
479
+ // If request is interactive, check if prompt provided is allowed to go directly to native broker
480
+ switch (request.prompt) {
481
+ case PromptValue.NONE:
482
+ case PromptValue.CONSENT:
483
+ case PromptValue.LOGIN:
484
+ this.logger.trace("initializeNativeRequest: prompt is compatible with native flow");
485
+ return request.prompt;
486
+ default:
487
+ this.logger.trace(`initializeNativeRequest: prompt = ${request.prompt} is not compatible with native flow`);
488
+ throw BrowserAuthError.createNativePromptParameterNotSupportedError();
489
+ }
490
+ };
491
+ const validatedRequest = {
492
+ ...remainingProperties,
493
+ accountId: this.accountId,
494
+ clientId: this.config.auth.clientId,
495
+ authority: canonicalAuthority.urlString,
496
+ scope: scopeSet.printScopes(),
497
+ redirectUri: this.getRedirectUri(request.redirectUri),
498
+ prompt: getPrompt(),
499
+ correlationId: this.correlationId,
500
+ tokenType: request.authenticationScheme,
501
+ windowTitleSubstring: document.title,
502
+ extraParameters: {
503
+ ...request.extraQueryParameters,
504
+ ...request.tokenQueryParameters,
505
+ telemetry: NativeConstants.MATS_TELEMETRY,
506
+ },
507
+ extendedExpiryToken: false, // Make this configurable?
508
+ };
509
+ if (request.authenticationScheme === AuthenticationScheme.POP) {
510
+ // add POP request type
511
+ const shrParameters = {
512
+ resourceRequestUri: request.resourceRequestUri,
513
+ resourceRequestMethod: request.resourceRequestMethod,
514
+ shrClaims: request.shrClaims,
515
+ shrNonce: request.shrNonce,
516
+ };
517
+ const popTokenGenerator = new PopTokenGenerator(this.browserCrypto);
518
+ const reqCnfData = await popTokenGenerator.generateCnf(shrParameters);
519
+ // to reduce the URL length, it is recommended to send the hash of the req_cnf instead of the whole string
520
+ validatedRequest.reqCnf = reqCnfData.reqCnfHash;
521
+ validatedRequest.keyId = reqCnfData.kid;
522
+ }
523
+ return validatedRequest;
524
+ }
525
525
  }
526
526
 
527
527
  export { NativeInteractionClient };