@azure/msal-node 1.11.0 → 1.13.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 (31) hide show
  1. package/README.md +1 -3
  2. package/dist/client/ClientApplication.d.ts +3 -2
  3. package/dist/client/ClientApplication.d.ts.map +1 -1
  4. package/dist/client/ConfidentialClientApplication.d.ts +9 -1
  5. package/dist/client/ConfidentialClientApplication.d.ts.map +1 -1
  6. package/dist/client/IConfidentialClientApplication.d.ts +4 -2
  7. package/dist/client/IConfidentialClientApplication.d.ts.map +1 -1
  8. package/dist/client/IPublicClientApplication.d.ts +4 -1
  9. package/dist/client/IPublicClientApplication.d.ts.map +1 -1
  10. package/dist/client/PublicClientApplication.d.ts +5 -0
  11. package/dist/client/PublicClientApplication.d.ts.map +1 -1
  12. package/dist/error/NodeAuthError.d.ts +58 -0
  13. package/dist/error/NodeAuthError.d.ts.map +1 -0
  14. package/dist/index.d.ts +2 -1
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/msal-node.cjs.development.js +277 -7
  17. package/dist/msal-node.cjs.development.js.map +1 -1
  18. package/dist/msal-node.cjs.production.min.js +1 -1
  19. package/dist/msal-node.cjs.production.min.js.map +1 -1
  20. package/dist/msal-node.esm.js +276 -7
  21. package/dist/msal-node.esm.js.map +1 -1
  22. package/dist/network/LoopbackClient.d.ts +21 -0
  23. package/dist/network/LoopbackClient.d.ts.map +1 -0
  24. package/dist/packageMetadata.d.ts +1 -1
  25. package/dist/request/InteractiveRequest.d.ts +8 -0
  26. package/dist/request/InteractiveRequest.d.ts.map +1 -0
  27. package/dist/request/RefreshTokenRequest.d.ts +3 -1
  28. package/dist/request/RefreshTokenRequest.d.ts.map +1 -1
  29. package/dist/utils/Constants.d.ts +10 -0
  30. package/dist/utils/Constants.d.ts.map +1 -1
  31. package/package.json +2 -2
@@ -1,6 +1,6 @@
1
- import { Constants as Constants$1, ProtocolMode, AzureCloudInstance, LogLevel, StringUtils, AccountEntity, CacheManager, IdTokenEntity, AccessTokenEntity, RefreshTokenEntity, AppMetadataEntity, ServerTelemetryEntity, AuthorityMetadataEntity, ThrottlingEntity, TokenCacheContext, Logger, ResponseMode, AuthenticationScheme, AuthorizationCodeClient, AuthError, RefreshTokenClient, SilentFlowClient, UsernamePasswordClient, OIDC_DEFAULT_SCOPES, ServerTelemetryManager, Authority, AuthorityFactory, DeviceCodeClient, ClientAuthError, TimeUtils, ClientCredentialClient, OnBehalfOfClient } from '@azure/msal-common';
1
+ import { Constants as Constants$1, ProtocolMode, AzureCloudInstance, LogLevel, StringUtils, AccountEntity, CacheManager, IdTokenEntity, AccessTokenEntity, RefreshTokenEntity, AppMetadataEntity, ServerTelemetryEntity, AuthorityMetadataEntity, ThrottlingEntity, TokenCacheContext, Logger, ResponseMode, AuthenticationScheme, AuthorizationCodeClient, AuthError, RefreshTokenClient, SilentFlowClient, UsernamePasswordClient, OIDC_DEFAULT_SCOPES, ServerTelemetryManager, Authority, AuthorityFactory, UrlString, DeviceCodeClient, ServerError, CodeChallengeMethodValues, ClientAuthError, TimeUtils, ClientCredentialClient, OnBehalfOfClient } from '@azure/msal-common';
2
2
  export { AuthError, AuthErrorMessage, AzureCloudInstance, ClientAuthError, ClientAuthErrorMessage, ClientConfigurationError, ClientConfigurationErrorMessage, InteractionRequiredAuthError, InteractionRequiredAuthErrorMessage, LogLevel, Logger, PromptValue, ProtocolMode, ResponseMode, ServerError, TokenCacheContext } from '@azure/msal-common';
