@azure/msal-node 2.1.0 → 2.2.0-alpha.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 (134) hide show
  1. package/dist/cache/ITokenCache.d.ts +15 -15
  2. package/dist/cache/NodeStorage.cjs +401 -401
  3. package/dist/cache/NodeStorage.d.ts +182 -182
  4. package/dist/cache/NodeStorage.mjs +401 -401
  5. package/dist/cache/TokenCache.cjs +265 -265
  6. package/dist/cache/TokenCache.d.ts +90 -90
  7. package/dist/cache/TokenCache.mjs +265 -265
  8. package/dist/cache/distributed/DistributedCachePlugin.cjs +26 -26
  9. package/dist/cache/distributed/DistributedCachePlugin.d.ts +10 -10
  10. package/dist/cache/distributed/DistributedCachePlugin.mjs +26 -26
  11. package/dist/cache/distributed/ICacheClient.d.ts +17 -17
  12. package/dist/cache/distributed/IPartitionManager.d.ts +28 -28
  13. package/dist/cache/serializer/Deserializer.cjs +173 -173
  14. package/dist/cache/serializer/Deserializer.d.ts +42 -42
  15. package/dist/cache/serializer/Deserializer.mjs +173 -173
  16. package/dist/cache/serializer/Serializer.cjs +134 -134
  17. package/dist/cache/serializer/Serializer.d.ts +39 -39
  18. package/dist/cache/serializer/Serializer.mjs +134 -134
  19. package/dist/cache/serializer/SerializerTypes.d.ts +101 -101
  20. package/dist/client/ClientApplication.cjs +333 -333
  21. package/dist/client/ClientApplication.cjs.map +1 -1
  22. package/dist/client/ClientApplication.d.ts +142 -142
  23. package/dist/client/ClientApplication.d.ts.map +1 -1
  24. package/dist/client/ClientApplication.mjs +334 -334
  25. package/dist/client/ClientApplication.mjs.map +1 -1
  26. package/dist/client/ClientAssertion.cjs +116 -116
  27. package/dist/client/ClientAssertion.cjs.map +1 -1
  28. package/dist/client/ClientAssertion.d.ts +46 -46
  29. package/dist/client/ClientAssertion.d.ts.map +1 -1
  30. package/dist/client/ClientAssertion.mjs +117 -117
  31. package/dist/client/ClientAssertion.mjs.map +1 -1
  32. package/dist/client/ClientCredentialClient.cjs +189 -190
  33. package/dist/client/ClientCredentialClient.cjs.map +1 -1
  34. package/dist/client/ClientCredentialClient.d.ts +33 -34
  35. package/dist/client/ClientCredentialClient.d.ts.map +1 -1
  36. package/dist/client/ClientCredentialClient.mjs +190 -191
  37. package/dist/client/ClientCredentialClient.mjs.map +1 -1
  38. package/dist/client/ConfidentialClientApplication.cjs +163 -163
  39. package/dist/client/ConfidentialClientApplication.cjs.map +1 -1
  40. package/dist/client/ConfidentialClientApplication.d.ts +58 -58
  41. package/dist/client/ConfidentialClientApplication.d.ts.map +1 -1
  42. package/dist/client/ConfidentialClientApplication.mjs +164 -164
  43. package/dist/client/ConfidentialClientApplication.mjs.map +1 -1
  44. package/dist/client/DeviceCodeClient.cjs +207 -207
  45. package/dist/client/DeviceCodeClient.cjs.map +1 -1
  46. package/dist/client/DeviceCodeClient.d.ts +53 -53
  47. package/dist/client/DeviceCodeClient.d.ts.map +1 -1
  48. package/dist/client/DeviceCodeClient.mjs +208 -208
  49. package/dist/client/DeviceCodeClient.mjs.map +1 -1
  50. package/dist/client/IConfidentialClientApplication.d.ts +39 -39
  51. package/dist/client/IPublicClientApplication.d.ts +42 -42
  52. package/dist/client/OnBehalfOfClient.cjs +202 -202
  53. package/dist/client/OnBehalfOfClient.cjs.map +1 -1
  54. package/dist/client/OnBehalfOfClient.d.ts +47 -47
  55. package/dist/client/OnBehalfOfClient.d.ts.map +1 -1
  56. package/dist/client/OnBehalfOfClient.mjs +203 -203
  57. package/dist/client/OnBehalfOfClient.mjs.map +1 -1
  58. package/dist/client/PublicClientApplication.cjs +229 -182
  59. package/dist/client/PublicClientApplication.cjs.map +1 -1
  60. package/dist/client/PublicClientApplication.d.ts +71 -65
  61. package/dist/client/PublicClientApplication.d.ts.map +1 -1
  62. package/dist/client/PublicClientApplication.mjs +231 -184
  63. package/dist/client/PublicClientApplication.mjs.map +1 -1
  64. package/dist/client/UsernamePasswordClient.cjs +95 -95
  65. package/dist/client/UsernamePasswordClient.d.ts +25 -25
  66. package/dist/client/UsernamePasswordClient.mjs +95 -95
  67. package/dist/config/Configuration.cjs +72 -72
  68. package/dist/config/Configuration.d.ts +107 -107
  69. package/dist/config/Configuration.mjs +72 -72
  70. package/dist/crypto/CryptoProvider.cjs +75 -75
  71. package/dist/crypto/CryptoProvider.d.ts +52 -52
  72. package/dist/crypto/CryptoProvider.mjs +75 -75
  73. package/dist/crypto/GuidGenerator.cjs +22 -22
  74. package/dist/crypto/GuidGenerator.d.ts +14 -14
  75. package/dist/crypto/GuidGenerator.mjs +22 -22
  76. package/dist/crypto/HashUtils.cjs +13 -13
  77. package/dist/crypto/HashUtils.d.ts +8 -8
  78. package/dist/crypto/HashUtils.mjs +13 -13
  79. package/dist/crypto/PkceGenerator.cjs +49 -49
  80. package/dist/crypto/PkceGenerator.d.ts +22 -22
  81. package/dist/crypto/PkceGenerator.mjs +49 -49
  82. package/dist/error/NodeAuthError.cjs +85 -85
  83. package/dist/error/NodeAuthError.d.ts +65 -65
  84. package/dist/error/NodeAuthError.mjs +85 -85
  85. package/dist/index.cjs +17 -1
  86. package/dist/index.cjs.map +1 -1
  87. package/dist/index.d.ts +42 -42
  88. package/dist/index.d.ts.map +1 -1
  89. package/dist/index.mjs +2 -2
  90. package/dist/internals.cjs +8 -8
  91. package/dist/internals.d.ts +6 -6
  92. package/dist/internals.mjs +8 -8
  93. package/dist/network/HttpClient.cjs +276 -276
  94. package/dist/network/HttpClient.d.ts +25 -25
  95. package/dist/network/HttpClient.mjs +276 -276
  96. package/dist/network/ILoopbackClient.d.ts +10 -10
  97. package/dist/network/LoopbackClient.cjs +75 -84
  98. package/dist/network/LoopbackClient.cjs.map +1 -1
  99. package/dist/network/LoopbackClient.d.ts +21 -21
  100. package/dist/network/LoopbackClient.d.ts.map +1 -1
  101. package/dist/network/LoopbackClient.mjs +76 -85
  102. package/dist/network/LoopbackClient.mjs.map +1 -1
  103. package/dist/packageMetadata.cjs +3 -3
  104. package/dist/packageMetadata.d.ts +2 -2
  105. package/dist/packageMetadata.mjs +3 -3
  106. package/dist/request/AuthorizationCodeRequest.d.ts +21 -21
  107. package/dist/request/AuthorizationUrlRequest.d.ts +33 -33
  108. package/dist/request/ClientCredentialRequest.d.ts +14 -14
  109. package/dist/request/DeviceCodeRequest.d.ts +15 -15
  110. package/dist/request/InteractiveRequest.d.ts +22 -22
  111. package/dist/request/OnBehalfOfRequest.d.ts +14 -14
  112. package/dist/request/RefreshTokenRequest.d.ts +17 -17
  113. package/dist/request/SignOutRequest.d.ts +5 -5
  114. package/dist/request/SilentFlowRequest.d.ts +16 -16
  115. package/dist/request/UsernamePasswordRequest.d.ts +19 -19
  116. package/dist/utils/Constants.cjs +80 -80
  117. package/dist/utils/Constants.d.ts +86 -86
  118. package/dist/utils/Constants.mjs +80 -80
  119. package/dist/utils/EncodingUtils.cjs +44 -44
  120. package/dist/utils/EncodingUtils.d.ts +26 -26
  121. package/dist/utils/EncodingUtils.mjs +44 -44
  122. package/dist/utils/NetworkUtils.cjs +38 -38
  123. package/dist/utils/NetworkUtils.d.ts +5 -5
  124. package/dist/utils/NetworkUtils.mjs +38 -38
  125. package/package.json +2 -2
  126. package/src/client/ClientApplication.ts +3 -2
  127. package/src/client/ClientAssertion.ts +7 -2
  128. package/src/client/ClientCredentialClient.ts +32 -34
  129. package/src/client/ConfidentialClientApplication.ts +11 -4
  130. package/src/client/DeviceCodeClient.ts +16 -7
  131. package/src/client/OnBehalfOfClient.ts +11 -4
  132. package/src/client/PublicClientApplication.ts +69 -13
  133. package/src/index.ts +4 -0
  134. package/src/network/LoopbackClient.ts +17 -33
