@azure/msal-node 1.9.0 → 1.11.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.
@@ -1,7 +1,7 @@
1
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';
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 axios from 'axios';
4
- import createHttpsProxyAgent from 'https-proxy-agent';
3
+ import http from 'http';
4
+ import https from 'https';
5
5
  import { v4 } from 'uuid';
6
6
  import crypto from 'crypto';
7
7
  import { sign } from 'jsonwebtoken';
@@ -51,7 +51,8 @@ const CharSet = {
51
51
 
52
52
  const Constants = {
53
53
  MSAL_SKU: "msal.js.node",
54
- JWT_BEARER_ASSERTION_TYPE: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
54
+ JWT_BEARER_ASSERTION_TYPE: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
55
+ AUTHORIZATION_PENDING: "authorization_pending"
55
56
  };
56
57
  /**
57
58
  * API Codes for Telemetry purposes.
@@ -104,29 +105,11 @@ class HttpClient {
104
105
  * @param options
105
106
  */
106
107
  async sendGetRequestAsync(url, options) {
107
- const request = {
108
- method: HttpMethod.GET,
109
- url: url,
110
-
111
- /* istanbul ignore next */
112
- headers: options && options.headers,
113
-
114
- /* istanbul ignore next */
115
- validateStatus: () => true
116
- };
117
-
118
- if (options && options.proxyUrl) {
119
- // for axios, this has to be disabled
120
- request.proxy = false;
121
- request.httpsAgent = createHttpsProxyAgent(options.proxyUrl);
108
+ if (options != null && options.proxyUrl) {
109
+ return networkRequestViaProxy(url, HttpMethod.GET, options);
110
+ } else {
111
+ return networkRequestViaHttps(url, HttpMethod.GET, options);
122
112
  }
123
-
124
- const response = await axios(request);
125
- return {
126
- headers: response.headers,
127
- body: response.data,
128
- status: response.status
129
- };
130
113
  }
131
114
  /**
132
115
  * Http Post request
@@ -136,36 +119,207 @@ class HttpClient {
136
119
 
137
120
 
138
121
  async sendPostRequestAsync(url, options, cancellationToken) {
139
- const request = {
140
- method: HttpMethod.POST,
141
- url: url,
122
+ if (options != null && options.proxyUrl) {
123
+ return networkRequestViaProxy(url, HttpMethod.POST, options, cancellationToken);
124
+ } else {
125
+ return networkRequestViaHttps(url, HttpMethod.POST, options, cancellationToken);
126
+ }
127
+ }
128
+
129
+ }
142
130
 
143
- /* istanbul ignore next */
144
- data: options && options.body || Constants$1.EMPTY_STRING,
145
- timeout: cancellationToken,
131
+ const networkRequestViaProxy = (url, httpMethod, options, timeout) => {
132
+ const headers = (options == null ? void 0 : options.headers) || {};
133
+ const proxyUrl = new URL((options == null ? void 0 : options.proxyUrl) || "");
134
+ const destinationUrl = new URL(url); // "method: connect" must be used to establish a connection to the proxy
135
+
136
+ const tunnelRequestOptions = {
137
+ host: proxyUrl.hostname,
138
+ port: proxyUrl.port,
139
+ method: "CONNECT",
140
+ path: destinationUrl.hostname,
141
+ headers: headers
142
+ };
146
143
 
147
- /* istanbul ignore next */
148
- headers: options && options.headers,
144
+ if (timeout) {
145
+ tunnelRequestOptions.timeout = timeout;
146
+ } // compose a request string for the socket
149
147
 
150
- /* istanbul ignore next */
151
- validateStatus: () => true
152
- };
153
148
 
154
- if (options && options.proxyUrl) {
155
- // for axios, this has to be disabled
156
- request.proxy = false;
157
- request.httpsAgent = createHttpsProxyAgent(options.proxyUrl);
149
+ let postRequestStringContent = "";
150
+
151
+ if (httpMethod === HttpMethod.POST) {
152
+ const body = (options == null ? void 0 : options.body) || "";
153
+ postRequestStringContent = "Content-Type: application/x-www-form-urlencoded\r\n" + `Content-Length: ${body.length}\r\n` + `\r\n${body}`;
154
+ }
155
+
156
+ const outgoingRequestString = `${httpMethod.toUpperCase()} ${destinationUrl.href} HTTP/1.1\r\n` + `Host: ${destinationUrl.host}\r\n` + "Connection: close\r\n" + postRequestStringContent + "\r\n";
157
+ return new Promise((resolve, reject) => {
158
+ const request = http.request(tunnelRequestOptions);
159
+
160
+ if (tunnelRequestOptions.timeout) {
161
+ request.on("timeout", () => {
162
+ request.destroy();
163
+ reject(new Error("Request time out"));
164
+ });
158
165
  }
159
166
 
160
- const response = await axios(request);
161
- return {
162
- headers: response.headers,
163
- body: response.data,
164
- status: response.status
167
+ request.end(); // establish connection to the proxy
168
+
169
+ request.on("connect", (response, socket) => {
170
+ const statusCode = (response == null ? void 0 : response.statusCode) || 500;
171
+
172
+ if (statusCode < 200 || statusCode > 299) {
173
+ request.destroy();
174
+ socket.destroy();
175
+ reject(new Error(`HTTP status code ${statusCode}`));
176
+ }
177
+
178
+ if (tunnelRequestOptions.timeout) {
179
+ socket.setTimeout(tunnelRequestOptions.timeout);
180
+ socket.on("timeout", () => {
181
+ request.destroy();
182
+ socket.destroy();
183
+ reject(new Error("Request time out"));
184
+ });
185
+ } // make a request over an HTTP tunnel
186
+
187
+
188
+ socket.write(outgoingRequestString);
189
+ const data = [];
190
+ socket.on("data", chunk => {
191
+ data.push(chunk);
192
+ });
193
+ socket.on("end", () => {
194
+ // combine all received buffer streams into one buffer, and then into a string
195
+ const dataString = Buffer.concat([...data]).toString(); // separate each line into it's own entry in an arry
196
+
197
+ const dataStringArray = dataString.split("\r\n"); // the first entry will contain the statusCode
198
+
199
+ const statusCode = parseInt(dataStringArray[0].split(" ")[1]); // the last entry will contain the body
200
+
201
+ const body = dataStringArray[dataStringArray.length - 1]; // everything in between the first and last entries are the headers
202
+
203
+ const headersArray = dataStringArray.slice(1, dataStringArray.length - 2); // build an object out of all the headers
204
+
205
+ const entries = new Map();
206
+ headersArray.forEach(header => {
207
+ /**
208
+ * the header might look like "Content-Length: 1531", but that is just a string
209
+ * it needs to be converted to a key/value pair
210
+ * split the string at the first instance of ":"
211
+ * there may be more than one ":" if the value of the header is supposed to be a JSON object
212
+ */
213
+ const headerKeyValue = header.split(new RegExp(/:\s(.*)/s));
214
+ const headerKey = headerKeyValue[0];
215
+ let headerValue = headerKeyValue[1]; // check if the value of the header is supposed to be a JSON object
216
+
217
+ try {
218
+ const object = JSON.parse(headerValue); // if it is, then convert it from a string to a JSON object
219
+
220
+ if (object && typeof object === "object") {
221
+ headerValue = object;
222
+ }
223
+ } catch (e) {// otherwise, leave it as a string
224
+ }
225
+
226
+ entries.set(headerKey, headerValue);
227
+ });
228
+ const headers = Object.fromEntries(entries);
229
+ const networkResponse = {
230
+ headers: headers,
231
+ body: JSON.parse(body),
232
+ status: statusCode
233
+ };
234
+
235
+ if ((statusCode < 200 || statusCode > 299) && // do not destroy the request for the device code flow
236
+ networkResponse.body["error"] !== Constants.AUTHORIZATION_PENDING) {
237
+ request.destroy();
238
+ socket.destroy();
239
+ reject(new Error(`HTTP status code ${statusCode}`));
240
+ }
241
+
242
+ resolve(networkResponse);
243
+ });
244
+ socket.on("error", chunk => {
245
+ request.destroy();
246
+ socket.destroy();
247
+ reject(new Error(chunk.toString()));
248
+ });
249
+ });
250
+ request.on("error", chunk => {
251
+ request.destroy();
252
+ reject(new Error(chunk.toString()));
253
+ });
254
+ });
255
+ };
256
+
257
+ const networkRequestViaHttps = (url, httpMethod, options, timeout) => {
258
+ const isPostRequest = httpMethod === HttpMethod.POST;
259
+ const body = (options == null ? void 0 : options.body) || "";
260
+ const emptyHeaders = {};
261
+ const customOptions = {
262
+ method: httpMethod,
263
+ headers: (options == null ? void 0 : options.headers) || emptyHeaders
264
+ };
265
+
266
+ if (timeout) {
267
+ customOptions.timeout = timeout;
268
+ }
269
+
270
+ if (isPostRequest) {
271
+ // needed for post request to work
272
+ customOptions.headers = { ...customOptions.headers,
273
+ "Content-Length": body.length
165
274
  };
166
275
  }
167
276
 
168
- }
277
+ return new Promise((resolve, reject) => {
278
+ const request = https.request(url, customOptions);
279
+
280
+ if (timeout) {
281
+ request.on("timeout", () => {
282
+ request.destroy();
283
+ reject(new Error("Request time out"));
284
+ });
285
+ }
286
+
287
+ if (isPostRequest) {
288
+ request.write(body);
289
+ }
290
+
291
+ request.end();
292
+ request.on("response", response => {
293
+ const headers = response.headers;
294
+ const statusCode = response.statusCode;
295
+ const data = [];
296
+ response.on("data", chunk => {
297
+ data.push(chunk);
298
+ });
299
+ response.on("end", () => {
300
+ // combine all received buffer streams into one buffer, and then into a string
301
+ const body = Buffer.concat([...data]).toString();
302
+ const networkResponse = {
303
+ headers: headers,
304
+ body: JSON.parse(body),
305
+ status: statusCode
306
+ };
307
+
308
+ if ((statusCode < 200 || statusCode > 299) && // do not destroy the request for the device code flow
309
+ networkResponse.body["error"] !== Constants.AUTHORIZATION_PENDING) {
310
+ request.destroy();
311
+ reject(new Error(`HTTP status code ${statusCode}`));
312
+ }
313
+
314
+ resolve(networkResponse);
315
+ });
316
+ });
317
+ request.on("error", chunk => {
318
+ request.destroy();
319
+ reject(new Error(chunk.toString()));
320
+ });
321
+ });
322
+ };
169
323
 
170
324
  /*
171
325
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -203,7 +357,8 @@ const DEFAULT_AUTH_OPTIONS = {
203
357
  azureCloudOptions: {
204
358
  azureCloudInstance: AzureCloudInstance.None,
205
359
  tenant: Constants$1.EMPTY_STRING
206
- }
360
+ },
361
+ skipAuthorityMetadataCache: false
207
362
  };
208
363
  const DEFAULT_CACHE_OPTIONS = {};
209
364
  const DEFAULT_LOGGER_OPTIONS = {
@@ -1598,7 +1753,7 @@ class TokenCache {
1598
1753
 
1599
1754
  /* eslint-disable header/header */
1600
1755
  const name = "@azure/msal-node";
1601
- const version = "1.9.0";
1756
+ const version = "1.11.0";
1602
1757
 
1603
1758
  /*
1604
1759
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -1910,9 +2065,10 @@ class ClientApplication {
1910
2065
  knownAuthorities: this.config.auth.knownAuthorities,
1911
2066
  cloudDiscoveryMetadata: this.config.auth.cloudDiscoveryMetadata,
1912
2067
  authorityMetadata: this.config.auth.authorityMetadata,
1913
- azureRegionConfiguration
2068
+ azureRegionConfiguration,
2069
+ skipAuthorityMetadataCache: this.config.auth.skipAuthorityMetadataCache
1914
2070
  };
1915
- return await AuthorityFactory.createDiscoveredInstance(authorityUrl, this.config.system.networkClient, this.storage, authorityOptions);
2071
+ return await AuthorityFactory.createDiscoveredInstance(authorityUrl, this.config.system.networkClient, this.storage, authorityOptions, this.config.system.proxyUrl);
1916
2072
  }
1917
2073
  /**
1918
2074
  * Clear the cache
@@ -2112,13 +2268,13 @@ class ClientAssertion {
2112
2268
  * "." means any string character, "+" means match 1 or more times, and "?" means the shortest match.
2113
2269
  * The "g" at the end of the regex means search the string globally, and the "s" enables the "." to match newlines.
2114
2270
  */
2115
- const regexToFindCerts = /-----BEGIN CERTIFICATE-----\n(.+?)\n-----END CERTIFICATE-----/gs;
2271
+ const regexToFindCerts = /-----BEGIN CERTIFICATE-----\r*\n(.+?)\r*\n-----END CERTIFICATE-----/gs;
2116
2272
  const certs = [];
2117
2273
  let matches;
2118
2274
 
2119
2275
  while ((matches = regexToFindCerts.exec(publicCertificate)) !== null) {
2120
2276
  // matches[1] represents the first parens capture group in the regex.
2121
- certs.push(matches[1].replace(/\n/, Constants$1.EMPTY_STRING));
2277
+ certs.push(matches[1].replace(/\r*\n/g, Constants$1.EMPTY_STRING));
2122
2278
  }
2123
2279
 
2124
2280
  return certs;
@@ -2166,9 +2322,20 @@ class ConfidentialClientApplication extends ClientApplication {
2166
2322
 
2167
2323
 
2168
2324
  async acquireTokenByClientCredential(request) {
2169
- this.logger.info("acquireTokenByClientCredential called", request.correlationId);
2325
+ this.logger.info("acquireTokenByClientCredential called", request.correlationId); // If there is a client assertion present in the request, it overrides the one present in the client configuration
2326
+
2327
+ let clientAssertion;
2328
+
2329
+ if (request.clientAssertion) {
2330
+ clientAssertion = {
2331
+ assertion: request.clientAssertion,
2332
+ assertionType: Constants.JWT_BEARER_ASSERTION_TYPE
2333
+ };
2334
+ }
2335
+
2170
2336
  const validRequest = { ...request,
2171
- ...(await this.initializeBaseRequest(request))
2337
+ ...(await this.initializeBaseRequest(request)),
2338
+ clientAssertion
2172
2339
  };
2173
2340
  const azureRegionConfiguration = {
2174
2341
  azureRegion: validRequest.azureRegion,
@@ -2210,8 +2377,8 @@ class ConfidentialClientApplication extends ClientApplication {
2210
2377
  };
2211
2378
 
2212
2379
  try {
2213
- const clientCredentialConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, undefined, undefined, request.azureCloudOptions);
2214
- const oboClient = new OnBehalfOfClient(clientCredentialConfig);
2380
+ const onBehalfOfConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, undefined, undefined, request.azureCloudOptions);
2381
+ const oboClient = new OnBehalfOfClient(onBehalfOfConfig);
2215
2382
  this.logger.verbose("On behalf of client created", validRequest.correlationId);
2216
2383
  return oboClient.acquireToken(validRequest);
2217
2384
  } catch (e) {