3
- import http from 'http';
3
+ import http, { createServer } from 'http';
4
4
  import https from 'https';
5
5
  import { v4 } from 'uuid';
6
6
  import crypto from 'crypto';
@@ -20,6 +20,13 @@ var HttpMethod;
20
20
  HttpMethod["GET"] = "get";
21
21
  HttpMethod["POST"] = "post";
22
22
  })(HttpMethod || (HttpMethod = {}));
23
+
24
+ var HttpStatus;
25
+
26
+ (function (HttpStatus) {
27
+ HttpStatus[HttpStatus["OK"] = 200] = "OK";
28
+ HttpStatus[HttpStatus["REDIRECT"] = 302] = "REDIRECT";
29
+ })(HttpStatus || (HttpStatus = {}));
23
30
  /**
24
31
  * Constants used for region discovery
25
32
  */
@@ -52,7 +59,9 @@ const CharSet = {
52
59
  const Constants = {
53
60
  MSAL_SKU: "msal.js.node",
54
61
  JWT_BEARER_ASSERTION_TYPE: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
55
- AUTHORIZATION_PENDING: "authorization_pending"
62
+ AUTHORIZATION_PENDING: "authorization_pending",
63
+ HTTP_PROTOCOL: "http://",
64
+ LOCALHOST: "localhost"
56
65
  };
57
66
  /**
58
67
  * API Codes for Telemetry purposes.
@@ -89,6 +98,10 @@ const JwtConstants = {
89
98
  NOT_BEFORE: "nbf",
90
99
  JWT_ID: "jti"
91
100
  };
101
+ const LOOPBACK_SERVER_CONSTANTS = {
102
+ INTERVAL_MS: 100,
103
+ TIMEOUT_MS: 5000
104
+ };
92
105
 
93
106
  /*
94
107
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -1753,7 +1766,7 @@ class TokenCache {
1753
1766
 
1754
1767
  /* eslint-disable header/header */
1755
1768
  const name = "@azure/msal-node";
1756
- const version = "1.11.0";
1769
+ const version = "1.13.0";
1757
1770
 
1758
1771
  /*
1759
1772
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -1966,7 +1979,7 @@ class ClientApplication {
1966
1979
  this.logger.verbose(`building oauth client configuration with the authority: ${authority}`, requestCorrelationId);
1967
1980
  const discoveredAuthority = await this.createAuthority(authority, azureRegionConfiguration, requestCorrelationId, userAzureCloudOptions);
1968
1981
  serverTelemetryManager == null ? void 0 : serverTelemetryManager.updateRegionDiscoveryMetadata(discoveredAuthority.regionDiscoveryMetadata);
1969
- return {
1982
+ const clientConfiguration = {
1970
1983
  authOptions: {
1971
1984
  clientId: this.config.auth.clientId,
1972
1985
  authority: discoveredAuthority,
@@ -1999,6 +2012,7 @@ class ClientApplication {
1999
2012
  persistencePlugin: this.config.cache.cachePlugin,
2000
2013
  serializableCache: this.tokenCache
2001
2014
  };
2015
+ return clientConfiguration;
2002
2016
  }
2003
2017
 
2004
2018
  getClientAssertion(authority) {
@@ -2081,6 +2095,192 @@ class ClientApplication {
2081
2095
 
2082
2096
  }
2083
2097
 
2098
+ /*
2099
+ * Copyright (c) Microsoft Corporation. All rights reserved.
2100
+ * Licensed under the MIT License.
2101
+ */
2102
+ /**
2103
+ * NodeAuthErrorMessage class containing string constants used by error codes and messages.
2104
+ */
2105
+
2106
+ const NodeAuthErrorMessage = {
2107
+ invalidLoopbackAddressType: {
2108
+ code: "invalid_loopback_server_address_type",
2109
+ desc: "Loopback server address is not type string. This is unexpected."
2110
+ },
2111
+ unableToLoadRedirectUri: {
2112
+ code: "unable_to_load_redirectUrl",
2113
+ desc: "Loopback server callback was invoked without a url. This is unexpected."
2114
+ },
2115
+ noAuthCodeInResponse: {
2116
+ code: "no_auth_code_in_response",
2117
+ desc: "No auth code found in the server response. Please check your network trace to determine what happened."
2118
+ },
2119
+ noLoopbackServerExists: {
2120
+ code: "no_loopback_server_exists",
2121
+ desc: "No loopback server exists yet."
2122
+ },
2123
+ loopbackServerAlreadyExists: {
2124
+ code: "loopback_server_already_exists",
2125
+ desc: "Loopback server already exists. Cannot create another."
2126
+ },
2127
+ loopbackServerTimeout: {
2128
+ code: "loopback_server_timeout",
2129
+ desc: "Timed out waiting for auth code listener to be registered."
2130
+ }
2131
+ };
2132
+ class NodeAuthError extends AuthError {
2133
+ constructor(errorCode, errorMessage) {
2134
+ super(errorCode, errorMessage);
2135
+ this.name = "NodeAuthError";
2136
+ }
2137
+ /**
2138
+ * Creates an error thrown if loopback server address is of type string.
2139
+ */
2140
+
2141
+
2142
+ static createInvalidLoopbackAddressTypeError() {
2143
+ return new NodeAuthError(NodeAuthErrorMessage.invalidLoopbackAddressType.code, `${NodeAuthErrorMessage.invalidLoopbackAddressType.desc}`);
2144
+ }
2145
+ /**
2146
+ * Creates an error thrown if the loopback server is unable to get a url.
2147
+ */
2148
+
2149
+
2150
+ static createUnableToLoadRedirectUrlError() {
2151
+ return new NodeAuthError(NodeAuthErrorMessage.unableToLoadRedirectUri.code, `${NodeAuthErrorMessage.unableToLoadRedirectUri.desc}`);
2152
+ }
2153
+ /**
2154
+ * Creates an error thrown if the server response does not contain an auth code.
2155
+ */
2156
+
2157
+
2158
+ static createNoAuthCodeInResponseError() {
2159
+ return new NodeAuthError(NodeAuthErrorMessage.noAuthCodeInResponse.code, `${NodeAuthErrorMessage.noAuthCodeInResponse.desc}`);
2160
+ }
2161
+ /**
2162
+ * Creates an error thrown if the loopback server has not been spun up yet.
2163
+ */
2164
+
2165
+
2166
+ static createNoLoopbackServerExistsError() {
2167
+ return new NodeAuthError(NodeAuthErrorMessage.noLoopbackServerExists.code, `${NodeAuthErrorMessage.noLoopbackServerExists.desc}`);
2168
+ }
2169
+ /**
2170
+ * Creates an error thrown if a loopback server already exists when attempting to create another one.
2171
+ */
2172
+
2173
+
2174
+ static createLoopbackServerAlreadyExistsError() {
2175
+ return new NodeAuthError(NodeAuthErrorMessage.loopbackServerAlreadyExists.code, `${NodeAuthErrorMessage.loopbackServerAlreadyExists.desc}`);
2176
+ }
2177
+ /**
2178
+ * Creates an error thrown if the loopback server times out registering the auth code listener.
2179
+ */
2180
+
2181
+
2182
+ static createLoopbackServerTimeoutError() {
2183
+ return new NodeAuthError(NodeAuthErrorMessage.loopbackServerTimeout.code, `${NodeAuthErrorMessage.loopbackServerTimeout.desc}`);
2184
+ }
2185
+
2186
+ }
2187
+
2188
+ /*
2189
+ * Copyright (c) Microsoft Corporation. All rights reserved.
2190
+ * Licensed under the MIT License.
2191
+ */
2192
+ class LoopbackClient {
2193
+ /**
2194
+ * Spins up a loopback server which returns the server response when the localhost redirectUri is hit
2195
+ * @param successTemplate
2196
+ * @param errorTemplate
2197
+ * @returns
2198
+ */
2199
+ async listenForAuthCode(successTemplate, errorTemplate) {
2200
+ if (!!this.server) {
2201
+ throw NodeAuthError.createLoopbackServerAlreadyExistsError();
2202
+ }
2203
+
2204
+ const authCodeListener = new Promise((resolve, reject) => {
2205
+ this.server = createServer(async (req, res) => {
2206
+ const url = req.url;
2207
+
2208
+ if (!url) {
2209
+ res.end(errorTemplate || "Error occurred loading redirectUrl");
2210
+ reject(NodeAuthError.createUnableToLoadRedirectUrlError());
2211
+ return;
2212
+ } else if (url === Constants$1.FORWARD_SLASH) {
2213
+ res.end(successTemplate || "Auth code was successfully acquired. You can close this window now.");
2214
+ return;
2215
+ }
2216
+
2217
+ const authCodeResponse = UrlString.getDeserializedQueryString(url);
2218
+
2219
+ if (authCodeResponse.code) {
2220
+ const redirectUri = await this.getRedirectUri();
2221
+ res.writeHead(HttpStatus.REDIRECT, {
2222
+ location: redirectUri
2223
+ }); // Prevent auth code from being saved in the browser history
2224
+
2225
+ res.end();
2226
+ }
2227
+
2228
+ resolve(authCodeResponse);
2229
+ });
2230
+ this.server.listen(0); // Listen on any available port
2231
+ }); // Wait for server to be listening
2232
+
2233
+ await new Promise(resolve => {
2234
+ let ticks = 0;
2235
+ const id = setInterval(() => {
2236
+ if (LOOPBACK_SERVER_CONSTANTS.TIMEOUT_MS / LOOPBACK_SERVER_CONSTANTS.INTERVAL_MS < ticks) {
2237
+ throw NodeAuthError.createLoopbackServerTimeoutError();
2238
+ }
2239
+
2240
+ if (this.server.listening) {
2241
+ clearInterval(id);
2242
+ resolve();
2243
+ }
2244
+
2245
+ ticks++;
2246
+ }, LOOPBACK_SERVER_CONSTANTS.INTERVAL_MS);
2247
+ });
2248
+ return authCodeListener;
2249
+ }
2250
+ /**
2251
+ * Get the port that the loopback server is running on
2252
+ * @returns
2253
+ */
2254
+
2255
+
2256
+ getRedirectUri() {
2257
+ if (!this.server) {
2258
+ throw NodeAuthError.createNoLoopbackServerExistsError();
2259
+ }
2260
+
2261
+ const address = this.server.address();
2262
+
2263
+ if (!address || typeof address === "string" || !address.port) {
2264
+ this.closeServer();
2265
+ throw NodeAuthError.createInvalidLoopbackAddressTypeError();
2266
+ }
2267
+
2268
+ const port = address && address.port;
2269
+ return `${Constants.HTTP_PROTOCOL}${Constants.LOCALHOST}:${port}`;
2270
+ }
2271
+ /**
2272
+ * Close the loopback server
2273
+ */
2274
+
2275
+
2276
+ closeServer() {
2277
+ if (!!this.server) {
2278
+ this.server.close();
2279
+ }
2280
+ }
2281
+
2282
+ }
2283
+
2084
2284
  /*
2085
2285
  * Copyright (c) Microsoft Corporation. All rights reserved.
2086
2286
  * Licensed under the MIT License.
@@ -2142,6 +2342,54 @@ class PublicClientApplication extends ClientApplication {
2142
2342
  throw e;
2143
2343
  }
2144
2344
  }
2345
+ /**
2346
+ * Acquires a token by requesting an Authorization code then exchanging it for a token.
2347
+ */
2348
+
2349
+
2350
+ async acquireTokenInteractive(request) {
2351
+ const {
2352
+ verifier,
2353
+ challenge
2354
+ } = await this.cryptoProvider.generatePkceCodes();
2355
+ const {
2356
+ openBrowser,
2357
+ successTemplate,
2358
+ errorTemplate,
2359
+ ...remainingProperties
2360
+ } = request;
2361
+ const loopbackClient = new LoopbackClient();
2362
+ const authCodeListener = loopbackClient.listenForAuthCode(successTemplate, errorTemplate);
2363
+ const redirectUri = loopbackClient.getRedirectUri();
2364
+ const validRequest = { ...remainingProperties,
2365
+ scopes: request.scopes || [],
2366
+ redirectUri: redirectUri,
2367
+ responseMode: ResponseMode.QUERY,
2368
+ codeChallenge: challenge,
2369
+ codeChallengeMethod: CodeChallengeMethodValues.S256
2370
+ };
2371
+ const authCodeUrl = await this.getAuthCodeUrl(validRequest);
2372
+ await openBrowser(authCodeUrl);
2373
+ const authCodeResponse = await authCodeListener.finally(() => {
2374
+ loopbackClient.closeServer();
2375
+ });
2376
+
2377
+ if (authCodeResponse.error) {
2378
+ throw new ServerError(authCodeResponse.error, authCodeResponse.error_description, authCodeResponse.suberror);
2379
+ } else if (!authCodeResponse.code) {
2380
+ throw NodeAuthError.createNoAuthCodeInResponseError();
2381
+ }
2382
+
2383
+ const clientInfo = authCodeResponse.client_info;
2384
+ const tokenRequest = {
2385
+ code: authCodeResponse.code,
2386
+ scopes: OIDC_DEFAULT_SCOPES,
2387
+ redirectUri: validRequest.redirectUri,
2388
+ codeVerifier: verifier,
2389
+ clientInfo: clientInfo || Constants$1.EMPTY_STRING
2390
+ };
2391
+ return this.acquireTokenByCode(tokenRequest);
2392
+ }
2145
2393
 
2146
2394
  }