@@ -10,7 +10,7 @@ import {
10
10
  Authority,
11
11
  BaseClient,
12
12
  CacheOutcome,
13
- ClientAuthError,
13
+ ClientAuthErrorCodes,
14
14
  ClientConfiguration,
15
15
  CommonClientCredentialRequest,
16
16
  Constants,
@@ -27,6 +27,7 @@ import {
27
27
  TimeUtils,
28
28
  TokenCacheContext,
29
29
  UrlString,
30
+ createClientAuthError,
30
31
  } from "@azure/msal-common";
31
32
 
32
33
  /**
@@ -35,7 +36,6 @@ import {
35
36
  export class ClientCredentialClient extends BaseClient {
36
37
  private scopeSet: ScopeSet;
37
38
  private readonly appTokenProvider?: IAppTokenProvider;
38
- private lastCacheOutcome: CacheOutcome;
39
39
 
40
40
  constructor(
41
41
  configuration: ClientConfiguration,
@@ -58,20 +58,17 @@ export class ClientCredentialClient extends BaseClient {
58
58
  return await this.executeTokenRequest(request, this.authority);
59
59
  }
60
60
 
61
- const cachedAuthenticationResult =
61
+ const [cachedAuthenticationResult, lastCacheOutcome] =
62
62
  await this.getCachedAuthenticationResult(request);
63
63
 
64
64
  if (cachedAuthenticationResult) {
65
65
  // if the token is not expired but must be refreshed; get a new one in the background
66
- if (
67
- this.lastCacheOutcome ===
68
- CacheOutcome.REFRESH_CACHED_ACCESS_TOKEN
69
- ) {
66
+ if (lastCacheOutcome === CacheOutcome.PROACTIVELY_REFRESHED) {
70
67
  this.logger.info(
71
68
  "ClientCredentialClient:getCachedAuthenticationResult - Cached access token's refreshOn property has been exceeded'. It's not expired, but must be refreshed."
72
69
  );
73
70
 
74
- // return the cached token, don't wait for the result of this request
71
+ // refresh the access token in the background
75
72
  const refreshAccessToken = true;
76
73
  await this.executeTokenRequest(
77
74
  request,
@@ -80,10 +77,7 @@ export class ClientCredentialClient extends BaseClient {
80
77
  );
81
78
  }
82
79
 
83
- // reset the last cache outcome
84
- this.lastCacheOutcome = CacheOutcome.NO_CACHE_HIT;
85
-
86
- // otherwise, the token is not expired and does not need to be refreshed
80
+ // return the cached token
87
81
  return cachedAuthenticationResult;
88
82
  } else {
89
83
  return await this.executeTokenRequest(request, this.authority);
@@ -95,7 +89,9 @@ export class ClientCredentialClient extends BaseClient {
95
89
  */
96
90
  private async getCachedAuthenticationResult(
97
91
  request: CommonClientCredentialRequest
98
- ): Promise<AuthenticationResult | null> {
92
+ ): Promise<[AuthenticationResult | null, CacheOutcome]> {
93
+ let lastCacheOutcome: CacheOutcome = CacheOutcome.NOT_APPLICABLE;
94
+
99
95
  // read the user-supplied cache into memory, if applicable
100
96
  let cacheContext;
101
97
  if (this.config.serializableCache && this.config.persistencePlugin) {
@@ -118,11 +114,10 @@ export class ClientCredentialClient extends BaseClient {
118
114
 
119
115
  // must refresh due to non-existent access_token
120
116
  if (!cachedAccessToken) {
121
- this.lastCacheOutcome = CacheOutcome.NO_CACHED_ACCESS_TOKEN;
122
117
  this.serverTelemetryManager?.setCacheOutcome(
123
118
  CacheOutcome.NO_CACHED_ACCESS_TOKEN
124
119
  );
125
- return null;
120
+ return [null, CacheOutcome.NO_CACHED_ACCESS_TOKEN];
126
121
  }
127
122
 
128
123
  // must refresh due to the expires_in value
@@ -132,12 +127,10 @@ export class ClientCredentialClient extends BaseClient {
132
127
  this.config.systemOptions.tokenRenewalOffsetSeconds
133
128
  )
134
129
  ) {
135
- this.lastCacheOutcome = CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED;
136
130
  this.serverTelemetryManager?.setCacheOutcome(
137
131
  CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED
138
132
  );
139
-
140
- return null;
133
+ return [null, CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED];
141
134
  }
142
135
 
143
136
  // must refresh (in the background) due to the refresh_in value
@@ -145,25 +138,28 @@ export class ClientCredentialClient extends BaseClient {
145
138
  cachedAccessToken.refreshOn &&
146
139
  TimeUtils.isTokenExpired(cachedAccessToken.refreshOn.toString(), 0)
147
140
  ) {
148
- this.lastCacheOutcome = CacheOutcome.REFRESH_CACHED_ACCESS_TOKEN;
141
+ lastCacheOutcome = CacheOutcome.PROACTIVELY_REFRESHED;
149
142
  this.serverTelemetryManager?.setCacheOutcome(
150
- CacheOutcome.REFRESH_CACHED_ACCESS_TOKEN
143
+ CacheOutcome.PROACTIVELY_REFRESHED
151
144
  );
152
145
  }
153
146
 
154
- return await ResponseHandler.generateAuthenticationResult(
155
- this.cryptoUtils,
156
- this.authority,
157
- {
158
- account: null,
159
- idToken: null,
160
- accessToken: cachedAccessToken,
161
- refreshToken: null,
162
- appMetadata: null,
163
- },
164
- true,
165
- request
166
- );
147
+ return [
148
+ await ResponseHandler.generateAuthenticationResult(
149
+ this.cryptoUtils,
150
+ this.authority,
151
+ {
152
+ account: null,
153
+ idToken: null,
154
+ accessToken: cachedAccessToken,
155
+ refreshToken: null,
156
+ appMetadata: null,
157
+ },
158
+ true,
159
+ request
160
+ ),
161
+ lastCacheOutcome,
162
+ ];
167
163
  }
168
164
 
169
165
  /**
@@ -185,7 +181,9 @@ export class ClientCredentialClient extends BaseClient {
185
181
  if (accessTokens.length < 1) {
186
182
  return null;
187
183
  } else if (accessTokens.length > 1) {
188
- throw ClientAuthError.createMultipleMatchingTokensInCacheError();
184
+ throw createClientAuthError(
185
+ ClientAuthErrorCodes.multipleMatchingTokens
186
+ );
189
187
  }
190
188
  return accessTokens[0] as AccessTokenEntity;
191
189
  }
@@ -17,7 +17,6 @@ import {
17
17
  CommonClientCredentialRequest,
18
18
  CommonOnBehalfOfRequest,
19
19
  AuthenticationResult,
20
- ClientAuthError,
21
20
  AzureRegionConfiguration,
22
21
  AuthError,
23
22
  Constants,
@@ -25,6 +24,8 @@ import {
25
24
  OIDC_DEFAULT_SCOPES,
26
25
  UrlString,
27
26
  AADAuthorityConstants,
27
+ createClientAuthError,
28
+ ClientAuthErrorCodes,
28
29
  } from "@azure/msal-common";
29
30
  import { IConfidentialClientApplication } from "./IConfidentialClientApplication.js";
30
31
  import { OnBehalfOfRequest } from "../request/OnBehalfOfRequest.js";
@@ -125,7 +126,9 @@ export class ConfidentialClientApplication
125
126
  tenantId as AADAuthorityConstants
126
127
  )
127
128
  ) {
128
- throw ClientAuthError.createMissingTenantIdError();
129
+ throw createClientAuthError(
130
+ ClientAuthErrorCodes.missingTenantIdError
131
+ );
129
132
  }
130
133
 
131
134
  const azureRegionConfiguration: AzureRegionConfiguration = {
@@ -233,7 +236,9 @@ export class ConfidentialClientApplication
233
236
  (clientAssertionNotEmpty && certificateNotEmpty) ||
234
237
  (clientSecretNotEmpty && certificateNotEmpty)
235
238
  ) {
236
- throw ClientAuthError.createInvalidCredentialError();
239
+ throw createClientAuthError(
240
+ ClientAuthErrorCodes.invalidClientCredential
241
+ );
237
242
  }
238
243
 
239
244
  if (configuration.auth.clientSecret) {
@@ -249,7 +254,9 @@ export class ConfidentialClientApplication
249
254
  }
250
255
 
251
256
  if (!certificateNotEmpty) {
252
- throw ClientAuthError.createInvalidCredentialError();
257
+ throw createClientAuthError(
258
+ ClientAuthErrorCodes.invalidClientCredential
259
+ );
253
260
  } else {
254
261
  this.clientAssertion = ClientAssertion.fromCertificate(
255
262
  certificate.thumbprint,
@@ -4,9 +4,10 @@
4
4
  */
5
5
 
6
6
  import {
7
+ AuthErrorCodes,
7
8
  AuthenticationResult,
8
9
  BaseClient,
9
- ClientAuthError,
10
+ ClientAuthErrorCodes,
10
11
  ClientConfiguration,
11
12
  CommonDeviceCodeRequest,
12
13
  Constants,
@@ -17,10 +18,11 @@ import {
17
18
  ResponseHandler,
18
19
  ServerAuthorizationTokenResponse,
19
20
  ServerDeviceCodeResponse,
20
- ServerError,
21
21
  StringUtils,
22
22
  TimeUtils,
23
23
  UrlString,
24
+ createAuthError,
25
+ createClientAuthError,
24
26
  } from "@azure/msal-common";
25
27
 
26
28
  /**
@@ -200,7 +202,9 @@ export class DeviceCodeClient extends BaseClient {
200
202
  this.logger.error(
201
203
  "Token request cancelled by setting DeviceCodeRequest.cancel = true"
202
204
  );
203
- throw ClientAuthError.createDeviceCodeCancelledError();
205
+ throw createClientAuthError(
206
+ ClientAuthErrorCodes.deviceCodePollingCancelled
207
+ );
204
208
  } else if (
205
209
  userSpecifiedTimeout &&
206
210
  userSpecifiedTimeout < deviceCodeExpirationTime &&
@@ -209,7 +213,9 @@ export class DeviceCodeClient extends BaseClient {
209
213
  this.logger.error(
210
214
  `User defined timeout for device code polling reached. The timeout was set for ${userSpecifiedTimeout}`
211
215
  );
212
- throw ClientAuthError.createUserTimeoutReachedError();
216
+ throw createClientAuthError(
217
+ ClientAuthErrorCodes.userTimeoutReached
218
+ );
213
219
  } else if (TimeUtils.nowSeconds() > deviceCodeExpirationTime) {
214
220
  if (userSpecifiedTimeout) {
215
221
  this.logger.verbose(
@@ -219,7 +225,7 @@ export class DeviceCodeClient extends BaseClient {
219
225
  this.logger.error(
220
226
  `Device code expired. Expiration time of device code was ${deviceCodeExpirationTime}`
221
227
  );
222
- throw ClientAuthError.createDeviceCodeExpiredError();
228
+ throw createClientAuthError(ClientAuthErrorCodes.deviceCodeExpired);
223
229
  }
224
230
  return true;
225
231
  }
@@ -295,7 +301,8 @@ export class DeviceCodeClient extends BaseClient {
295
301
  this.logger.info(
296
302
  "Unexpected error in polling from the server"
297
303
  );
298
- throw ServerError.createPostRequestFailed(
304
+ throw createAuthError(
305
+ AuthErrorCodes.postRequestFailed,
299
306
  response.body.error
300
307
  );
301
308
  }
@@ -312,7 +319,9 @@ export class DeviceCodeClient extends BaseClient {
312
319
  * and in the rare case the conditionals in continuePolling() may not catch everything...
313
320
  */
314
321
  this.logger.error("Polling stopped for unknown reasons.");
315
- throw ClientAuthError.createDeviceCodeUnknownError();
322
+ throw createClientAuthError(
323
+ ClientAuthErrorCodes.deviceCodeUnknownError
324
+ );
316
325
  }
317
326
 
318
327
  /**
@@ -14,10 +14,11 @@ import {
14
14
  AuthToken,
15
15
  BaseClient,
16
16
  CacheOutcome,
17
- ClientAuthError,
17
+ ClientAuthErrorCodes,
18
18
  ClientConfiguration,
19
19
  CommonOnBehalfOfRequest,
20
20
  Constants,
21
+ createClientAuthError,
21
22
  CredentialFilter,
22
23
  CredentialType,
23
24
  GrantType,
@@ -101,7 +102,9 @@ export class OnBehalfOfClient extends BaseClient {
101
102
  this.logger.info(
102
103
  "SilentFlowClient:acquireCachedToken - No access token found in cache for the given properties."
103
104
  );
104
- throw ClientAuthError.createRefreshRequiredError();
105
+ throw createClientAuthError(
106
+ ClientAuthErrorCodes.tokenRefreshRequired
107
+ );
105
108
  } else if (
106
109
  TimeUtils.isTokenExpired(
107
110
  cachedAccessToken.expiresOn,
@@ -115,7 +118,9 @@ export class OnBehalfOfClient extends BaseClient {
115
118
  this.logger.info(
116
119
  `OnbehalfofFlow:getCachedAuthenticationResult - Cached access token is expired or will expire within ${this.config.systemOptions.tokenRenewalOffsetSeconds} seconds.`
117
120
  );
118
- throw ClientAuthError.createRefreshRequiredError();
121
+ throw createClientAuthError(
122
+ ClientAuthErrorCodes.tokenRefreshRequired
123
+ );
119
124
  }
120
125
 
121
126
  // fetch the idToken from cache
@@ -229,7 +234,9 @@ export class OnBehalfOfClient extends BaseClient {
229
234
  if (numAccessTokens < 1) {
230
235
  return null;
231
236
  } else if (numAccessTokens > 1) {
232
- throw ClientAuthError.createMultipleMatchingTokensInCacheError();
237
+ throw createClientAuthError(
238
+ ClientAuthErrorCodes.multipleMatchingTokens
239
+ );
233
240
  }
234
241
 
235
242
  return accessTokens[0] as AccessTokenEntity;
@@ -3,7 +3,11 @@
3
3
  * Licensed under the MIT License.
4
4
  */
5
5
 
6
- import { ApiId, Constants } from "../utils/Constants.js";
6
+ import {
7
+ ApiId,
8
+ Constants,
9
+ LOOPBACK_SERVER_CONSTANTS,
10
+ } from "../utils/Constants.js";
7
11
  import {
8
12
  AuthenticationResult,
9
13
  CommonDeviceCodeRequest,
@@ -26,7 +30,7 @@ import { DeviceCodeRequest } from "../request/DeviceCodeRequest.js";
26
30
  import { AuthorizationUrlRequest } from "../request/AuthorizationUrlRequest.js";
27
31
  import { AuthorizationCodeRequest } from "../request/AuthorizationCodeRequest.js";
28
32
  import { InteractiveRequest } from "../request/InteractiveRequest.js";
29
- import { NodeAuthError } from "../error/NodeAuthError.js";
33
+ import { NodeAuthError, NodeAuthErrorMessage } from "../error/NodeAuthError.js";
30
34
  import { LoopbackClient } from "../network/LoopbackClient.js";
31
35
  import { SilentFlowRequest } from "../request/SilentFlowRequest.js";
32
36
  import { SignOutRequest } from "../request/SignOutRequest.js";
@@ -167,13 +171,21 @@ export class PublicClientApplication
167
171
  const loopbackClient: ILoopbackClient =
168
172
  customLoopbackClient || new LoopbackClient();
169
173
 
170
- let authCodeListener: Promise<ServerAuthorizationCodeResponse>;
174
+ let authCodeResponse: ServerAuthorizationCodeResponse = {};
175
+ let authCodeListenerError: AuthError | null = null;
171
176
  try {
172
- authCodeListener = loopbackClient.listenForAuthCode(
173
- successTemplate,
174
- errorTemplate
175
- );
176
- const redirectUri = loopbackClient.getRedirectUri();
177
+ const authCodeListener = loopbackClient
178
+ .listenForAuthCode(successTemplate, errorTemplate)
179
+ .then((response) => {
180
+ authCodeResponse = response;
181
+ })
182
+ .catch((e) => {
183
+ // Store the promise instead of throwing so we can control when its thrown
184
+ authCodeListenerError = e;
185
+ });
186
+
187
+ // Wait for server to be listening
188
+ const redirectUri = await this.waitForRedirectUri(loopbackClient);
177
189
 
178
190
  const validRequest: AuthorizationUrlRequest = {
179
191
  ...remainingProperties,
@@ -187,9 +199,10 @@ export class PublicClientApplication
187
199
 
188
200
  const authCodeUrl = await this.getAuthCodeUrl(validRequest);
189
201
  await openBrowser(authCodeUrl);
190
- const authCodeResponse = await authCodeListener.finally(() => {
191
- loopbackClient.closeServer();
192
- });
202
+ await authCodeListener;
203
+ if (authCodeListenerError) {
204
+ throw authCodeListenerError;
205
+ }
193
206
 
194
207
  if (authCodeResponse.error) {
195
208
  throw new ServerError(
@@ -209,9 +222,8 @@ export class PublicClientApplication
209
222
  ...validRequest,
210
223
  };
211
224
  return this.acquireTokenByCode(tokenRequest);
212
- } catch (e) {
225
+ } finally {
213
226
  loopbackClient.closeServer();
214
- throw e;
215
227
  }
216
228
  }
217
229
 
@@ -280,4 +292,48 @@ export class PublicClientApplication
280
292
 
281
293
  return this.getTokenCache().getAllAccounts();
282
294
  }
295
+
296
+ /**
297
+ * Attempts to retrieve the redirectUri from the loopback server. If the loopback server does not start listening for requests within the timeout this will throw.
298
+ * @param loopbackClient
299
+ * @returns
300
+ */
301
+ private async waitForRedirectUri(
302
+ loopbackClient: ILoopbackClient
303
+ ): Promise<string> {
304
+ return new Promise<string>((resolve, reject) => {
305
+ let ticks = 0;
306
+ const id = setInterval(() => {
307
+ if (
308
+ LOOPBACK_SERVER_CONSTANTS.TIMEOUT_MS /
309
+ LOOPBACK_SERVER_CONSTANTS.INTERVAL_MS <
310
+ ticks
311
+ ) {
312
+ clearInterval(id);
313
+ reject(NodeAuthError.createLoopbackServerTimeoutError());
314
+ return;
315
+ }
316
+
317
+ try {
318
+ const r = loopbackClient.getRedirectUri();
319
+ clearInterval(id);
320
+ resolve(r);
321
+ return;
322
+ } catch (e) {
323
+ if (
324
+ e instanceof AuthError &&
325
+ e.errorCode ===
326
+ NodeAuthErrorMessage.noLoopbackServerExists.code
327
+ ) {
328
+ // Loopback server is not listening yet
329
+ ticks++;
330
+ return;
331
+ }
332
+ clearInterval(id);
333
+ reject(e);
334
+ return;
335
+ }
336
+ }, LOOPBACK_SERVER_CONSTANTS.INTERVAL_MS);
337
+ });
338
+ }
283
339
  }
package/src/index.ts CHANGED
@@ -90,11 +90,15 @@ export {
90
90
  // Error
91
91
  AuthError,
92
92
  AuthErrorMessage,
93
+ AuthErrorCodes,
93
94
  ClientAuthError,
95
+ ClientAuthErrorCodes,
94
96
  ClientAuthErrorMessage,
95
97
  ClientConfigurationError,
98
+ ClientConfigurationErrorCodes,
96
99
  ClientConfigurationErrorMessage,
97
100
  InteractionRequiredAuthError,
101
+ InteractionRequiredAuthErrorCodes,
98
102
  InteractionRequiredAuthErrorMessage,
99
103
  ServerError,
100
104
  // Network Interface
@@ -11,11 +11,11 @@ import {
11
11
  } from "@azure/msal-common";
12
12
  import http from "http";
13
13
  import { NodeAuthError } from "../error/NodeAuthError.js";
14
- import { Constants, LOOPBACK_SERVER_CONSTANTS } from "../utils/Constants.js";
14
+ import { Constants } from "../utils/Constants.js";
15
15
  import { ILoopbackClient } from "./ILoopbackClient.js";
16
16
 
17
17
  export class LoopbackClient implements ILoopbackClient {
18
- private server: http.Server;
18
+ private server: http.Server | undefined;
19
19
 
20
20
  /**
21
21
  * Spins up a loopback server which returns the server response when the localhost redirectUri is hit
@@ -27,17 +27,14 @@ export class LoopbackClient implements ILoopbackClient {
27
27
  successTemplate?: string,
28
28
  errorTemplate?: string
29
29
  ): Promise<ServerAuthorizationCodeResponse> {
30
- if (!!this.server) {
30
+ if (this.server) {
31
31
  throw NodeAuthError.createLoopbackServerAlreadyExistsError();
32
32
  }
33
33
 
34
- const authCodeListener = new Promise<ServerAuthorizationCodeResponse>(
34
+ return new Promise<ServerAuthorizationCodeResponse>(
35
35
  (resolve, reject) => {
36
36
  this.server = http.createServer(
37
- async (
38
- req: http.IncomingMessage,
39
- res: http.ServerResponse
40
- ) => {
37
+ (req: http.IncomingMessage, res: http.ServerResponse) => {
41
38
  const url = req.url;
42
39
  if (!url) {
43
40
  res.end(
@@ -59,7 +56,7 @@ export class LoopbackClient implements ILoopbackClient {
59
56
  const authCodeResponse =
60
57
  UrlString.getDeserializedQueryString(url);
61
58
  if (authCodeResponse.code) {
62
- const redirectUri = await this.getRedirectUri();
59
+ const redirectUri = this.getRedirectUri();
63
60
  res.writeHead(HttpStatus.REDIRECT, {
64
61
  location: redirectUri,
65
62
  }); // Prevent auth code from being saved in the browser history
@@ -71,28 +68,6 @@ export class LoopbackClient implements ILoopbackClient {
71
68
  this.server.listen(0); // Listen on any available port
72
69
  }
73
70
  );
74
-
75
- // Wait for server to be listening
76
- await new Promise<void>((resolve) => {
77
- let ticks = 0;
78
- const id = setInterval(() => {
79
- if (
80
- LOOPBACK_SERVER_CONSTANTS.TIMEOUT_MS /
81
- LOOPBACK_SERVER_CONSTANTS.INTERVAL_MS <
82
- ticks
83
- ) {
84
- throw NodeAuthError.createLoopbackServerTimeoutError();
85
- }
86
-
87
- if (this.server.listening) {
88
- clearInterval(id);
89
- resolve();
90
- }
91
- ticks++;
92
- }, LOOPBACK_SERVER_CONSTANTS.INTERVAL_MS);
93
- });
94
-
95
- return authCodeListener;
96
71
  }
97
72
 
98
73
  /**
@@ -100,7 +75,7 @@ export class LoopbackClient implements ILoopbackClient {
100
75
  * @returns
101
76
  */
102
77
  getRedirectUri(): string {
103
- if (!this.server) {
78
+ if (!this.server || !this.server.listening) {
104
79
  throw NodeAuthError.createNoLoopbackServerExistsError();
105
80
  }
106
81
 
@@ -119,8 +94,17 @@ export class LoopbackClient implements ILoopbackClient {
119
94
  * Close the loopback server
120
95
  */
121
96
  closeServer(): void {
122
- if (!!this.server) {
97
+ if (this.server) {
98
+ // Only stops accepting new connections, server will close once open/idle connections are closed.
123
99
  this.server.close();
100
+
101
+ if (typeof this.server.closeAllConnections === "function") {
102
+ /*
103
+ * Close open/idle connections. This API is available in Node versions 18.2 and higher
104
+ */
105
+ this.server.closeAllConnections();
106
+ }
107
+ this.server = undefined;
124
108
  }
125
109
  }
126
110
  }