@azure/msal-browser 3.0.0-alpha.1 → 3.0.0-beta.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 (178) 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 +376 -377
  14. package/dist/cache/BrowserCacheManager.d.ts.map +1 -1
  15. package/dist/cache/BrowserCacheManager.js +1275 -1276
  16. package/dist/cache/BrowserCacheManager.js.map +1 -1
  17. package/dist/cache/BrowserStorage.d.ts +11 -11
  18. package/dist/cache/BrowserStorage.js +35 -35
  19. package/dist/cache/CryptoKeyStore.d.ts +18 -17
  20. package/dist/cache/CryptoKeyStore.d.ts.map +1 -1
  21. package/dist/cache/CryptoKeyStore.js +40 -41
  22. package/dist/cache/CryptoKeyStore.js.map +1 -1
  23. package/dist/cache/DatabaseStorage.d.ts +56 -56
  24. package/dist/cache/DatabaseStorage.js +190 -190
  25. package/dist/cache/IAsyncMemoryStorage.d.ts +27 -27
  26. package/dist/cache/ITokenCache.d.ts +10 -10
  27. package/dist/cache/IWindowStorage.d.ts +27 -27
  28. package/dist/cache/MemoryStorage.d.ts +11 -11
  29. package/dist/cache/MemoryStorage.js +31 -31
  30. package/dist/cache/TokenCache.d.ts +76 -76
  31. package/dist/cache/TokenCache.js +225 -225
  32. package/dist/config/Configuration.d.ts +187 -203
  33. package/dist/config/Configuration.d.ts.map +1 -1
  34. package/dist/config/Configuration.js +97 -101
  35. package/dist/config/Configuration.js.map +1 -1
  36. package/dist/controllers/ControllerFactory.d.ts +9 -9
  37. package/dist/controllers/ControllerFactory.js +37 -37
  38. package/dist/controllers/IController.d.ts +66 -66
  39. package/dist/controllers/IController.d.ts.map +1 -1
  40. package/dist/controllers/StandardController.d.ts +413 -413
  41. package/dist/controllers/StandardController.d.ts.map +1 -1
  42. package/dist/controllers/StandardController.js +1277 -1272
  43. package/dist/controllers/StandardController.js.map +1 -1
  44. package/dist/crypto/BrowserCrypto.d.ts +49 -61
  45. package/dist/crypto/BrowserCrypto.d.ts.map +1 -1
  46. package/dist/crypto/BrowserCrypto.js +93 -134
  47. package/dist/crypto/BrowserCrypto.js.map +1 -1
  48. package/dist/crypto/CryptoOps.d.ts +72 -73
  49. package/dist/crypto/CryptoOps.d.ts.map +1 -1
  50. package/dist/crypto/CryptoOps.js +150 -150
  51. package/dist/crypto/CryptoOps.js.map +1 -1
  52. package/dist/crypto/GuidGenerator.d.ts +12 -12
  53. package/dist/crypto/GuidGenerator.js +96 -96
  54. package/dist/crypto/ISubtleCrypto.d.ts +9 -9
  55. package/dist/crypto/ModernBrowserCrypto.d.ts +9 -9
  56. package/dist/crypto/ModernBrowserCrypto.js +24 -24
  57. package/dist/crypto/PkceGenerator.d.ts +24 -24
  58. package/dist/crypto/PkceGenerator.js +58 -58
  59. package/dist/crypto/SignedHttpRequest.d.ts +30 -30
  60. package/dist/crypto/SignedHttpRequest.js +39 -39
  61. package/dist/encode/Base64Decode.d.ts +22 -22
  62. package/dist/encode/Base64Decode.js +73 -73
  63. package/dist/encode/Base64Encode.d.ts +31 -31
  64. package/dist/encode/Base64Encode.js +79 -79
  65. package/dist/error/BrowserAuthError.d.ts +382 -382
  66. package/dist/error/BrowserAuthError.js +483 -483
  67. package/dist/error/BrowserConfigurationAuthError.d.ts +70 -70
  68. package/dist/error/BrowserConfigurationAuthError.js +96 -96
  69. package/dist/error/NativeAuthError.d.ts +57 -56
  70. package/dist/error/NativeAuthError.d.ts.map +1 -1
  71. package/dist/error/NativeAuthError.js +93 -88
  72. package/dist/error/NativeAuthError.js.map +1 -1
  73. package/dist/event/EventHandler.d.ts +41 -41
  74. package/dist/event/EventHandler.js +119 -119
  75. package/dist/event/EventMessage.d.ts +25 -25
  76. package/dist/event/EventMessage.d.ts.map +1 -1
  77. package/dist/event/EventMessage.js +68 -67
  78. package/dist/event/EventMessage.js.map +1 -1
  79. package/dist/event/EventType.d.ts +28 -26
  80. package/dist/event/EventType.d.ts.map +1 -1
  81. package/dist/event/EventType.js +32 -32
  82. package/dist/event/EventType.js.map +1 -1
  83. package/dist/index.d.ts +35 -35
  84. package/dist/index.js +1 -1
  85. package/dist/interaction_client/BaseInteractionClient.d.ts +53 -52
  86. package/dist/interaction_client/BaseInteractionClient.d.ts.map +1 -1
  87. package/dist/interaction_client/BaseInteractionClient.js +151 -138
  88. package/dist/interaction_client/BaseInteractionClient.js.map +1 -1
  89. package/dist/interaction_client/HybridSpaAuthorizationCodeClient.d.ts +4 -4
  90. package/dist/interaction_client/HybridSpaAuthorizationCodeClient.js +10 -10
  91. package/dist/interaction_client/NativeInteractionClient.d.ts +148 -148
  92. package/dist/interaction_client/NativeInteractionClient.d.ts.map +1 -1
  93. package/dist/interaction_client/NativeInteractionClient.js +521 -517
  94. package/dist/interaction_client/NativeInteractionClient.js.map +1 -1
  95. package/dist/interaction_client/PopupClient.d.ts +111 -111
  96. package/dist/interaction_client/PopupClient.js +476 -476
  97. package/dist/interaction_client/RedirectClient.d.ts +48 -48
  98. package/dist/interaction_client/RedirectClient.d.ts.map +1 -1
  99. package/dist/interaction_client/RedirectClient.js +291 -290
  100. package/dist/interaction_client/RedirectClient.js.map +1 -1
  101. package/dist/interaction_client/SilentAuthCodeClient.d.ts +22 -22
  102. package/dist/interaction_client/SilentAuthCodeClient.js +62 -62
  103. package/dist/interaction_client/SilentCacheClient.d.ts +21 -21
  104. package/dist/interaction_client/SilentCacheClient.js +67 -67
  105. package/dist/interaction_client/SilentCacheClient.js.map +1 -1
  106. package/dist/interaction_client/SilentIframeClient.d.ts +31 -31
  107. package/dist/interaction_client/SilentIframeClient.js +127 -127
  108. package/dist/interaction_client/SilentRefreshClient.d.ts +19 -19
  109. package/dist/interaction_client/SilentRefreshClient.js +62 -62
  110. package/dist/interaction_client/SilentRefreshClient.js.map +1 -1
  111. package/dist/interaction_client/StandardInteractionClient.d.ts +59 -59
  112. package/dist/interaction_client/StandardInteractionClient.js +259 -259
  113. package/dist/interaction_handler/InteractionHandler.d.ts +39 -39
  114. package/dist/interaction_handler/InteractionHandler.js +127 -127
  115. package/dist/interaction_handler/RedirectHandler.d.ts +24 -24
  116. package/dist/interaction_handler/RedirectHandler.js +118 -118
  117. package/dist/interaction_handler/SilentHandler.d.ts +47 -47
  118. package/dist/interaction_handler/SilentHandler.js +162 -162
  119. package/dist/internals.d.ts +23 -23
  120. package/dist/internals.js +4 -4
  121. package/dist/navigation/INavigationClient.d.ts +16 -16
  122. package/dist/navigation/NavigationClient.d.ts +22 -22
  123. package/dist/navigation/NavigationClient.js +40 -40
  124. package/dist/navigation/NavigationOptions.d.ts +12 -12
  125. package/dist/network/FetchClient.d.ts +26 -26
  126. package/dist/network/FetchClient.js +99 -99
  127. package/dist/network/XhrClient.d.ts +40 -40
  128. package/dist/network/XhrClient.js +117 -117
  129. package/dist/operatingcontext/BaseOperatingContext.d.ts +40 -40
  130. package/dist/operatingcontext/BaseOperatingContext.js +44 -44
  131. package/dist/operatingcontext/StandardOperatingContext.d.ts +25 -25
  132. package/dist/operatingcontext/StandardOperatingContext.js +43 -43
  133. package/dist/operatingcontext/TeamsAppOperatingContext.d.ts +25 -25
  134. package/dist/operatingcontext/TeamsAppOperatingContext.js +42 -42
  135. package/dist/packageMetadata.d.ts +2 -2
  136. package/dist/packageMetadata.d.ts.map +1 -1
  137. package/dist/packageMetadata.js +4 -4
  138. package/dist/request/AuthorizationCodeRequest.d.ts +8 -8
  139. package/dist/request/AuthorizationUrlRequest.d.ts +8 -8
  140. package/dist/request/EndSessionPopupRequest.d.ts +18 -18
  141. package/dist/request/EndSessionRequest.d.ts +15 -15
  142. package/dist/request/PopupRequest.d.ts +32 -32
  143. package/dist/request/PopupWindowAttributes.d.ts +15 -15
  144. package/dist/request/RedirectRequest.d.ts +33 -33
  145. package/dist/request/SilentRequest.d.ts +30 -30
  146. package/dist/request/SsoSilentRequest.d.ts +26 -26
  147. package/dist/telemetry/BrowserPerformanceClient.d.ts +37 -38
  148. package/dist/telemetry/BrowserPerformanceClient.d.ts.map +1 -1
  149. package/dist/telemetry/BrowserPerformanceClient.js +124 -124
  150. package/dist/telemetry/BrowserPerformanceClient.js.map +1 -1
  151. package/dist/telemetry/BrowserPerformanceMeasurement.d.ts +21 -21
  152. package/dist/telemetry/BrowserPerformanceMeasurement.js +92 -92
  153. package/dist/utils/BrowserConstants.d.ts +176 -166
  154. package/dist/utils/BrowserConstants.d.ts.map +1 -1
  155. package/dist/utils/BrowserConstants.js +205 -215
  156. package/dist/utils/BrowserConstants.js.map +1 -1
  157. package/dist/utils/BrowserProtocolUtils.d.ts +18 -18
  158. package/dist/utils/BrowserProtocolUtils.js +34 -34
  159. package/dist/utils/BrowserStringUtils.d.ts +26 -26
  160. package/dist/utils/BrowserStringUtils.js +149 -149
  161. package/dist/utils/BrowserUtils.d.ts +65 -65
  162. package/dist/utils/BrowserUtils.js +138 -138
  163. package/dist/utils/MathUtils.d.ts +11 -11
  164. package/dist/utils/MathUtils.js +21 -21
  165. package/lib/msal-browser.cjs.js +18227 -0
  166. package/lib/msal-browser.cjs.js.map +1 -0
  167. package/lib/msal-browser.js +18233 -0
  168. package/lib/msal-browser.js.map +1 -0
  169. package/lib/msal-browser.min.js +63 -0
  170. package/package.json +101 -95
  171. package/dist/crypto/MsBrowserCrypto.d.ts +0 -10
  172. package/dist/crypto/MsBrowserCrypto.d.ts.map +0 -1
  173. package/dist/crypto/MsBrowserCrypto.js +0 -88
  174. package/dist/crypto/MsBrowserCrypto.js.map +0 -1
  175. package/dist/crypto/MsrBrowserCrypto.d.ts +0 -18
  176. package/dist/crypto/MsrBrowserCrypto.d.ts.map +0 -1
  177. package/dist/crypto/MsrBrowserCrypto.js +0 -35
  178. package/dist/crypto/MsrBrowserCrypto.js.map +0 -1