2147
2395
 
@@ -2315,6 +2563,18 @@ class ConfidentialClientApplication extends ClientApplication {
2315
2563
  constructor(configuration) {
2316
2564
  super(configuration);
2317
2565
  this.setClientCredential(this.config);
2566
+ this.appTokenProvider = undefined;
2567
+ }
2568
+ /**
2569
+ * This extensibility point only works for the client_credential flow, i.e. acquireTokenByClientCredential and
2570
+ * is meant for Azure SDK to enhance Managed Identity support.
2571
+ *
2572
+ * @param IAppTokenProvider - Extensibility interface, which allows the app developer to return a token from a custom source.
2573
+ */
2574
+
2575
+
2576
+ SetAppTokenProvider(provider) {
2577
+ this.appTokenProvider = provider;
2318
2578
  }
2319
2579
  /**
2320
2580
  * Acquires tokens from the authority for the application (not for an end user).
@@ -2345,7 +2605,7 @@ class ConfidentialClientApplication extends ClientApplication {
2345
2605
 
2346
2606
  try {
2347
2607
  const clientCredentialConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, serverTelemetryManager, azureRegionConfiguration, request.azureCloudOptions);
2348
- const clientCredentialClient = new ClientCredentialClient(clientCredentialConfig);
2608
+ const clientCredentialClient = new ClientCredentialClient(clientCredentialConfig, this.appTokenProvider);
2349
2609
  this.logger.verbose("Client credential client created", validRequest.correlationId);
2350
2610
  return clientCredentialClient.acquireToken(validRequest);
2351
2611
  } catch (e) {
@@ -2397,7 +2657,16 @@ class ConfidentialClientApplication extends ClientApplication {
2397
2657
  thumbprint: Constants$1.EMPTY_STRING,
2398
2658
  privateKey: Constants$1.EMPTY_STRING
2399
2659
  };
2400
- const certificateNotEmpty = !StringUtils.isEmpty(certificate.thumbprint) || !StringUtils.isEmpty(certificate.privateKey); // Check that at most one credential is set on the application
2660
+ const certificateNotEmpty = !StringUtils.isEmpty(certificate.thumbprint) || !StringUtils.isEmpty(certificate.privateKey);
2661
+ /*
2662
+ * If app developer configures this callback, they don't need a credential
2663
+ * i.e. AzureSDK can get token from Managed Identity without a cert / secret
2664
+ */
2665
+
2666
+ if (this.appTokenProvider) {
2667
+ return;
2668
+ } // Check that at most one credential is set on the application
2669
+
2401
2670
 
2402
2671
  if (clientSecretNotEmpty && clientAssertionNotEmpty || clientAssertionNotEmpty && certificateNotEmpty || clientSecretNotEmpty && certificateNotEmpty) {
2403
2672
  throw ClientAuthError.createInvalidCredentialError();