@azure/msal-node 1.7.0 → 1.9.1

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
+ }
130
+
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
+ };
142
143
 
143
- /* istanbul ignore next */
144
- data: options && options.body || "",
145
- timeout: cancellationToken,
144
+ if (timeout) {
145
+ tunnelRequestOptions.timeout = timeout;
146
+ } // compose a request string for the socket
146
147
 
147
- /* istanbul ignore next */
148
- headers: options && options.headers,
149
148
 
150
- /* istanbul ignore next */
151
- validateStatus: () => true
152
- };
149
+ let postRequestStringContent = "";
153
150
 
154
- if (options && options.proxyUrl) {
155
- // for axios, this has to be disabled
156
- request.proxy = false;
157
- request.httpsAgent = createHttpsProxyAgent(options.proxyUrl);
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.
@@ -186,23 +340,23 @@ class NetworkUtils {
186
340
  * Licensed under the MIT License.
187
341
  */
188
342
  const DEFAULT_AUTH_OPTIONS = {
189
- clientId: "",
343
+ clientId: Constants$1.EMPTY_STRING,
190
344
  authority: Constants$1.DEFAULT_AUTHORITY,
191
- clientSecret: "",
192
- clientAssertion: "",
345
+ clientSecret: Constants$1.EMPTY_STRING,
346
+ clientAssertion: Constants$1.EMPTY_STRING,
193
347
  clientCertificate: {
194
- thumbprint: "",
195
- privateKey: "",
196
- x5c: ""
348
+ thumbprint: Constants$1.EMPTY_STRING,
349
+ privateKey: Constants$1.EMPTY_STRING,
350
+ x5c: Constants$1.EMPTY_STRING
197
351
  },
198
352
  knownAuthorities: [],
199
- cloudDiscoveryMetadata: "",
200
- authorityMetadata: "",
353
+ cloudDiscoveryMetadata: Constants$1.EMPTY_STRING,
354
+ authorityMetadata: Constants$1.EMPTY_STRING,
201
355
  clientCapabilities: [],
202
356
  protocolMode: ProtocolMode.AAD,
203
357
  azureCloudOptions: {
204
358
  azureCloudInstance: AzureCloudInstance.None,
205
- tenant: ""
359
+ tenant: Constants$1.EMPTY_STRING
206
360
  }
207
361
  };
208
362
  const DEFAULT_CACHE_OPTIONS = {};
@@ -215,7 +369,13 @@ const DEFAULT_LOGGER_OPTIONS = {
215
369
  const DEFAULT_SYSTEM_OPTIONS = {
216
370
  loggerOptions: DEFAULT_LOGGER_OPTIONS,
217
371
  networkClient: /*#__PURE__*/NetworkUtils.getNetworkClient(),
218
- proxyUrl: ""
372
+ proxyUrl: Constants$1.EMPTY_STRING
373
+ };
374
+ const DEFAULT_TELEMETRY_OPTIONS = {
375
+ application: {
376
+ appName: Constants$1.EMPTY_STRING,
377
+ appVersion: Constants$1.EMPTY_STRING
378
+ }
219
379
  };
220
380
  /**
221
381
  * Sets the default options when not explicitly configured from app developer
@@ -223,6 +383,7 @@ const DEFAULT_SYSTEM_OPTIONS = {
223
383
  * @param auth - Authentication options
224
384
  * @param cache - Cache options
225
385
  * @param system - System options
386
+ * @param telemetry - Telemetry options
226
387
  *
227
388
  * @returns Configuration
228
389
  * @public
@@ -231,7 +392,8 @@ const DEFAULT_SYSTEM_OPTIONS = {
231
392
  function buildAppConfiguration({
232
393
  auth,
233
394
  cache,
234
- system
395
+ system,
396
+ telemetry
235
397
  }) {
236
398
  return {
237
399
  auth: { ...DEFAULT_AUTH_OPTIONS,
@@ -242,6 +404,9 @@ function buildAppConfiguration({
242
404
  },
243
405
  system: { ...DEFAULT_SYSTEM_OPTIONS,
244
406
  ...system
407
+ },
408
+ telemetry: { ...DEFAULT_TELEMETRY_OPTIONS,
409
+ ...telemetry
245
410
  }
246
411
  };
247
412
  }
@@ -256,7 +421,7 @@ class GuidGenerator {
256
421
  * RFC4122: The version 4 UUID is meant for generating UUIDs from truly-random or pseudo-random numbers.
257
422
  * uuidv4 generates guids from cryprtographically-string random
258
423
  */
259
- static generateGuid() {
424
+ generateGuid() {
260
425
  return v4();
261
426
  }
262
427
  /**
@@ -265,7 +430,7 @@ class GuidGenerator {
265
430
  */
266
431
 
267
432
 
268
- static isGuid(guid) {
433
+ isGuid(guid) {
269
434
  const regexGuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
270
435
  return regexGuid.test(guid);
271
436
  }
@@ -293,7 +458,7 @@ class EncodingUtils {
293
458
 
294
459
 
295
460
  static base64EncodeUrl(str, encoding) {
296
- return EncodingUtils.base64Encode(str, encoding).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
461
+ return EncodingUtils.base64Encode(str, encoding).replace(/=/g, Constants$1.EMPTY_STRING).replace(/\+/g, "-").replace(/\//g, "_");
297
462
  }
298
463
  /**
299
464
  * 'utf8': Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8.
@@ -388,7 +553,7 @@ class PkceGenerator {
388
553
  charArr.push(CharSet.CV_CHARSET[index]);
389
554
  }
390
555
 
391
- const verifier = charArr.join("");
556
+ const verifier = charArr.join(Constants$1.EMPTY_STRING);
392
557
  return EncodingUtils.base64EncodeUrl(verifier);
393
558
  }
394
559
  /**
@@ -417,6 +582,7 @@ class CryptoProvider {
417
582
  constructor() {
418
583
  // Browser crypto needs to be validated first before any other classes can be set.
419
584
  this.pkceGenerator = new PkceGenerator();
585
+ this.guidGenerator = new GuidGenerator();
420
586
  this.hashUtils = new HashUtils();
421
587
  }
422
588
  /**
@@ -426,7 +592,7 @@ class CryptoProvider {
426
592
 
427
593
 
428
594
  createNewGuid() {
429
- return GuidGenerator.generateGuid();
595
+ return this.guidGenerator.generateGuid();
430
596
  }
431
597
  /**
432
598
  * Encodes input string to base64.
@@ -1586,7 +1752,7 @@ class TokenCache {
1586
1752
 
1587
1753
  /* eslint-disable header/header */
1588
1754
  const name = "@azure/msal-node";
1589
- const version = "1.7.0";
1755
+ const version = "1.9.1";
1590
1756
 
1591
1757
  /*
1592
1758
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -1825,9 +1991,10 @@ class ClientApplication {
1825
1991
  libraryInfo: {
1826
1992
  sku: Constants.MSAL_SKU,
1827
1993
  version: version,
1828
- cpu: process.arch || "",
1829
- os: process.platform || ""
1994
+ cpu: process.arch || Constants$1.EMPTY_STRING,
1995
+ os: process.platform || Constants$1.EMPTY_STRING
1830
1996
  },
1997
+ telemetry: this.config.telemetry,
1831
1998
  persistencePlugin: this.config.cache.cachePlugin,
1832
1999
  serializableCache: this.tokenCache
1833
2000
  };
@@ -1899,7 +2066,7 @@ class ClientApplication {
1899
2066
  authorityMetadata: this.config.auth.authorityMetadata,
1900
2067
  azureRegionConfiguration
1901
2068
  };
1902
- return await AuthorityFactory.createDiscoveredInstance(authorityUrl, this.config.system.networkClient, this.storage, authorityOptions);
2069
+ return await AuthorityFactory.createDiscoveredInstance(authorityUrl, this.config.system.networkClient, this.storage, authorityOptions, this.config.system.proxyUrl);
1903
2070
  }
1904
2071
  /**
1905
2072
  * Clear the cache
@@ -2099,13 +2266,13 @@ class ClientAssertion {
2099
2266
  * "." means any string character, "+" means match 1 or more times, and "?" means the shortest match.
2100
2267
  * The "g" at the end of the regex means search the string globally, and the "s" enables the "." to match newlines.
2101
2268
  */
2102
- const regexToFindCerts = /-----BEGIN CERTIFICATE-----\n(.+?)\n-----END CERTIFICATE-----/gs;
2269
+ const regexToFindCerts = /-----BEGIN CERTIFICATE-----\r*\n(.+?)\r*\n-----END CERTIFICATE-----/gs;
2103
2270
  const certs = [];
2104
2271
  let matches;
2105
2272
 
2106
2273
  while ((matches = regexToFindCerts.exec(publicCertificate)) !== null) {
2107
2274
  // matches[1] represents the first parens capture group in the regex.
2108
- certs.push(matches[1].replace(/\n/, ""));
2275
+ certs.push(matches[1].replace(/\r*\n/g, Constants$1.EMPTY_STRING));
2109
2276
  }
2110
2277
 
2111
2278
  return certs;
@@ -2214,8 +2381,8 @@ class ConfidentialClientApplication extends ClientApplication {
2214
2381
  const clientSecretNotEmpty = !StringUtils.isEmpty(configuration.auth.clientSecret);
2215
2382
  const clientAssertionNotEmpty = !StringUtils.isEmpty(configuration.auth.clientAssertion);
2216
2383
  const certificate = configuration.auth.clientCertificate || {
2217
- thumbprint: "",
2218
- privateKey: ""
2384
+ thumbprint: Constants$1.EMPTY_STRING,
2385
+ privateKey: Constants$1.EMPTY_STRING
2219
2386
  };
2220
2387
  const certificateNotEmpty = !StringUtils.isEmpty(certificate.thumbprint) || !StringUtils.isEmpty(certificate.privateKey); // Check that at most one credential is set on the application
2221
2388