@@ -1,527 +1,531 @@
1
- /*! @azure/msal-browser v3.0.0-alpha.1 2023-05-08 */
1
+ /*! @azure/msal-browser v3.0.0-beta.0 2023-06-19 */
2
2
  'use strict';
3
- import { PerformanceEvents, TimeUtils, ScopeSet, ClientAuthError, AuthToken, Constants, AccountEntity, AuthorityType, AuthenticationScheme, PopTokenGenerator, IdTokenEntity, AccessTokenEntity, UrlString, OIDC_DEFAULT_SCOPES, PromptValue } from '@azure/msal-common';
3
+ import { PerformanceEvents, TimeUtils, ScopeSet, ClientAuthError, AuthToken, Constants, AccountEntity, AuthorityType, AuthenticationScheme, PopTokenGenerator, IdTokenEntity, AccessTokenEntity, CacheRecord, UrlString, OIDC_DEFAULT_SCOPES, PromptValue } from '@azure/msal-common';
4
4
  import { BaseInteractionClient } from './BaseInteractionClient.js';
5
5
  import { TemporaryCacheKeys, NativeConstants, NativeExtensionMethod, ApiId } from '../utils/BrowserConstants.js';
6
6
  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 browser 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, accountEntity, 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, accountEntity, idTokenObj, responseAccessToken, tenantId, reqTimestamp) {
370
+ const cachedIdToken = IdTokenEntity.createIdTokenEntity(homeAccountIdentifier, request.authority, response.id_token || Constants.EMPTY_STRING, request.clientId, idTokenObj.claims.tid || Constants.EMPTY_STRING);
371
+ // cache accessToken in inmemory storage
372
+ const expiresIn = request.tokenType === AuthenticationScheme.POP
373
+ ? Constants.SHR_NONCE_VALIDITY
374
+ : (typeof response.expires_in === "string"
375
+ ? parseInt(response.expires_in, 10)
376
+ : response.expires_in) || 0;
377
+ const tokenExpirationSeconds = reqTimestamp + expiresIn;
378
+ const responseScopes = this.generateScopes(response, request);
379
+ const cachedAccessToken = AccessTokenEntity.createAccessTokenEntity(homeAccountIdentifier, request.authority, responseAccessToken, request.clientId, idTokenObj
380
+ ? idTokenObj.claims.tid || Constants.EMPTY_STRING
381
+ : tenantId, responseScopes.printScopes(), tokenExpirationSeconds, 0, this.browserCrypto);
382
+ const nativeCacheRecord = new CacheRecord(accountEntity, cachedIdToken, cachedAccessToken);
383
+ this.nativeStorageManager.saveCacheRecord(nativeCacheRecord);
384
+ }
385
+ addTelemetryFromNativeResponse(response) {
386
+ const mats = this.getMATSFromResponse(response);
387
+ if (!mats) {
388
+ return null;
389
+ }
390
+ this.performanceClient.addStaticFields({
391
+ extensionId: this.nativeMessageHandler.getExtensionId(),
392
+ extensionVersion: this.nativeMessageHandler.getExtensionVersion(),
393
+ matsBrokerVersion: mats.broker_version,
394
+ matsAccountJoinOnStart: mats.account_join_on_start,
395
+ matsAccountJoinOnEnd: mats.account_join_on_end,
396
+ matsDeviceJoin: mats.device_join,
397
+ matsPromptBehavior: mats.prompt_behavior,
398
+ matsApiErrorCode: mats.api_error_code,
399
+ matsUiVisible: mats.ui_visible,
400
+ matsSilentCode: mats.silent_code,
401
+ matsSilentBiSubCode: mats.silent_bi_sub_code,
402
+ matsSilentMessage: mats.silent_message,
403
+ matsSilentStatus: mats.silent_status,
404
+ matsHttpStatus: mats.http_status,
405
+ matsHttpEventCount: mats.http_event_count,
406
+ }, this.correlationId);
407
+ return mats;
408
+ }
409
+ /**
410
+ * Validates native platform response before processing
411
+ * @param response
412
+ */
413
+ validateNativeResponse(response) {
414
+ if (response.hasOwnProperty("access_token") &&
415
+ response.hasOwnProperty("id_token") &&
416
+ response.hasOwnProperty("client_info") &&
417
+ response.hasOwnProperty("account") &&
418
+ response.hasOwnProperty("scope") &&
419
+ response.hasOwnProperty("expires_in")) {
420
+ return response;
421
+ }
422
+ else {
423
+ throw NativeAuthError.createUnexpectedError("Response missing expected properties.");
424
+ }
425
+ }
426
+ /**
427
+ * Gets MATS telemetry from native response
428
+ * @param response
429
+ * @returns
430
+ */
431
+ getMATSFromResponse(response) {
432
+ if (response.properties.MATS) {
433
+ try {
434
+ return JSON.parse(response.properties.MATS);
435
+ }
436
+ catch (e) {
437
+ this.logger.error("NativeInteractionClient - Error parsing MATS telemetry, returning null instead");
438
+ }
439
+ }
440
+ return null;
441
+ }
442
+ /**
443
+ * Returns whether or not response came from native cache
444
+ * @param response
445
+ * @returns
446
+ */
447
+ isResponseFromCache(mats) {
448
+ if (typeof mats.is_cached === "undefined") {
449
+ this.logger.verbose("NativeInteractionClient - MATS telemetry does not contain field indicating if response was served from cache. Returning false.");
450
+ return false;
451
+ }
452
+ return !!mats.is_cached;
453
+ }
454
+ /**
455
+ * Translates developer provided request object into NativeRequest object
456
+ * @param request
457
+ */
458
+ async initializeNativeRequest(request) {
459
+ this.logger.trace("NativeInteractionClient - initializeNativeRequest called");
460
+ const authority = request.authority || this.config.auth.authority;
461
+ if (request.account) {
462
+ await this.validateRequestAuthority(authority, request.account);
463
+ }
464
+ const canonicalAuthority = new UrlString(authority);
465
+ canonicalAuthority.validateAsUri();
466
+ // 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.
467
+ const { scopes, ...remainingProperties } = request;
468
+ const scopeSet = new ScopeSet(scopes || []);
469
+ scopeSet.appendScopes(OIDC_DEFAULT_SCOPES);
470
+ const getPrompt = () => {
471
+ // If request is silent, prompt is always none
472
+ switch (this.apiId) {
473
+ case ApiId.ssoSilent:
474
+ case ApiId.acquireTokenSilent_silentFlow:
475
+ this.logger.trace("initializeNativeRequest: silent request sets prompt to none");
476
+ return PromptValue.NONE;
477
+ }
478
+ // Prompt not provided, request may proceed and native broker decides if it needs to prompt
479
+ if (!request.prompt) {
480
+ this.logger.trace("initializeNativeRequest: prompt was not provided");
481
+ return undefined;
482
+ }
483
+ // If request is interactive, check if prompt provided is allowed to go directly to native broker
484
+ switch (request.prompt) {
485
+ case PromptValue.NONE:
486
+ case PromptValue.CONSENT:
487
+ case PromptValue.LOGIN:
488
+ this.logger.trace("initializeNativeRequest: prompt is compatible with native flow");
489
+ return request.prompt;
490
+ default:
491
+ this.logger.trace(`initializeNativeRequest: prompt = ${request.prompt} is not compatible with native flow`);
492
+ throw BrowserAuthError.createNativePromptParameterNotSupportedError();
493
+ }
494
+ };
495
+ const validatedRequest = {
496
+ ...remainingProperties,
497
+ accountId: this.accountId,
498
+ clientId: this.config.auth.clientId,
499
+ authority: canonicalAuthority.urlString,
500
+ scope: scopeSet.printScopes(),
501
+ redirectUri: this.getRedirectUri(request.redirectUri),
502
+ prompt: getPrompt(),
503
+ correlationId: this.correlationId,
504
+ tokenType: request.authenticationScheme,
505
+ windowTitleSubstring: document.title,
506
+ extraParameters: {
507
+ ...request.extraQueryParameters,
508
+ ...request.tokenQueryParameters,
509
+ telemetry: NativeConstants.MATS_TELEMETRY,
510
+ },
511
+ extendedExpiryToken: false, // Make this configurable?
512
+ };
513
+ if (request.authenticationScheme === AuthenticationScheme.POP) {
514
+ // add POP request type
515
+ const shrParameters = {
516
+ resourceRequestUri: request.resourceRequestUri,
517
+ resourceRequestMethod: request.resourceRequestMethod,
518
+ shrClaims: request.shrClaims,
519
+ shrNonce: request.shrNonce,
520
+ };
521
+ const popTokenGenerator = new PopTokenGenerator(this.browserCrypto);
522
+ const reqCnfData = await popTokenGenerator.generateCnf(shrParameters);
523
+ // to reduce the URL length, it is recommended to send the hash of the req_cnf instead of the whole string
524
+ validatedRequest.reqCnf = reqCnfData.reqCnfHash;
525
+ validatedRequest.keyId = reqCnfData.kid;
526
+ }
527
+ return validatedRequest;
528
+ }
525
529
  }
526
530
 
527
531
  export { NativeInteractionClient };