@azure/msal-node 1.14.5 → 1.15.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.
@@ -16,19 +16,15 @@ var jsonwebtoken = require('jsonwebtoken');
16
16
  * Copyright (c) Microsoft Corporation. All rights reserved.
17
17
  * Licensed under the MIT License.
18
18
  */
19
-
20
19
  /**
21
20
  * http methods
22
21
  */
23
22
  var HttpMethod;
24
-
25
23
  (function (HttpMethod) {
26
24
  HttpMethod["GET"] = "get";
27
25
  HttpMethod["POST"] = "post";
28
26
  })(HttpMethod || (HttpMethod = {}));
29
-
30
27
  var HttpStatus;
31
-
32
28
  (function (HttpStatus) {
33
29
  HttpStatus[HttpStatus["SUCCESS_RANGE_START"] = 200] = "SUCCESS_RANGE_START";
34
30
  HttpStatus[HttpStatus["SUCCESS_RANGE_END"] = 299] = "SUCCESS_RANGE_END";
@@ -38,9 +34,7 @@ var HttpStatus;
38
34
  HttpStatus[HttpStatus["SERVER_ERROR_RANGE_START"] = 500] = "SERVER_ERROR_RANGE_START";
39
35
  HttpStatus[HttpStatus["SERVER_ERROR_RANGE_END"] = 599] = "SERVER_ERROR_RANGE_END";
40
36
  })(HttpStatus || (HttpStatus = {}));
41
-
42
37
  var ProxyStatus;
43
-
44
38
  (function (ProxyStatus) {
45
39
  ProxyStatus[ProxyStatus["SUCCESS_RANGE_START"] = 200] = "SUCCESS_RANGE_START";
46
40
  ProxyStatus[ProxyStatus["SUCCESS_RANGE_END"] = 299] = "SUCCESS_RANGE_END";
@@ -49,32 +43,26 @@ var ProxyStatus;
49
43
  /**
50
44
  * Constants used for region discovery
51
45
  */
52
-
53
-
54
46
  const REGION_ENVIRONMENT_VARIABLE = "REGION_NAME";
55
47
  /**
56
48
  * Constant used for PKCE
57
49
  */
58
-
59
50
  const RANDOM_OCTET_SIZE = 32;
60
51
  /**
61
52
  * Constants used in PKCE
62
53
  */
63
-
64
54
  const Hash = {
65
55
  SHA256: "sha256"
66
56
  };
67
57
  /**
68
58
  * Constants for encoding schemes
69
59
  */
70
-
71
60
  const CharSet = {
72
61
  CV_CHARSET: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"
73
62
  };
74
63
  /**
75
64
  * Constants
76
65
  */
77
-
78
66
  const Constants = {
79
67
  MSAL_SKU: "msal.js.node",
80
68
  JWT_BEARER_ASSERTION_TYPE: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
@@ -89,9 +77,7 @@ const Constants = {
89
77
  * 600-699 Device Code Flow
90
78
  * 800-899 Auth Code Flow
91
79
  */
92
-
93
80
  var ApiId;
94
-
95
81
  (function (ApiId) {
96
82
  ApiId[ApiId["acquireTokenSilent"] = 62] = "acquireTokenSilent";
97
83
  ApiId[ApiId["acquireTokenByUsernamePassword"] = 371] = "acquireTokenByUsernamePassword";
@@ -103,8 +89,6 @@ var ApiId;
103
89
  /**
104
90
  * JWT constants
105
91
  */
106
-
107
-
108
92
  const JwtConstants = {
109
93
  ALGORITHM: "alg",
110
94
  RSA_256: "RS256",
@@ -134,7 +118,6 @@ class NetworkUtils {
134
118
  status: statusCode
135
119
  };
136
120
  }
137
-
138
121
  }
139
122
 
140
123
  /*
@@ -144,18 +127,21 @@ class NetworkUtils {
144
127
  /**
145
128
  * This class implements the API for network requests.
146
129
  */
147
-
148
130
  class HttpClient {
131
+ constructor(proxyUrl, customAgentOptions) {
132
+ this.proxyUrl = proxyUrl || "";
133
+ this.customAgentOptions = customAgentOptions || {};
134
+ }
149
135
  /**
150
136
  * Http Get request
151
137
  * @param url
152
138
  * @param options
153
139
  */
154
140
  async sendGetRequestAsync(url, options) {
155
- if (options != null && options.proxyUrl) {
156
- return networkRequestViaProxy(url, HttpMethod.GET, options);
141
+ if (this.proxyUrl) {
142
+ return networkRequestViaProxy(url, this.proxyUrl, HttpMethod.GET, options, this.customAgentOptions);
157
143
  } else {
158
- return networkRequestViaHttps(url, HttpMethod.GET, options);
144
+ return networkRequestViaHttps(url, HttpMethod.GET, options, this.customAgentOptions);
159
145
  }
160
146
  }
161
147
  /**
@@ -163,23 +149,19 @@ class HttpClient {
163
149
  * @param url
164
150
  * @param options
165
151
  */
166
-
167
-
168
152
  async sendPostRequestAsync(url, options, cancellationToken) {
169
- if (options != null && options.proxyUrl) {
170
- return networkRequestViaProxy(url, HttpMethod.POST, options, cancellationToken);
153
+ if (this.proxyUrl) {
154
+ return networkRequestViaProxy(url, this.proxyUrl, HttpMethod.POST, options, this.customAgentOptions, cancellationToken);
171
155
  } else {
172
- return networkRequestViaHttps(url, HttpMethod.POST, options, cancellationToken);
156
+ return networkRequestViaHttps(url, HttpMethod.POST, options, this.customAgentOptions, cancellationToken);
173
157
  }
174
158
  }
175
-
176
159
  }
177
-
178
- const networkRequestViaProxy = (url, httpMethod, options, timeout) => {
160
+ const networkRequestViaProxy = (url, proxyUrlString, httpMethod, options, agentOptions, timeout) => {
179
161
  const headers = (options == null ? void 0 : options.headers) || {};
180
- const proxyUrl = new URL((options == null ? void 0 : options.proxyUrl) || "");
181
- const destinationUrl = new URL(url); // "method: connect" must be used to establish a connection to the proxy
182
-
162
+ const proxyUrl = new URL(proxyUrlString);
163
+ const destinationUrl = new URL(url);
164
+ // "method: connect" must be used to establish a connection to the proxy
183
165
  const tunnelRequestOptions = {
184
166
  host: proxyUrl.hostname,
185
167
  port: proxyUrl.port,
@@ -187,41 +169,36 @@ const networkRequestViaProxy = (url, httpMethod, options, timeout) => {
187
169
  path: destinationUrl.hostname,
188
170
  headers: headers
189
171
  };
190
-
191
172
  if (timeout) {
192
173
  tunnelRequestOptions.timeout = timeout;
193
- } // compose a request string for the socket
194
-
195
-
174
+ }
175
+ if (agentOptions && Object.keys(agentOptions).length) {
176
+ tunnelRequestOptions.agent = new http__default.Agent(agentOptions);
177
+ }
178
+ // compose a request string for the socket
196
179
  let postRequestStringContent = "";
197
-
198
180
  if (httpMethod === HttpMethod.POST) {
199
181
  const body = (options == null ? void 0 : options.body) || "";
200
182
  postRequestStringContent = "Content-Type: application/x-www-form-urlencoded\r\n" + `Content-Length: ${body.length}\r\n` + `\r\n${body}`;
201
183
  }
202
-
203
184
  const outgoingRequestString = `${httpMethod.toUpperCase()} ${destinationUrl.href} HTTP/1.1\r\n` + `Host: ${destinationUrl.host}\r\n` + "Connection: close\r\n" + postRequestStringContent + "\r\n";
204
185
  return new Promise((resolve, reject) => {
205
186
  const request = http__default.request(tunnelRequestOptions);
206
-
207
187
  if (tunnelRequestOptions.timeout) {
208
188
  request.on("timeout", () => {
209
189
  request.destroy();
210
190
  reject(new Error("Request time out"));
211
191
  });
212
192
  }
213
-
214
- request.end(); // establish connection to the proxy
215
-
193
+ request.end();
194
+ // establish connection to the proxy
216
195
  request.on("connect", (response, socket) => {
217
196
  const proxyStatusCode = (response == null ? void 0 : response.statusCode) || ProxyStatus.SERVER_ERROR;
218
-
219
197
  if (proxyStatusCode < ProxyStatus.SUCCESS_RANGE_START || proxyStatusCode > ProxyStatus.SUCCESS_RANGE_END) {
220
198
  request.destroy();
221
199
  socket.destroy();
222
200
  reject(new Error(`Error connecting to proxy. Http status code: ${response.statusCode}. Http status message: ${(response == null ? void 0 : response.statusMessage) || "Unknown"}`));
223
201
  }
224
-
225
202
  if (tunnelRequestOptions.timeout) {
226
203
  socket.setTimeout(tunnelRequestOptions.timeout);
227
204
  socket.on("timeout", () => {
@@ -229,9 +206,8 @@ const networkRequestViaProxy = (url, httpMethod, options, timeout) => {
229
206
  socket.destroy();
230
207
  reject(new Error("Request time out"));
231
208
  });
232
- } // make a request over an HTTP tunnel
233
-
234
-
209
+ }
210
+ // make a request over an HTTP tunnel
235
211
  socket.write(outgoingRequestString);
236
212
  const data = [];
237
213
  socket.on("data", chunk => {
@@ -239,18 +215,18 @@ const networkRequestViaProxy = (url, httpMethod, options, timeout) => {
239
215
  });
240
216
  socket.on("end", () => {
241
217
  // combine all received buffer streams into one buffer, and then into a string
242
- const dataString = Buffer.concat([...data]).toString(); // separate each line into it's own entry in an arry
243
-
244
- const dataStringArray = dataString.split("\r\n"); // the first entry will contain the statusCode and statusMessage
245
-
246
- const httpStatusCode = parseInt(dataStringArray[0].split(" ")[1]); // remove "HTTP/1.1" and the status code to get the status message
247
-
248
- const statusMessage = dataStringArray[0].split(" ").slice(2).join(" "); // the last entry will contain the body
249
-
250
- const body = dataStringArray[dataStringArray.length - 1]; // everything in between the first and last entries are the headers
251
-
252
- const headersArray = dataStringArray.slice(1, dataStringArray.length - 2); // build an object out of all the headers
253
-
218
+ const dataString = Buffer.concat([...data]).toString();
219
+ // separate each line into it's own entry in an arry
220
+ const dataStringArray = dataString.split("\r\n");
221
+ // the first entry will contain the statusCode and statusMessage
222
+ const httpStatusCode = parseInt(dataStringArray[0].split(" ")[1]);
223
+ // remove "HTTP/1.1" and the status code to get the status message
224
+ const statusMessage = dataStringArray[0].split(" ").slice(2).join(" ");
225
+ // the last entry will contain the body
226
+ const body = dataStringArray[dataStringArray.length - 1];
227
+ // everything in between the first and last entries are the headers
228
+ const headersArray = dataStringArray.slice(1, dataStringArray.length - 2);
229
+ // build an object out of all the headers
254
230
  const entries = new Map();
255
231
  headersArray.forEach(header => {
256
232
  /**
@@ -261,28 +237,27 @@ const networkRequestViaProxy = (url, httpMethod, options, timeout) => {
261
237
  */
262
238
  const headerKeyValue = header.split(new RegExp(/:\s(.*)/s));
263
239
  const headerKey = headerKeyValue[0];
264
- let headerValue = headerKeyValue[1]; // check if the value of the header is supposed to be a JSON object
265
-
240
+ let headerValue = headerKeyValue[1];
241
+ // check if the value of the header is supposed to be a JSON object
266
242
  try {
267
- const object = JSON.parse(headerValue); // if it is, then convert it from a string to a JSON object
268
-
243
+ const object = JSON.parse(headerValue);
244
+ // if it is, then convert it from a string to a JSON object
269
245
  if (object && typeof object === "object") {
270
246
  headerValue = object;
271
247
  }
272
- } catch (e) {// otherwise, leave it as a string
248
+ } catch (e) {
249
+ // otherwise, leave it as a string
273
250
  }
274
-
275
251
  entries.set(headerKey, headerValue);
276
252
  });
277
253
  const headers = Object.fromEntries(entries);
278
254
  const parsedHeaders = headers;
279
255
  const networkResponse = NetworkUtils.getNetworkResponse(parsedHeaders, parseBody(httpStatusCode, statusMessage, parsedHeaders, body), httpStatusCode);
280
-
281
- if ((httpStatusCode < HttpStatus.SUCCESS_RANGE_START || httpStatusCode > HttpStatus.SUCCESS_RANGE_END) && // do not destroy the request for the device code flow
256
+ if ((httpStatusCode < HttpStatus.SUCCESS_RANGE_START || httpStatusCode > HttpStatus.SUCCESS_RANGE_END) &&
257
+ // do not destroy the request for the device code flow
282
258
  networkResponse.body["error"] !== Constants.AUTHORIZATION_PENDING) {
283
259
  request.destroy();
284
260
  }
285
-
286
261
  resolve(networkResponse);
287
262
  });
288
263
  socket.on("error", chunk => {
@@ -297,8 +272,7 @@ const networkRequestViaProxy = (url, httpMethod, options, timeout) => {
297
272
  });
298
273
  });
299
274
  };
300
-
301
- const networkRequestViaHttps = (url, httpMethod, options, timeout) => {
275
+ const networkRequestViaHttps = (url, httpMethod, options, agentOptions, timeout) => {
302
276
  const isPostRequest = httpMethod === HttpMethod.POST;
303
277
  const body = (options == null ? void 0 : options.body) || "";
304
278
  const emptyHeaders = {};
@@ -306,32 +280,30 @@ const networkRequestViaHttps = (url, httpMethod, options, timeout) => {
306
280
  method: httpMethod,
307
281
  headers: (options == null ? void 0 : options.headers) || emptyHeaders
308
282
  };
309
-
310
283
  if (timeout) {
311
284
  customOptions.timeout = timeout;
312
285
  }
313
-
286
+ if (agentOptions && Object.keys(agentOptions).length) {
287
+ customOptions.agent = new https.Agent(agentOptions);
288
+ }
314
289
  if (isPostRequest) {
315
290
  // needed for post request to work
316
- customOptions.headers = { ...customOptions.headers,
291
+ customOptions.headers = {
292
+ ...customOptions.headers,
317
293
  "Content-Length": body.length
318
294
  };
319
295
  }
320
-
321
296
  return new Promise((resolve, reject) => {
322
297
  const request = https.request(url, customOptions);
323
-
324
298
  if (timeout) {
325
299
  request.on("timeout", () => {
326
300
  request.destroy();
327
301
  reject(new Error("Request time out"));
328
302
  });
329
303
  }
330
-
331
304
  if (isPostRequest) {
332
305
  request.write(body);
333
306
  }
334
-
335
307
  request.end();
336
308
  request.on("response", response => {
337
309
  const headers = response.headers;
@@ -346,12 +318,11 @@ const networkRequestViaHttps = (url, httpMethod, options, timeout) => {
346
318
  const body = Buffer.concat([...data]).toString();
347
319
  const parsedHeaders = headers;
348
320
  const networkResponse = NetworkUtils.getNetworkResponse(parsedHeaders, parseBody(statusCode, statusMessage, parsedHeaders, body), statusCode);
349
-
350
- if ((statusCode < HttpStatus.SUCCESS_RANGE_START || statusCode > HttpStatus.SUCCESS_RANGE_END) && // do not destroy the request for the device code flow
321
+ if ((statusCode < HttpStatus.SUCCESS_RANGE_START || statusCode > HttpStatus.SUCCESS_RANGE_END) &&
322
+ // do not destroy the request for the device code flow
351
323
  networkResponse.body["error"] !== Constants.AUTHORIZATION_PENDING) {
352
324
  request.destroy();
353
325
  }
354
-
355
326
  resolve(networkResponse);
356
327
  });
357
328
  });
@@ -369,8 +340,6 @@ const networkRequestViaHttps = (url, httpMethod, options, timeout) => {
369
340
  * @param body {string} the body from the response of the server
370
341
  * @returns {Object} JSON parsed body or error object
371
342
  */
372
-
373
-
374
343
  const parseBody = (statusCode, statusMessage, headers, body) => {
375
344
  /*
376
345
  * Informational responses (100 – 199)
@@ -380,13 +349,11 @@ const parseBody = (statusCode, statusMessage, headers, body) => {
380
349
  * Server error responses (500 – 599)
381
350
  */
382
351
  let parsedBody;
383
-
384
352
  try {
385
353
  parsedBody = JSON.parse(body);
386
354
  } catch (error) {
387
355
  let errorType;
388
356
  let errorDescriptionHelper;
389
-
390
357
  if (statusCode >= HttpStatus.CLIENT_ERROR_RANGE_START && statusCode <= HttpStatus.CLIENT_ERROR_RANGE_END) {
391
358
  errorType = "client_error";
392
359
  errorDescriptionHelper = "A client";
@@ -397,13 +364,11 @@ const parseBody = (statusCode, statusMessage, headers, body) => {
397
364
  errorType = "unknown_error";
398
365
  errorDescriptionHelper = "An unknown";
399
366
  }
400
-
401
367
  parsedBody = {
402
368
  error: errorType,
403
369
  error_description: `${errorDescriptionHelper} error occured.\nHttp status code: ${statusCode}\nHttp status message: ${statusMessage || "Unknown"}\nHeaders: ${JSON.stringify(headers)}`
404
370
  };
405
371
  }
406
-
407
372
  return parsedBody;
408
373
  };
409
374
 
@@ -434,7 +399,8 @@ const DEFAULT_AUTH_OPTIONS = {
434
399
  };
435
400
  const DEFAULT_CACHE_OPTIONS = {};
436
401
  const DEFAULT_LOGGER_OPTIONS = {
437
- loggerCallback: () => {// allow users to not set logger call back
402
+ loggerCallback: () => {
403
+ // allow users to not set logger call back
438
404
  },
439
405
  piiLoggingEnabled: false,
440
406
  logLevel: msalCommon.LogLevel.Info
@@ -442,7 +408,8 @@ const DEFAULT_LOGGER_OPTIONS = {
442
408
  const DEFAULT_SYSTEM_OPTIONS = {
443
409
  loggerOptions: DEFAULT_LOGGER_OPTIONS,
444
410
  networkClient: /*#__PURE__*/new HttpClient(),
445
- proxyUrl: msalCommon.Constants.EMPTY_STRING
411
+ proxyUrl: msalCommon.Constants.EMPTY_STRING,
412
+ customAgentOptions: {}
446
413
  };
447
414
  const DEFAULT_TELEMETRY_OPTIONS = {
448
415
  application: {
@@ -461,24 +428,32 @@ const DEFAULT_TELEMETRY_OPTIONS = {
461
428
  * @returns Configuration
462
429
  * @public
463
430
  */
464
-
465
431
  function buildAppConfiguration({
466
432
  auth,
467
433
  cache,
468
434
  system,
469
435
  telemetry
470
436
  }) {
437
+ const systemOptions = {
438
+ ...DEFAULT_SYSTEM_OPTIONS,
439
+ networkClient: new HttpClient(system == null ? void 0 : system.proxyUrl, system == null ? void 0 : system.customAgentOptions),
440
+ loggerOptions: (system == null ? void 0 : system.loggerOptions) || DEFAULT_LOGGER_OPTIONS
441
+ };
471
442
  return {
472
- auth: { ...DEFAULT_AUTH_OPTIONS,
443
+ auth: {
444
+ ...DEFAULT_AUTH_OPTIONS,
473
445
  ...auth
474
446
  },
475
- cache: { ...DEFAULT_CACHE_OPTIONS,
447
+ cache: {
448
+ ...DEFAULT_CACHE_OPTIONS,
476
449
  ...cache
477
450
  },
478
- system: { ...DEFAULT_SYSTEM_OPTIONS,
451
+ system: {
452
+ ...systemOptions,
479
453
  ...system
480
454
  },
481
- telemetry: { ...DEFAULT_TELEMETRY_OPTIONS,
455
+ telemetry: {
456
+ ...DEFAULT_TELEMETRY_OPTIONS,
482
457
  ...telemetry
483
458
  }
484
459
  };
@@ -501,13 +476,10 @@ class GuidGenerator {
501
476
  * verifies if a string is GUID
502
477
  * @param guid
503
478
  */
504
-
505
-
506
479
  isGuid(guid) {
507
480
  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;
508
481
  return regexGuid.test(guid);
509
482
  }
510
-
511
483
  }
512
484
 
513
485
  /*
@@ -528,8 +500,6 @@ class EncodingUtils {
528
500
  * encode a URL
529
501
  * @param str
530
502
  */
531
-
532
-
533
503
  static base64EncodeUrl(str, encoding) {
534
504
  return EncodingUtils.base64Encode(str, encoding).replace(/=/g, msalCommon.Constants.EMPTY_STRING).replace(/\+/g, "-").replace(/\//g, "_");
535
505
  }
@@ -539,26 +509,19 @@ class EncodingUtils {
539
509
  *
540
510
  * @param base64Str Base64 encoded text
541
511
  */
542
-
543
-
544
512
  static base64Decode(base64Str) {
545
513
  return Buffer.from(base64Str, "base64").toString("utf8");
546
514
  }
547
515
  /**
548
516
  * @param base64Str Base64 encoded Url
549
517
  */
550
-
551
-
552
518
  static base64DecodeUrl(base64Str) {
553
519
  let str = base64Str.replace(/-/g, "+").replace(/_/g, "/");
554
-
555
520
  while (str.length % 4) {
556
521
  str += "=";
557
522
  }
558
-
559
523
  return EncodingUtils.base64Decode(str);
560
524
  }
561
-
562
525
  }
563
526
 
564
527
  /*
@@ -573,7 +536,6 @@ class HashUtils {
573
536
  sha256(buffer) {
574
537
  return crypto.createHash(Hash.SHA256).update(buffer).digest();
575
538
  }
576
-
577
539
  }
578
540
 
579
541
  /*
@@ -583,7 +545,6 @@ class HashUtils {
583
545
  /**
584
546
  * https://tools.ietf.org/html/rfc7636#page-8
585
547
  */
586
-
587
548
  class PkceGenerator {
588
549
  constructor() {
589
550
  this.hashUtils = new HashUtils();
@@ -592,8 +553,6 @@ class PkceGenerator {
592
553
  * generates the codeVerfier and the challenge from the codeVerfier
593
554
  * reference: https://tools.ietf.org/html/rfc7636#section-4.1 and https://tools.ietf.org/html/rfc7636#section-4.2
594
555
  */
595
-
596
-
597
556
  async generatePkceCodes() {
598
557
  const verifier = this.generateCodeVerifier();
599
558
  const challenge = this.generateCodeChallengeFromVerifier(verifier);
@@ -605,15 +564,11 @@ class PkceGenerator {
605
564
  /**
606
565
  * generates the codeVerfier; reference: https://tools.ietf.org/html/rfc7636#section-4.1
607
566
  */
608
-
609
-
610
567
  generateCodeVerifier() {
611
568
  const charArr = [];
612
569
  const maxNumber = 256 - 256 % CharSet.CV_CHARSET.length;
613
-
614
570
  while (charArr.length <= RANDOM_OCTET_SIZE) {
615
571
  const byte = crypto.randomBytes(1)[0];
616
-
617
572
  if (byte >= maxNumber) {
618
573
  /*
619
574
  * Ignore this number to maintain randomness.
@@ -621,11 +576,9 @@ class PkceGenerator {
621
576
  */
622
577
  continue;
623
578
  }
624
-
625
579
  const index = byte % CharSet.CV_CHARSET.length;
626
580
  charArr.push(CharSet.CV_CHARSET[index]);
627
581
  }
628
-
629
582
  const verifier = charArr.join(msalCommon.Constants.EMPTY_STRING);
630
583
  return EncodingUtils.base64EncodeUrl(verifier);
631
584
  }
@@ -633,12 +586,9 @@ class PkceGenerator {
633
586
  * generate the challenge from the codeVerfier; reference: https://tools.ietf.org/html/rfc7636#section-4.2
634
587
  * @param codeVerifier
635
588
  */
636
-
637
-
638
589
  generateCodeChallengeFromVerifier(codeVerifier) {
639
590
  return EncodingUtils.base64EncodeUrl(this.hashUtils.sha256(codeVerifier).toString("base64"), "base64");
640
591
  }
641
-
642
592
  }
643
593
 
644
594
  /*
@@ -650,7 +600,6 @@ class PkceGenerator {
650
600
  * implementing Proof Key for Code Exchange specs for the OAuth Authorization Code Flow using PKCE (rfc here: https://tools.ietf.org/html/rfc7636).
651
601
  * @public
652
602
  */
653
-
654
603
  class CryptoProvider {
655
604
  constructor() {
656
605
  // Browser crypto needs to be validated first before any other classes can be set.
@@ -662,8 +611,6 @@ class CryptoProvider {
662
611
  * Creates a new random GUID - used to populate state and nonce.
663
612
  * @returns string (GUID)
664
613
  */
665
-
666
-
667
614
  createNewGuid() {
668
615
  return this.guidGenerator.generateGuid();
669
616
  }
@@ -671,8 +618,6 @@ class CryptoProvider {
671
618
  * Encodes input string to base64.
672
619
  * @param input - string to be encoded
673
620
  */
674
-
675
-
676
621
  base64Encode(input) {
677
622
  return EncodingUtils.base64Encode(input);
678
623
  }
@@ -680,24 +625,18 @@ class CryptoProvider {
680
625
  * Decodes input string from base64.
681
626
  * @param input - string to be decoded
682
627
  */
683
-
684
-
685
628
  base64Decode(input) {
686
629
  return EncodingUtils.base64Decode(input);
687
630
  }
688
631
  /**
689
632
  * Generates PKCE codes used in Authorization Code Flow.
690
633
  */
691
-
692
-
693
634
  generatePkceCodes() {
694
635
  return this.pkceGenerator.generatePkceCodes();
695
636
  }
696
637
  /**
697
638
  * Generates a keypair, stores it and returns a thumbprint - not yet implemented for node
698
639
  */
699
-
700
-
701
640
  getPublicKeyThumbprint() {
702
641
  throw new Error("Method not implemented.");
703
642
  }
@@ -705,36 +644,27 @@ class CryptoProvider {
705
644
  * Removes cryptographic keypair from key store matching the keyId passed in
706
645
  * @param kid
707
646
  */
708
-
709
-
710
647
  removeTokenBindingKey() {
711
648
  throw new Error("Method not implemented.");
712
649
  }
713
650
  /**
714
651
  * Removes all cryptographic keys from Keystore
715
652
  */
716
-
717
-
718
653
  clearKeystore() {
719
654
  throw new Error("Method not implemented.");
720
655
  }
721
656
  /**
722
657
  * Signs the given object as a jwt payload with private key retrieved by given kid - currently not implemented for node
723
658
  */
724
-
725
-
726
659
  signJwt() {
727
660
  throw new Error("Method not implemented.");
728
661
  }
729
662
  /**
730
663
  * Returns the SHA-256 hash of an input string
731
664
  */
732
-
733
-
734
665
  async hashString(plainText) {
735
666
  return EncodingUtils.base64EncodeUrl(this.hashUtils.sha256(plainText).toString("base64"), "base64");
736
667
  }
737
-
738
668
  }
739
669
 
740
670
  /*
@@ -744,7 +674,6 @@ class CryptoProvider {
744
674
  /**
745
675
  * This class deserializes cache entities read from the file into in memory object types defined internally
746
676
  */
747
-
748
677
  class Deserializer {
749
678
  /**
750
679
  * Parse the JSON blob in memory and deserialize the content
@@ -758,11 +687,8 @@ class Deserializer {
758
687
  * Deserializes accounts to AccountEntity objects
759
688
  * @param accounts
760
689
  */
761
-
762
-
763
690
  static deserializeAccounts(accounts) {
764
691
  const accountObjects = {};
765
-
766
692
  if (accounts) {
767
693
  Object.keys(accounts).map(function (key) {
768
694
  const serializedAcc = accounts[key];
@@ -783,18 +709,14 @@ class Deserializer {
783
709
  accountObjects[key] = account;
784
710
  });
785
711
  }
786
-
787
712
  return accountObjects;
788
713
  }
789
714
  /**
790
715
  * Deserializes id tokens to IdTokenEntity objects
791
716
  * @param idTokens
792
717
  */
793
-
794
-
795
718
  static deserializeIdTokens(idTokens) {
796
719
  const idObjects = {};
797
-
798
720
  if (idTokens) {
799
721
  Object.keys(idTokens).map(function (key) {
800
722
  const serializedIdT = idTokens[key];
@@ -811,18 +733,14 @@ class Deserializer {
811
733
  idObjects[key] = idToken;
812
734
  });
813
735
  }
814
-
815
736
  return idObjects;
816
737
  }
817
738
  /**
818
739
  * Deserializes access tokens to AccessTokenEntity objects
819
740
  * @param accessTokens
820
741
  */
821
-
822
-
823
742
  static deserializeAccessTokens(accessTokens) {
824
743
  const atObjects = {};
825
-
826
744
  if (accessTokens) {
827
745
  Object.keys(accessTokens).map(function (key) {
828
746
  const serializedAT = accessTokens[key];
@@ -849,18 +767,14 @@ class Deserializer {
849
767
  atObjects[key] = accessToken;
850
768
  });
851
769
  }
852
-
853
770
  return atObjects;
854
771
  }
855
772
  /**
856
773
  * Deserializes refresh tokens to RefreshTokenEntity objects
857
774
  * @param refreshTokens
858
775
  */
859
-
860
-
861
776
  static deserializeRefreshTokens(refreshTokens) {
862
777
  const rtObjects = {};
863
-
864
778
  if (refreshTokens) {
865
779
  Object.keys(refreshTokens).map(function (key) {
866
780
  const serializedRT = refreshTokens[key];
@@ -879,18 +793,14 @@ class Deserializer {
879
793
  rtObjects[key] = refreshToken;
880
794
  });
881
795
  }
882
-
883
796
  return rtObjects;
884
797
  }
885
798
  /**
886
799
  * Deserializes appMetadata to AppMetaData objects
887
800
  * @param appMetadata
888
801
  */
889
-
890
-
891
802
  static deserializeAppMetadata(appMetadata) {
892
803
  const appMetadataObjects = {};
893
-
894
804
  if (appMetadata) {
895
805
  Object.keys(appMetadata).map(function (key) {
896
806
  const serializedAmdt = appMetadata[key];
@@ -904,15 +814,12 @@ class Deserializer {
904
814
  appMetadataObjects[key] = amd;
905
815
  });
906
816
  }
907
-
908
817
  return appMetadataObjects;
909
818
  }
910
819
  /**
911
820
  * Deserialize an inMemory Cache
912
821
  * @param jsonCache
913
822
  */
914
-
915
-
916
823
  static deserializeAllCache(jsonCache) {
917
824
  return {
918
825
  accounts: jsonCache.Account ? this.deserializeAccounts(jsonCache.Account) : {},
@@ -922,7 +829,6 @@ class Deserializer {
922
829
  appMetadata: jsonCache.AppMetadata ? this.deserializeAppMetadata(jsonCache.AppMetadata) : {}
923
830
  };
924
831
  }
925
-
926
832
  }
927
833
 
928
834
  /*
@@ -941,8 +847,6 @@ class Serializer {
941
847
  * Serialize Accounts
942
848
  * @param accCache
943
849
  */
944
-
945
-
946
850
  static serializeAccounts(accCache) {
947
851
  const accounts = {};
948
852
  Object.keys(accCache).map(function (key) {
@@ -966,8 +870,6 @@ class Serializer {
966
870
  * Serialize IdTokens
967
871
  * @param idTCache
968
872
  */
969
-
970
-
971
873
  static serializeIdTokens(idTCache) {
972
874
  const idTokens = {};
973
875
  Object.keys(idTCache).map(function (key) {
@@ -987,8 +889,6 @@ class Serializer {
987
889
  * Serializes AccessTokens
988
890
  * @param atCache
989
891
  */
990
-
991
-
992
892
  static serializeAccessTokens(atCache) {
993
893
  const accessTokens = {};
994
894
  Object.keys(atCache).map(function (key) {
@@ -1018,8 +918,6 @@ class Serializer {
1018
918
  * Serialize refreshTokens
1019
919
  * @param rtCache
1020
920
  */
1021
-
1022
-
1023
921
  static serializeRefreshTokens(rtCache) {
1024
922
  const refreshTokens = {};
1025
923
  Object.keys(rtCache).map(function (key) {
@@ -1041,8 +939,6 @@ class Serializer {
1041
939
  * Serialize amdtCache
1042
940
  * @param amdtCache
1043
941
  */
1044
-
1045
-
1046
942
  static serializeAppMetadata(amdtCache) {
1047
943
  const appMetadata = {};
1048
944
  Object.keys(amdtCache).map(function (key) {
@@ -1059,8 +955,6 @@ class Serializer {
1059
955
  * Serialize the cache
1060
956
  * @param jsonContent
1061
957
  */
1062
-
1063
-
1064
958
  static serializeAllCache(inMemCache) {
1065
959
  return {
1066
960
  Account: this.serializeAccounts(inMemCache.accounts),
@@ -1070,7 +964,6 @@ class Serializer {
1070
964
  AppMetadata: this.serializeAppMetadata(inMemCache.appMetadata)
1071
965
  };
1072
966
  }
1073
-
1074
967
  }
1075
968
 
1076
969
  /*
@@ -1081,7 +974,6 @@ class Serializer {
1081
974
  * This class implements Storage for node, reading cache from user specified storage location or an extension library
1082
975
  * @public
1083
976
  */
1084
-
1085
977
  class NodeStorage extends msalCommon.CacheManager {
1086
978
  constructor(logger, clientId, cryptoImpl) {
1087
979
  super(clientId, cryptoImpl);
@@ -1093,16 +985,12 @@ class NodeStorage extends msalCommon.CacheManager {
1093
985
  * Queue up callbacks
1094
986
  * @param func - a callback function for cache change indication
1095
987
  */
1096
-
1097
-
1098
988
  registerChangeEmitter(func) {
1099
989
  this.changeEmitters.push(func);
1100
990
  }
1101
991
  /**
1102
992
  * Invoke the callback when cache changes
1103
993
  */
1104
-
1105
-
1106
994
  emitChange() {
1107
995
  this.changeEmitters.forEach(func => func.call(null));
1108
996
  }
@@ -1110,8 +998,6 @@ class NodeStorage extends msalCommon.CacheManager {
1110
998
  * Converts cacheKVStore to InMemoryCache
1111
999
  * @param cache - key value store
1112
1000
  */
1113
-
1114
-
1115
1001
  cacheToInMemoryCache(cache) {
1116
1002
  const inMemoryCache = {
1117
1003
  accounts: {},
@@ -1120,7 +1006,6 @@ class NodeStorage extends msalCommon.CacheManager {
1120
1006
  refreshTokens: {},
1121
1007
  appMetadata: {}
1122
1008
  };
1123
-
1124
1009
  for (const key in cache) {
1125
1010
  if (cache[key] instanceof msalCommon.AccountEntity) {
1126
1011
  inMemoryCache.accounts[key] = cache[key];
@@ -1136,36 +1021,32 @@ class NodeStorage extends msalCommon.CacheManager {
1136
1021
  continue;
1137
1022
  }
1138
1023
  }
1139
-
1140
1024
  return inMemoryCache;
1141
1025
  }
1142
1026
  /**
1143
1027
  * converts inMemoryCache to CacheKVStore
1144
1028
  * @param inMemoryCache - kvstore map for inmemory
1145
1029
  */
1146
-
1147
-
1148
1030
  inMemoryCacheToCache(inMemoryCache) {
1149
1031
  // convert in memory cache to a flat Key-Value map
1150
1032
  let cache = this.getCache();
1151
- cache = { ...cache,
1033
+ cache = {
1034
+ ...cache,
1152
1035
  ...inMemoryCache.accounts,
1153
1036
  ...inMemoryCache.idTokens,
1154
1037
  ...inMemoryCache.accessTokens,
1155
1038
  ...inMemoryCache.refreshTokens,
1156
1039
  ...inMemoryCache.appMetadata
1157
- }; // convert in memory cache to a flat Key-Value map
1158
-
1040
+ };
1041
+ // convert in memory cache to a flat Key-Value map
1159
1042
  return cache;
1160
1043
  }
1161
1044
  /**
1162
1045
  * gets the current in memory cache for the client
1163
1046
  */
1164
-
1165
-
1166
1047
  getInMemoryCache() {
1167
- this.logger.trace("Getting in-memory cache"); // convert the cache key value store to inMemoryCache
1168
-
1048
+ this.logger.trace("Getting in-memory cache");
1049
+ // convert the cache key value store to inMemoryCache
1169
1050
  const inMemoryCache = this.cacheToInMemoryCache(this.getCache());
1170
1051
  return inMemoryCache;
1171
1052
  }
@@ -1173,11 +1054,9 @@ class NodeStorage extends msalCommon.CacheManager {
1173
1054
  * sets the current in memory cache for the client
1174
1055
  * @param inMemoryCache - key value map in memory
1175
1056
  */
1176
-
1177
-
1178
1057
  setInMemoryCache(inMemoryCache) {
1179
- this.logger.trace("Setting in-memory cache"); // convert and append the inMemoryCache to cacheKVStore
1180
-
1058
+ this.logger.trace("Setting in-memory cache");
1059
+ // convert and append the inMemoryCache to cacheKVStore
1181
1060
  const cache = this.inMemoryCacheToCache(inMemoryCache);
1182
1061
  this.setCache(cache);
1183
1062
  this.emitChange();
@@ -1185,8 +1064,6 @@ class NodeStorage extends msalCommon.CacheManager {
1185
1064
  /**
1186
1065
  * get the current cache key-value store
1187
1066
  */
1188
-
1189
-
1190
1067
  getCache() {
1191
1068
  this.logger.trace("Getting cache key-value store");
1192
1069
  return this.cache;
@@ -1195,23 +1072,19 @@ class NodeStorage extends msalCommon.CacheManager {
1195
1072
  * sets the current cache (key value store)
1196
1073
  * @param cacheMap - key value map
1197
1074
  */
1198
-
1199
-
1200
1075
  setCache(cache) {
1201
1076
  this.logger.trace("Setting cache key value store");
1202
- this.cache = cache; // mark change in cache
1203
-
1077
+ this.cache = cache;
1078
+ // mark change in cache
1204
1079
  this.emitChange();
1205
1080
  }
1206
1081
  /**
1207
1082
  * Gets cache item with given key.
1208
1083
  * @param key - lookup key for the cache entry
1209
1084
  */
1210
-
1211
-
1212
1085
  getItem(key) {
1213
- this.logger.tracePii(`Item key: ${key}`); // read cache
1214
-
1086
+ this.logger.tracePii(`Item key: ${key}`);
1087
+ // read cache
1215
1088
  const cache = this.getCache();
1216
1089
  return cache[key];
1217
1090
  }
@@ -1220,37 +1093,29 @@ class NodeStorage extends msalCommon.CacheManager {
1220
1093
  * @param key - lookup key for the cache entry
1221
1094
  * @param value - value of the cache entry
1222
1095
  */
1223
-
1224
-
1225
1096
  setItem(key, value) {
1226
- this.logger.tracePii(`Item key: ${key}`); // read cache
1227
-
1097
+ this.logger.tracePii(`Item key: ${key}`);
1098
+ // read cache
1228
1099
  const cache = this.getCache();
1229
- cache[key] = value; // write to cache
1230
-
1100
+ cache[key] = value;
1101
+ // write to cache
1231
1102
  this.setCache(cache);
1232
1103
  }
1233
1104
  /**
1234
1105
  * fetch the account entity
1235
1106
  * @param accountKey - lookup key to fetch cache type AccountEntity
1236
1107
  */
1237
-
1238
-
1239
1108
  getAccount(accountKey) {
1240
1109
  const account = this.getItem(accountKey);
1241
-
1242
1110
  if (msalCommon.AccountEntity.isAccountEntity(account)) {
1243
1111
  return account;
1244
1112
  }
1245
-
1246
1113
  return null;
1247
1114
  }
1248
1115
  /**
1249
1116
  * set account entity
1250
1117
  * @param account - cache value to be set of type AccountEntity
1251
1118
  */
1252
-
1253
-
1254
1119
  setAccount(account) {
1255
1120
  const accountKey = account.generateAccountKey();
1256
1121
  this.setItem(accountKey, account);
@@ -1259,23 +1124,17 @@ class NodeStorage extends msalCommon.CacheManager {
1259
1124
  * fetch the idToken credential
1260
1125
  * @param idTokenKey - lookup key to fetch cache type IdTokenEntity
1261
1126
  */
1262
-
1263
-
1264
1127
  getIdTokenCredential(idTokenKey) {
1265
1128
  const idToken = this.getItem(idTokenKey);
1266
-
1267
1129
  if (msalCommon.IdTokenEntity.isIdTokenEntity(idToken)) {
1268
1130
  return idToken;
1269
1131
  }
1270
-
1271
1132
  return null;
1272
1133
  }
1273
1134
  /**
1274
1135
  * set idToken credential
1275
1136
  * @param idToken - cache value to be set of type IdTokenEntity
1276
1137
  */
1277
-
1278
-
1279
1138
  setIdTokenCredential(idToken) {
1280
1139
  const idTokenKey = idToken.generateCredentialKey();
1281
1140
  this.setItem(idTokenKey, idToken);
@@ -1284,23 +1143,17 @@ class NodeStorage extends msalCommon.CacheManager {
1284
1143
  * fetch the accessToken credential
1285
1144
  * @param accessTokenKey - lookup key to fetch cache type AccessTokenEntity
1286
1145
  */
1287
-
1288
-
1289
1146
  getAccessTokenCredential(accessTokenKey) {
1290
1147
  const accessToken = this.getItem(accessTokenKey);
1291
-
1292
1148
  if (msalCommon.AccessTokenEntity.isAccessTokenEntity(accessToken)) {
1293
1149
  return accessToken;
1294
1150
  }
1295
-
1296
1151
  return null;
1297
1152
  }
1298
1153
  /**
1299
1154
  * set accessToken credential
1300
1155
  * @param accessToken - cache value to be set of type AccessTokenEntity
1301
1156
  */
1302
-
1303
-
1304
1157
  setAccessTokenCredential(accessToken) {
1305
1158
  const accessTokenKey = accessToken.generateCredentialKey();
1306
1159
  this.setItem(accessTokenKey, accessToken);
@@ -1309,23 +1162,17 @@ class NodeStorage extends msalCommon.CacheManager {
1309
1162
  * fetch the refreshToken credential
1310
1163
  * @param refreshTokenKey - lookup key to fetch cache type RefreshTokenEntity
1311
1164
  */
1312
-
1313
-
1314
1165
  getRefreshTokenCredential(refreshTokenKey) {
1315
1166
  const refreshToken = this.getItem(refreshTokenKey);
1316
-
1317
1167
  if (msalCommon.RefreshTokenEntity.isRefreshTokenEntity(refreshToken)) {
1318
1168
  return refreshToken;
1319
1169
  }
1320
-
1321
1170
  return null;
1322
1171
  }
1323
1172
  /**
1324
1173
  * set refreshToken credential
1325
1174
  * @param refreshToken - cache value to be set of type RefreshTokenEntity
1326
1175
  */
1327
-
1328
-
1329
1176
  setRefreshTokenCredential(refreshToken) {
1330
1177
  const refreshTokenKey = refreshToken.generateCredentialKey();
1331
1178
  this.setItem(refreshTokenKey, refreshToken);
@@ -1334,23 +1181,17 @@ class NodeStorage extends msalCommon.CacheManager {
1334
1181
  * fetch appMetadata entity from the platform cache
1335
1182
  * @param appMetadataKey - lookup key to fetch cache type AppMetadataEntity
1336
1183
  */
1337
-
1338
-
1339
1184
  getAppMetadata(appMetadataKey) {
1340
1185
  const appMetadata = this.getItem(appMetadataKey);
1341
-
1342
1186
  if (msalCommon.AppMetadataEntity.isAppMetadataEntity(appMetadataKey, appMetadata)) {
1343
1187
  return appMetadata;
1344
1188
  }
1345
-
1346
1189
  return null;
1347
1190
  }
1348
1191
  /**
1349
1192
  * set appMetadata entity to the platform cache
1350
1193
  * @param appMetadata - cache value to be set of type AppMetadataEntity
1351
1194
  */
1352
-
1353
-
1354
1195
  setAppMetadata(appMetadata) {
1355
1196
  const appMetadataKey = appMetadata.generateAppMetadataKey();
1356
1197
  this.setItem(appMetadataKey, appMetadata);
@@ -1359,15 +1200,11 @@ class NodeStorage extends msalCommon.CacheManager {
1359
1200
  * fetch server telemetry entity from the platform cache
1360
1201
  * @param serverTelemetrykey - lookup key to fetch cache type ServerTelemetryEntity
1361
1202
  */
1362
-
1363
-
1364
1203
  getServerTelemetry(serverTelemetrykey) {
1365
1204
  const serverTelemetryEntity = this.getItem(serverTelemetrykey);
1366
-
1367
1205
  if (serverTelemetryEntity && msalCommon.ServerTelemetryEntity.isServerTelemetryEntity(serverTelemetrykey, serverTelemetryEntity)) {
1368
1206
  return serverTelemetryEntity;
1369
1207
  }
1370
-
1371
1208
  return null;
1372
1209
  }
1373
1210
  /**
@@ -1375,8 +1212,6 @@ class NodeStorage extends msalCommon.CacheManager {
1375
1212
  * @param serverTelemetryKey - lookup key to fetch cache type ServerTelemetryEntity
1376
1213
  * @param serverTelemetry - cache value to be set of type ServerTelemetryEntity
1377
1214
  */
1378
-
1379
-
1380
1215
  setServerTelemetry(serverTelemetryKey, serverTelemetry) {
1381
1216
  this.setItem(serverTelemetryKey, serverTelemetry);
1382
1217
  }
@@ -1384,22 +1219,16 @@ class NodeStorage extends msalCommon.CacheManager {
1384
1219
  * fetch authority metadata entity from the platform cache
1385
1220
  * @param key - lookup key to fetch cache type AuthorityMetadataEntity
1386
1221
  */
1387
-
1388
-
1389
1222
  getAuthorityMetadata(key) {
1390
1223
  const authorityMetadataEntity = this.getItem(key);
1391
-
1392
1224
  if (authorityMetadataEntity && msalCommon.AuthorityMetadataEntity.isAuthorityMetadataEntity(key, authorityMetadataEntity)) {
1393
1225
  return authorityMetadataEntity;
1394
1226
  }
1395
-
1396
1227
  return null;
1397
1228
  }
1398
1229
  /**
1399
1230
  * Get all authority metadata keys
1400
1231
  */
1401
-
1402
-
1403
1232
  getAuthorityMetadataKeys() {
1404
1233
  return this.getKeys().filter(key => {
1405
1234
  return this.isAuthorityMetadata(key);
@@ -1410,8 +1239,6 @@ class NodeStorage extends msalCommon.CacheManager {
1410
1239
  * @param key - lookup key to fetch cache type AuthorityMetadataEntity
1411
1240
  * @param metadata - cache value to be set of type AuthorityMetadataEntity
1412
1241
  */
1413
-
1414
-
1415
1242
  setAuthorityMetadata(key, metadata) {
1416
1243
  this.setItem(key, metadata);
1417
1244
  }
@@ -1419,15 +1246,11 @@ class NodeStorage extends msalCommon.CacheManager {
1419
1246
  * fetch throttling entity from the platform cache
1420
1247
  * @param throttlingCacheKey - lookup key to fetch cache type ThrottlingEntity
1421
1248
  */
1422
-
1423
-
1424
1249
  getThrottlingCache(throttlingCacheKey) {
1425
1250
  const throttlingCache = this.getItem(throttlingCacheKey);
1426
-
1427
1251
  if (throttlingCache && msalCommon.ThrottlingEntity.isThrottlingEntity(throttlingCacheKey, throttlingCache)) {
1428
1252
  return throttlingCache;
1429
1253
  }
1430
-
1431
1254
  return null;
1432
1255
  }
1433
1256
  /**
@@ -1435,8 +1258,6 @@ class NodeStorage extends msalCommon.CacheManager {
1435
1258
  * @param throttlingCacheKey - lookup key to fetch cache type ThrottlingEntity
1436
1259
  * @param throttlingCache - cache value to be set of type ThrottlingEntity
1437
1260
  */
1438
-
1439
-
1440
1261
  setThrottlingCache(throttlingCacheKey, throttlingCache) {
1441
1262
  this.setItem(throttlingCacheKey, throttlingCache);
1442
1263
  }
@@ -1445,57 +1266,46 @@ class NodeStorage extends msalCommon.CacheManager {
1445
1266
  * @param key - lookup key to remove a cache entity
1446
1267
  * @param inMemory - key value map of the cache
1447
1268
  */
1448
-
1449
-
1450
1269
  removeItem(key) {
1451
- this.logger.tracePii(`Item key: ${key}`); // read inMemoryCache
1452
-
1270
+ this.logger.tracePii(`Item key: ${key}`);
1271
+ // read inMemoryCache
1453
1272
  let result = false;
1454
1273
  const cache = this.getCache();
1455
-
1456
1274
  if (!!cache[key]) {
1457
1275
  delete cache[key];
1458
1276
  result = true;
1459
- } // write to the cache after removal
1460
-
1461
-
1277
+ }
1278
+ // write to the cache after removal
1462
1279
  if (result) {
1463
1280
  this.setCache(cache);
1464
1281
  this.emitChange();
1465
1282
  }
1466
-
1467
1283
  return result;
1468
1284
  }
1469
1285
  /**
1470
1286
  * Checks whether key is in cache.
1471
1287
  * @param key - look up key for a cache entity
1472
1288
  */
1473
-
1474
-
1475
1289
  containsKey(key) {
1476
1290
  return this.getKeys().includes(key);
1477
1291
  }
1478
1292
  /**
1479
1293
  * Gets all keys in window.
1480
1294
  */
1481
-
1482
-
1483
1295
  getKeys() {
1484
- this.logger.trace("Retrieving all cache keys"); // read cache
1485
-
1296
+ this.logger.trace("Retrieving all cache keys");
1297
+ // read cache
1486
1298
  const cache = this.getCache();
1487
1299
  return [...Object.keys(cache)];
1488
1300
  }
1489
1301
  /**
1490
1302
  * Clears all cache entries created by MSAL (except tokens).
1491
1303
  */
1492
-
1493
-
1494
1304
  async clear() {
1495
- this.logger.trace("Clearing cache entries created by MSAL"); // read inMemoryCache
1496
-
1497
- const cacheKeys = this.getKeys(); // delete each element
1498
-
1305
+ this.logger.trace("Clearing cache entries created by MSAL");
1306
+ // read inMemoryCache
1307
+ const cacheKeys = this.getKeys();
1308
+ // delete each element
1499
1309
  cacheKeys.forEach(key => {
1500
1310
  this.removeItem(key);
1501
1311
  });
@@ -1505,8 +1315,6 @@ class NodeStorage extends msalCommon.CacheManager {
1505
1315
  * Initialize in memory cache from an exisiting cache vault
1506
1316
  * @param cache - blob formatted cache (JSON)
1507
1317
  */
1508
-
1509
-
1510
1318
  static generateInMemoryCache(cache) {
1511
1319
  return Deserializer.deserializeAllCache(Deserializer.deserializeJSONBlob(cache));
1512
1320
  }
@@ -1514,22 +1322,16 @@ class NodeStorage extends msalCommon.CacheManager {
1514
1322
  * retrieves the final JSON
1515
1323
  * @param inMemoryCache - itemised cache read from the JSON
1516
1324
  */
1517
-
1518
-
1519
1325
  static generateJsonCache(inMemoryCache) {
1520
1326
  return Serializer.serializeAllCache(inMemoryCache);
1521
1327
  }
1522
1328
  /**
1523
1329
  * Updates a credential's cache key if the current cache key is outdated
1524
1330
  */
1525
-
1526
-
1527
1331
  updateCredentialCacheKey(currentCacheKey, credential) {
1528
1332
  const updatedCacheKey = credential.generateCredentialKey();
1529
-
1530
1333
  if (currentCacheKey !== updatedCacheKey) {
1531
1334
  const cacheItem = this.getItem(currentCacheKey);
1532
-
1533
1335
  if (cacheItem) {
1534
1336
  this.removeItem(currentCacheKey);
1535
1337
  this.setItem(updatedCacheKey, cacheItem);
@@ -1539,10 +1341,8 @@ class NodeStorage extends msalCommon.CacheManager {
1539
1341
  this.logger.error(`Attempted to update an outdated ${credential.credentialType} cache key but no item matching the outdated key was found in storage`);
1540
1342
  }
1541
1343
  }
1542
-
1543
1344
  return currentCacheKey;
1544
1345
  }
1545
-
1546
1346
  }
1547
1347
 
1548
1348
  /*
@@ -1560,43 +1360,35 @@ const defaultSerializedCache = {
1560
1360
  * In-memory token cache manager
1561
1361
  * @public
1562
1362
  */
1563
-
1564
1363
  class TokenCache {
1565
1364
  constructor(storage, logger, cachePlugin) {
1566
1365
  this.cacheHasChanged = false;
1567
1366
  this.storage = storage;
1568
1367
  this.storage.registerChangeEmitter(this.handleChangeEvent.bind(this));
1569
-
1570
1368
  if (cachePlugin) {
1571
1369
  this.persistence = cachePlugin;
1572
1370
  }
1573
-
1574
1371
  this.logger = logger;
1575
1372
  }
1576
1373
  /**
1577
1374
  * Set to true if cache state has changed since last time serialize or writeToPersistence was called
1578
1375
  */
1579
-
1580
-
1581
1376
  hasChanged() {
1582
1377
  return this.cacheHasChanged;
1583
1378
  }
1584
1379
  /**
1585
1380
  * Serializes in memory cache to JSON
1586
1381
  */
1587
-
1588
-
1589
1382
  serialize() {
1590
1383
  this.logger.trace("Serializing in-memory cache");
1591
- let finalState = Serializer.serializeAllCache(this.storage.getInMemoryCache()); // if cacheSnapshot not null or empty, merge
1592
-
1384
+ let finalState = Serializer.serializeAllCache(this.storage.getInMemoryCache());
1385
+ // if cacheSnapshot not null or empty, merge
1593
1386
  if (!msalCommon.StringUtils.isEmpty(this.cacheSnapshot)) {
1594
1387
  this.logger.trace("Reading cache snapshot from disk");
1595
1388
  finalState = this.mergeState(JSON.parse(this.cacheSnapshot), finalState);
1596
1389
  } else {
1597
1390
  this.logger.trace("No cache snapshot to merge");
1598
1391
  }
1599
-
1600
1392
  this.cacheHasChanged = false;
1601
1393
  return JSON.stringify(finalState);
1602
1394
  }
@@ -1604,12 +1396,9 @@ class TokenCache {
1604
1396
  * Deserializes JSON to in-memory cache. JSON should be in MSAL cache schema format
1605
1397
  * @param cache - blob formatted cache
1606
1398
  */
1607
-
1608
-
1609
1399
  deserialize(cache) {
1610
1400
  this.logger.trace("Deserializing JSON to in-memory cache");
1611
1401
  this.cacheSnapshot = cache;
1612
-
1613
1402
  if (!msalCommon.StringUtils.isEmpty(this.cacheSnapshot)) {
1614
1403
  this.logger.trace("Reading cache snapshot from disk");
1615
1404
  const deserializedCache = Deserializer.deserializeAllCache(this.overlayDefaults(JSON.parse(this.cacheSnapshot)));
@@ -1621,26 +1410,20 @@ class TokenCache {
1621
1410
  /**
1622
1411
  * Fetches the cache key-value map
1623
1412
  */
1624
-
1625
-
1626
1413
  getKVStore() {
1627
1414
  return this.storage.getCache();
1628
1415
  }
1629
1416
  /**
1630
1417
  * API that retrieves all accounts currently in cache to the user
1631
1418
  */
1632
-
1633
-
1634
1419
  async getAllAccounts() {
1635
1420
  this.logger.trace("getAllAccounts called");
1636
1421
  let cacheContext;
1637
-
1638
1422
  try {
1639
1423
  if (this.persistence) {
1640
1424
  cacheContext = new msalCommon.TokenCacheContext(this, false);
1641
1425
  await this.persistence.beforeCacheAccess(cacheContext);
1642
1426
  }
1643
-
1644
1427
  return this.storage.getAllAccounts();
1645
1428
  } finally {
1646
1429
  if (this.persistence && cacheContext) {
@@ -1654,11 +1437,8 @@ class TokenCache {
1654
1437
  * or null when no matching account is found
1655
1438
  * @param homeAccountId - unique identifier for an account (uid.utid)
1656
1439
  */
1657
-
1658
-
1659
1440
  async getAccountByHomeId(homeAccountId) {
1660
1441
  const allAccounts = await this.getAllAccounts();
1661
-
1662
1442
  if (!msalCommon.StringUtils.isEmpty(homeAccountId) && allAccounts && allAccounts.length) {
1663
1443
  return allAccounts.filter(accountObj => accountObj.homeAccountId === homeAccountId)[0] || null;
1664
1444
  } else {
@@ -1671,11 +1451,8 @@ class TokenCache {
1671
1451
  * or null when no matching account is found
1672
1452
  * @param localAccountId - unique identifier of an account (sub/obj when homeAccountId cannot be populated)
1673
1453
  */
1674
-
1675
-
1676
1454
  async getAccountByLocalId(localAccountId) {
1677
1455
  const allAccounts = await this.getAllAccounts();
1678
-
1679
1456
  if (!msalCommon.StringUtils.isEmpty(localAccountId) && allAccounts && allAccounts.length) {
1680
1457
  return allAccounts.filter(accountObj => accountObj.localAccountId === localAccountId)[0] || null;
1681
1458
  } else {
@@ -1686,18 +1463,14 @@ class TokenCache {
1686
1463
  * API to remove a specific account and the relevant data from cache
1687
1464
  * @param account - AccountInfo passed by the user
1688
1465
  */
1689
-
1690
-
1691
1466
  async removeAccount(account) {
1692
1467
  this.logger.trace("removeAccount called");
1693
1468
  let cacheContext;
1694
-
1695
1469
  try {
1696
1470
  if (this.persistence) {
1697
1471
  cacheContext = new msalCommon.TokenCacheContext(this, true);
1698
1472
  await this.persistence.beforeCacheAccess(cacheContext);
1699
1473
  }
1700
-
1701
1474
  await this.storage.removeAccount(msalCommon.AccountEntity.generateAccountCacheKey(account));
1702
1475
  } finally {
1703
1476
  if (this.persistence && cacheContext) {
@@ -1708,8 +1481,6 @@ class TokenCache {
1708
1481
  /**
1709
1482
  * Called when the cache has changed state.
1710
1483
  */
1711
-
1712
-
1713
1484
  handleChangeEvent() {
1714
1485
  this.cacheHasChanged = true;
1715
1486
  }
@@ -1718,8 +1489,6 @@ class TokenCache {
1718
1489
  * @param oldState - cache before changes
1719
1490
  * @param currentState - current cache state in the library
1720
1491
  */
1721
-
1722
-
1723
1492
  mergeState(oldState, currentState) {
1724
1493
  this.logger.trace("Merging in-memory cache with cache snapshot");
1725
1494
  const stateAfterRemoval = this.mergeRemovals(oldState, currentState);
@@ -1730,12 +1499,10 @@ class TokenCache {
1730
1499
  * @param oldState - cache before changes
1731
1500
  * @param newState - updated cache
1732
1501
  */
1733
-
1734
-
1735
1502
  mergeUpdates(oldState, newState) {
1736
1503
  Object.keys(newState).forEach(newKey => {
1737
- const newValue = newState[newKey]; // if oldState does not contain value but newValue does, add it
1738
-
1504
+ const newValue = newState[newKey];
1505
+ // if oldState does not contain value but newValue does, add it
1739
1506
  if (!oldState.hasOwnProperty(newKey)) {
1740
1507
  if (newValue !== null) {
1741
1508
  oldState[newKey] = newValue;
@@ -1746,7 +1513,6 @@ class TokenCache {
1746
1513
  const newValueIsObject = typeof newValue === "object";
1747
1514
  const newValueIsNotArray = !Array.isArray(newValue);
1748
1515
  const oldStateNotUndefinedOrNull = typeof oldState[newKey] !== "undefined" && oldState[newKey] !== null;
1749
-
1750
1516
  if (newValueNotNull && newValueIsObject && newValueIsNotArray && oldStateNotUndefinedOrNull) {
1751
1517
  this.mergeUpdates(oldState[newKey], newValue);
1752
1518
  } else {
@@ -1762,8 +1528,6 @@ class TokenCache {
1762
1528
  * @param oldState - cache before changes
1763
1529
  * @param newState - updated cache
1764
1530
  */
1765
-
1766
-
1767
1531
  mergeRemovals(oldState, newState) {
1768
1532
  this.logger.trace("Remove updated entries in cache");
1769
1533
  const accounts = oldState.Account ? this.mergeRemovalsDict(oldState.Account, newState.Account) : oldState.Account;
@@ -1771,7 +1535,8 @@ class TokenCache {
1771
1535
  const refreshTokens = oldState.RefreshToken ? this.mergeRemovalsDict(oldState.RefreshToken, newState.RefreshToken) : oldState.RefreshToken;
1772
1536
  const idTokens = oldState.IdToken ? this.mergeRemovalsDict(oldState.IdToken, newState.IdToken) : oldState.IdToken;
1773
1537
  const appMetadata = oldState.AppMetadata ? this.mergeRemovalsDict(oldState.AppMetadata, newState.AppMetadata) : oldState.AppMetadata;
1774
- return { ...oldState,
1538
+ return {
1539
+ ...oldState,
1775
1540
  Account: accounts,
1776
1541
  AccessToken: accessTokens,
1777
1542
  RefreshToken: refreshTokens,
@@ -1784,10 +1549,9 @@ class TokenCache {
1784
1549
  * @param oldState - cache before changes
1785
1550
  * @param newState - updated cache
1786
1551
  */
1787
-
1788
-
1789
1552
  mergeRemovalsDict(oldState, newState) {
1790
- const finalState = { ...oldState
1553
+ const finalState = {
1554
+ ...oldState
1791
1555
  };
1792
1556
  Object.keys(oldState).forEach(oldKey => {
1793
1557
  if (!newState || !newState.hasOwnProperty(oldKey)) {
@@ -1800,34 +1564,36 @@ class TokenCache {
1800
1564
  * Helper to overlay as a part of cache merge
1801
1565
  * @param passedInCache - cache read from the blob
1802
1566
  */
1803
-
1804
-
1805
1567
  overlayDefaults(passedInCache) {
1806
1568
  this.logger.trace("Overlaying input cache with the default cache");
1807
1569
  return {
1808
- Account: { ...defaultSerializedCache.Account,
1570
+ Account: {
1571
+ ...defaultSerializedCache.Account,
1809
1572
  ...passedInCache.Account
1810
1573
  },
1811
- IdToken: { ...defaultSerializedCache.IdToken,
1574
+ IdToken: {
1575
+ ...defaultSerializedCache.IdToken,
1812
1576
  ...passedInCache.IdToken
1813
1577
  },
1814
- AccessToken: { ...defaultSerializedCache.AccessToken,
1578
+ AccessToken: {
1579
+ ...defaultSerializedCache.AccessToken,
1815
1580
  ...passedInCache.AccessToken
1816
1581
  },
1817
- RefreshToken: { ...defaultSerializedCache.RefreshToken,
1582
+ RefreshToken: {
1583
+ ...defaultSerializedCache.RefreshToken,
1818
1584
  ...passedInCache.RefreshToken
1819
1585
  },
1820
- AppMetadata: { ...defaultSerializedCache.AppMetadata,
1586
+ AppMetadata: {
1587
+ ...defaultSerializedCache.AppMetadata,
1821
1588
  ...passedInCache.AppMetadata
1822
1589
  }
1823
1590
  };
1824
1591
  }
1825
-
1826
1592
  }
1827
1593
 
1828
1594
  /* eslint-disable header/header */
1829
1595
  const name = "@azure/msal-node";
1830
- const version = "1.14.5";
1596
+ const version = "1.15.0";
1831
1597
 
1832
1598
  /*
1833
1599
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -1836,7 +1602,6 @@ const version = "1.14.5";
1836
1602
  /**
1837
1603
  * NodeAuthErrorMessage class containing string constants used by error codes and messages.
1838
1604
  */
1839
-
1840
1605
  const NodeAuthErrorMessage = {
1841
1606
  invalidLoopbackAddressType: {
1842
1607
  code: "invalid_loopback_server_address_type",
@@ -1875,60 +1640,45 @@ class NodeAuthError extends msalCommon.AuthError {
1875
1640
  /**
1876
1641
  * Creates an error thrown if loopback server address is of type string.
1877
1642
  */
1878
-
1879
-
1880
1643
  static createInvalidLoopbackAddressTypeError() {
1881
1644
  return new NodeAuthError(NodeAuthErrorMessage.invalidLoopbackAddressType.code, `${NodeAuthErrorMessage.invalidLoopbackAddressType.desc}`);
1882
1645
  }
1883
1646
  /**
1884
1647
  * Creates an error thrown if the loopback server is unable to get a url.
1885
1648
  */
1886
-
1887
-
1888
1649
  static createUnableToLoadRedirectUrlError() {
1889
1650
  return new NodeAuthError(NodeAuthErrorMessage.unableToLoadRedirectUri.code, `${NodeAuthErrorMessage.unableToLoadRedirectUri.desc}`);
1890
1651
  }
1891
1652
  /**
1892
1653
  * Creates an error thrown if the server response does not contain an auth code.
1893
1654
  */
1894
-
1895
-
1896
1655
  static createNoAuthCodeInResponseError() {
1897
1656
  return new NodeAuthError(NodeAuthErrorMessage.noAuthCodeInResponse.code, `${NodeAuthErrorMessage.noAuthCodeInResponse.desc}`);
1898
1657
  }
1899
1658
  /**
1900
1659
  * Creates an error thrown if the loopback server has not been spun up yet.
1901
1660
  */
1902
-
1903
-
1904
1661
  static createNoLoopbackServerExistsError() {
1905
1662
  return new NodeAuthError(NodeAuthErrorMessage.noLoopbackServerExists.code, `${NodeAuthErrorMessage.noLoopbackServerExists.desc}`);
1906
1663
  }
1907
1664
  /**
1908
1665
  * Creates an error thrown if a loopback server already exists when attempting to create another one.
1909
1666
  */
1910
-
1911
-
1912
1667
  static createLoopbackServerAlreadyExistsError() {
1913
1668
  return new NodeAuthError(NodeAuthErrorMessage.loopbackServerAlreadyExists.code, `${NodeAuthErrorMessage.loopbackServerAlreadyExists.desc}`);
1914
1669
  }
1915
1670
  /**
1916
1671
  * Creates an error thrown if the loopback server times out registering the auth code listener.
1917
1672
  */
1918
-
1919
-
1920
1673
  static createLoopbackServerTimeoutError() {
1921
1674
  return new NodeAuthError(NodeAuthErrorMessage.loopbackServerTimeout.code, `${NodeAuthErrorMessage.loopbackServerTimeout.desc}`);
1922
1675
  }
1923
1676
  /**
1924
1677
  * Creates an error thrown when the state is not present.
1925
1678
  */
1926
-
1927
-
1928
1679
  static createStateNotFoundError() {
1929
1680
  return new NodeAuthError(NodeAuthErrorMessage.stateNotFoundError.code, NodeAuthErrorMessage.stateNotFoundError.desc);
1930
1681
  }
1931
-
1932
1682
  }
1933
1683
 
1934
1684
  /*
@@ -1939,7 +1689,6 @@ class NodeAuthError extends msalCommon.AuthError {
1939
1689
  * Base abstract class for all ClientApplications - public and confidential
1940
1690
  * @public
1941
1691
  */
1942
-
1943
1692
  class ClientApplication {
1944
1693
  /**
1945
1694
  * Constructor for the ClientApplication
@@ -1960,11 +1709,10 @@ class ClientApplication {
1960
1709
  * sent in the request and should contain an authorization code, which can then be used to acquire tokens via
1961
1710
  * `acquireTokenByCode(AuthorizationCodeRequest)`.
1962
1711
  */
1963
-
1964
-
1965
1712
  async getAuthCodeUrl(request) {
1966
1713
  this.logger.info("getAuthCodeUrl called", request.correlationId);
1967
- const validRequest = { ...request,
1714
+ const validRequest = {
1715
+ ...request,
1968
1716
  ...(await this.initializeBaseRequest(request)),
1969
1717
  responseMode: request.responseMode || msalCommon.ResponseMode.QUERY,
1970
1718
  authenticationScheme: msalCommon.AuthenticationScheme.BEARER
@@ -1982,26 +1730,23 @@ class ClientApplication {
1982
1730
  * Authorization Code flow. Ensure that values for redirectUri and scopes in AuthorizationCodeUrlRequest and
1983
1731
  * AuthorizationCodeRequest are the same.
1984
1732
  */
1985
-
1986
-
1987
1733
  async acquireTokenByCode(request, authCodePayLoad) {
1988
1734
  this.logger.info("acquireTokenByCode called");
1989
-
1990
1735
  if (request.state && authCodePayLoad) {
1991
1736
  this.logger.info("acquireTokenByCode - validating state");
1992
- this.validateState(request.state, authCodePayLoad.state || ""); // eslint-disable-next-line no-param-reassign
1993
-
1994
- authCodePayLoad = { ...authCodePayLoad,
1737
+ this.validateState(request.state, authCodePayLoad.state || "");
1738
+ // eslint-disable-next-line no-param-reassign
1739
+ authCodePayLoad = {
1740
+ ...authCodePayLoad,
1995
1741
  state: ""
1996
1742
  };
1997
1743
  }
1998
-
1999
- const validRequest = { ...request,
1744
+ const validRequest = {
1745
+ ...request,
2000
1746
  ...(await this.initializeBaseRequest(request)),
2001
1747
  authenticationScheme: msalCommon.AuthenticationScheme.BEARER
2002
1748
  };
2003
1749
  const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByCode, validRequest.correlationId);
2004
-
2005
1750
  try {
2006
1751
  const authClientConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, serverTelemetryManager, undefined, request.azureCloudOptions);
2007
1752
  const authorizationCodeClient = new msalCommon.AuthorizationCodeClient(authClientConfig);
@@ -2011,7 +1756,6 @@ class ClientApplication {
2011
1756
  if (e instanceof msalCommon.AuthError) {
2012
1757
  e.setCorrelationId(validRequest.correlationId);
2013
1758
  }
2014
-
2015
1759
  serverTelemetryManager.cacheFailedRequest(e);
2016
1760
  throw e;
2017
1761
  }
@@ -2023,16 +1767,14 @@ class ClientApplication {
2023
1767
  * recommended that you use `acquireTokenSilent()` for silent scenarios. When using `acquireTokenSilent()`, MSAL will
2024
1768
  * handle the caching and refreshing of tokens automatically.
2025
1769
  */
2026
-
2027
-
2028
1770
  async acquireTokenByRefreshToken(request) {
2029
1771
  this.logger.info("acquireTokenByRefreshToken called", request.correlationId);
2030
- const validRequest = { ...request,
1772
+ const validRequest = {
1773
+ ...request,
2031
1774
  ...(await this.initializeBaseRequest(request)),
2032
1775
  authenticationScheme: msalCommon.AuthenticationScheme.BEARER
2033
1776
  };
2034
1777
  const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByRefreshToken, validRequest.correlationId);
2035
-
2036
1778
  try {
2037
1779
  const refreshTokenClientConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, serverTelemetryManager, undefined, request.azureCloudOptions);
2038
1780
  const refreshTokenClient = new msalCommon.RefreshTokenClient(refreshTokenClientConfig);
@@ -2042,7 +1784,6 @@ class ClientApplication {
2042
1784
  if (e instanceof msalCommon.AuthError) {
2043
1785
  e.setCorrelationId(validRequest.correlationId);
2044
1786
  }
2045
-
2046
1787
  serverTelemetryManager.cacheFailedRequest(e);
2047
1788
  throw e;
2048
1789
  }
@@ -2055,15 +1796,13 @@ class ClientApplication {
2055
1796
  * In case the refresh_token is expired or not found, an error is thrown
2056
1797
  * and the guidance is for the user to call any interactive token acquisition API (eg: `acquireTokenByCode()`).
2057
1798
  */
2058
-
2059
-
2060
1799
  async acquireTokenSilent(request) {
2061
- const validRequest = { ...request,
1800
+ const validRequest = {
1801
+ ...request,
2062
1802
  ...(await this.initializeBaseRequest(request)),
2063
1803
  forceRefresh: request.forceRefresh || false
2064
1804
  };
2065
1805
  const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenSilent, validRequest.correlationId, validRequest.forceRefresh);
2066
-
2067
1806
  try {
2068
1807
  const silentFlowClientConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, serverTelemetryManager, undefined, request.azureCloudOptions);
2069
1808
  const silentFlowClient = new msalCommon.SilentFlowClient(silentFlowClientConfig);
@@ -2073,7 +1812,6 @@ class ClientApplication {
2073
1812
  if (e instanceof msalCommon.AuthError) {
2074
1813
  e.setCorrelationId(validRequest.correlationId);
2075
1814
  }
2076
-
2077
1815
  serverTelemetryManager.cacheFailedRequest(e);
2078
1816
  throw e;
2079
1817
  }
@@ -2088,15 +1826,13 @@ class ClientApplication {
2088
1826
  *
2089
1827
  * @param request - UsenamePasswordRequest
2090
1828
  */
2091
-
2092
-
2093
1829
  async acquireTokenByUsernamePassword(request) {
2094
1830
  this.logger.info("acquireTokenByUsernamePassword called", request.correlationId);
2095
- const validRequest = { ...request,
1831
+ const validRequest = {
1832
+ ...request,
2096
1833
  ...(await this.initializeBaseRequest(request))
2097
1834
  };
2098
1835
  const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByUsernamePassword, validRequest.correlationId);
2099
-
2100
1836
  try {
2101
1837
  const usernamePasswordClientConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, serverTelemetryManager, undefined, request.azureCloudOptions);
2102
1838
  const usernamePasswordClient = new msalCommon.UsernamePasswordClient(usernamePasswordClientConfig);
@@ -2106,7 +1842,6 @@ class ClientApplication {
2106
1842
  if (e instanceof msalCommon.AuthError) {
2107
1843
  e.setCorrelationId(validRequest.correlationId);
2108
1844
  }
2109
-
2110
1845
  serverTelemetryManager.cacheFailedRequest(e);
2111
1846
  throw e;
2112
1847
  }
@@ -2114,8 +1849,6 @@ class ClientApplication {
2114
1849
  /**
2115
1850
  * Gets the token cache for the application.
2116
1851
  */
2117
-
2118
-
2119
1852
  getTokenCache() {
2120
1853
  this.logger.info("getTokenCache called");
2121
1854
  return this.tokenCache;
@@ -2129,13 +1862,10 @@ class ClientApplication {
2129
1862
  * @param state
2130
1863
  * @param cachedState
2131
1864
  */
2132
-
2133
-
2134
1865
  validateState(state, cachedState) {
2135
1866
  if (!state) {
2136
1867
  throw NodeAuthError.createStateNotFoundError();
2137
1868
  }
2138
-
2139
1869
  if (state !== cachedState) {
2140
1870
  throw msalCommon.ClientAuthError.createStateMismatchError();
2141
1871
  }
@@ -2143,8 +1873,6 @@ class ClientApplication {
2143
1873
  /**
2144
1874
  * Returns the logger instance
2145
1875
  */
2146
-
2147
-
2148
1876
  getLogger() {
2149
1877
  return this.logger;
2150
1878
  }
@@ -2152,8 +1880,6 @@ class ClientApplication {
2152
1880
  * Replaces the default logger set in configurations with new Logger with new configurations
2153
1881
  * @param logger - Logger instance
2154
1882
  */
2155
-
2156
-
2157
1883
  setLogger(logger) {
2158
1884
  this.logger = logger;
2159
1885
  }
@@ -2162,13 +1888,11 @@ class ClientApplication {
2162
1888
  * @param authority - user passed authority in configuration
2163
1889
  * @param serverTelemetryManager - initializes servertelemetry if passed
2164
1890
  */
2165
-
2166
-
2167
1891
  async buildOauthClientConfiguration(authority, requestCorrelationId, serverTelemetryManager, azureRegionConfiguration, azureCloudOptions) {
2168
- this.logger.verbose("buildOauthClientConfiguration called", requestCorrelationId); // precedence - azureCloudInstance + tenant >> authority and request >> config
2169
-
2170
- const userAzureCloudOptions = azureCloudOptions ? azureCloudOptions : this.config.auth.azureCloudOptions; // using null assertion operator as we ensure that all config values have default values in buildConfiguration()
2171
-
1892
+ this.logger.verbose("buildOauthClientConfiguration called", requestCorrelationId);
1893
+ // precedence - azureCloudInstance + tenant >> authority and request >> config
1894
+ const userAzureCloudOptions = azureCloudOptions ? azureCloudOptions : this.config.auth.azureCloudOptions;
1895
+ // using null assertion operator as we ensure that all config values have default values in buildConfiguration()
2172
1896
  this.logger.verbose(`building oauth client configuration with the authority: ${authority}`, requestCorrelationId);
2173
1897
  const discoveredAuthority = await this.createAuthority(authority, azureRegionConfiguration, requestCorrelationId, userAzureCloudOptions);
2174
1898
  serverTelemetryManager == null ? void 0 : serverTelemetryManager.updateRegionDiscoveryMetadata(discoveredAuthority.regionDiscoveryMetadata);
@@ -2178,9 +1902,6 @@ class ClientApplication {
2178
1902
  authority: discoveredAuthority,
2179
1903
  clientCapabilities: this.config.auth.clientCapabilities
2180
1904
  },
2181
- systemOptions: {
2182
- proxyUrl: this.config.system.proxyUrl
2183
- },
2184
1905
  loggerOptions: {
2185
1906
  logLevel: this.config.system.loggerOptions.logLevel,
2186
1907
  loggerCallback: this.config.system.loggerOptions.loggerCallback,
@@ -2207,7 +1928,6 @@ class ClientApplication {
2207
1928
  };
2208
1929
  return clientConfiguration;
2209
1930
  }
2210
-
2211
1931
  getClientAssertion(authority) {
2212
1932
  return {
2213
1933
  assertion: this.clientAssertion.getJwt(this.cryptoProvider, this.config.auth.clientId, authority.tokenEndpoint),
@@ -2218,22 +1938,19 @@ class ClientApplication {
2218
1938
  * Generates a request with the default scopes & generates a correlationId.
2219
1939
  * @param authRequest - BaseAuthRequest for initialization
2220
1940
  */
2221
-
2222
-
2223
1941
  async initializeBaseRequest(authRequest) {
2224
- this.logger.verbose("initializeRequestScopes called", authRequest.correlationId); // Default authenticationScheme to Bearer, log that POP isn't supported yet
2225
-
1942
+ this.logger.verbose("initializeRequestScopes called", authRequest.correlationId);
1943
+ // Default authenticationScheme to Bearer, log that POP isn't supported yet
2226
1944
  if (authRequest.authenticationScheme && authRequest.authenticationScheme === msalCommon.AuthenticationScheme.POP) {
2227
1945
  this.logger.verbose("Authentication Scheme 'pop' is not supported yet, setting Authentication Scheme to 'Bearer' for request", authRequest.correlationId);
2228
1946
  }
2229
-
2230
- authRequest.authenticationScheme = msalCommon.AuthenticationScheme.BEARER; // Set requested claims hash if claims were requested
2231
-
1947
+ authRequest.authenticationScheme = msalCommon.AuthenticationScheme.BEARER;
1948
+ // Set requested claims hash if claims were requested
2232
1949
  if (authRequest.claims && !msalCommon.StringUtils.isEmpty(authRequest.claims)) {
2233
1950
  authRequest.requestedClaimsHash = await this.cryptoProvider.hashString(authRequest.claims);
2234
1951
  }
2235
-
2236
- return { ...authRequest,
1952
+ return {
1953
+ ...authRequest,
2237
1954
  scopes: [...(authRequest && authRequest.scopes || []), ...msalCommon.OIDC_DEFAULT_SCOPES],
2238
1955
  correlationId: authRequest && authRequest.correlationId || this.cryptoProvider.createNewGuid(),
2239
1956
  authority: authRequest.authority || this.config.auth.authority
@@ -2245,8 +1962,6 @@ class ClientApplication {
2245
1962
  * @param correlationId - GUID
2246
1963
  * @param forceRefresh - boolean to indicate network call
2247
1964
  */
2248
-
2249
-
2250
1965
  initializeServerTelemetryManager(apiId, correlationId, forceRefresh) {
2251
1966
  const telemetryPayload = {
2252
1967
  clientId: this.config.auth.clientId,
@@ -2261,11 +1976,9 @@ class ClientApplication {
2261
1976
  * object. If no authority set in application object, then default to common authority.
2262
1977
  * @param authorityString - authority from user configuration
2263
1978
  */
2264
-
2265
-
2266
1979
  async createAuthority(authorityString, azureRegionConfiguration, requestCorrelationId, azureCloudOptions) {
2267
- this.logger.verbose("createAuthority called", requestCorrelationId); // build authority string based on auth params - azureCloudInstance is prioritized if provided
2268
-
1980
+ this.logger.verbose("createAuthority called", requestCorrelationId);
1981
+ // build authority string based on auth params - azureCloudInstance is prioritized if provided
2269
1982
  const authorityUrl = msalCommon.Authority.generateAuthority(authorityString, azureCloudOptions);
2270
1983
  const authorityOptions = {
2271
1984
  protocolMode: this.config.auth.protocolMode,
@@ -2275,17 +1988,14 @@ class ClientApplication {
2275
1988
  azureRegionConfiguration,
2276
1989
  skipAuthorityMetadataCache: this.config.auth.skipAuthorityMetadataCache
2277
1990
  };
2278
- return await msalCommon.AuthorityFactory.createDiscoveredInstance(authorityUrl, this.config.system.networkClient, this.storage, authorityOptions, this.logger, this.config.system.proxyUrl);
1991
+ return await msalCommon.AuthorityFactory.createDiscoveredInstance(authorityUrl, this.config.system.networkClient, this.storage, authorityOptions, this.logger);
2279
1992
  }
2280
1993
  /**
2281
1994
  * Clear the cache
2282
1995
  */
2283
-
2284
-
2285
1996
  clearCache() {
2286
1997
  this.storage.clear();
2287
1998
  }
2288
-
2289
1999
  }
2290
2000
 
2291
2001
  /*
@@ -2303,11 +2013,9 @@ class LoopbackClient {
2303
2013
  if (!!this.server) {
2304
2014
  throw NodeAuthError.createLoopbackServerAlreadyExistsError();
2305
2015
  }
2306
-
2307
2016
  const authCodeListener = new Promise((resolve, reject) => {
2308
2017
  this.server = http.createServer(async (req, res) => {
2309
2018
  const url = req.url;
2310
-
2311
2019
  if (!url) {
2312
2020
  res.end(errorTemplate || "Error occurred loading redirectUrl");
2313
2021
  reject(NodeAuthError.createUnableToLoadRedirectUrlError());
@@ -2316,35 +2024,29 @@ class LoopbackClient {
2316
2024
  res.end(successTemplate || "Auth code was successfully acquired. You can close this window now.");
2317
2025
  return;
2318
2026
  }
2319
-
2320
2027
  const authCodeResponse = msalCommon.UrlString.getDeserializedQueryString(url);
2321
-
2322
2028
  if (authCodeResponse.code) {
2323
2029
  const redirectUri = await this.getRedirectUri();
2324
2030
  res.writeHead(HttpStatus.REDIRECT, {
2325
2031
  location: redirectUri
2326
2032
  }); // Prevent auth code from being saved in the browser history
2327
-
2328
2033
  res.end();
2329
2034
  }
2330
-
2331
2035
  resolve(authCodeResponse);
2332
2036
  });
2333
2037
  this.server.listen(0); // Listen on any available port
2334
- }); // Wait for server to be listening
2335
-
2038
+ });
2039
+ // Wait for server to be listening
2336
2040
  await new Promise(resolve => {
2337
2041
  let ticks = 0;
2338
2042
  const id = setInterval(() => {
2339
2043
  if (LOOPBACK_SERVER_CONSTANTS.TIMEOUT_MS / LOOPBACK_SERVER_CONSTANTS.INTERVAL_MS < ticks) {
2340
2044
  throw NodeAuthError.createLoopbackServerTimeoutError();
2341
2045
  }
2342
-
2343
2046
  if (this.server.listening) {
2344
2047
  clearInterval(id);
2345
2048
  resolve();
2346
2049
  }
2347
-
2348
2050
  ticks++;
2349
2051
  }, LOOPBACK_SERVER_CONSTANTS.INTERVAL_MS);
2350
2052
  });
@@ -2354,34 +2056,26 @@ class LoopbackClient {
2354
2056
  * Get the port that the loopback server is running on
2355
2057
  * @returns
2356
2058
  */
2357
-
2358
-
2359
2059
  getRedirectUri() {
2360
2060
  if (!this.server) {
2361
2061
  throw NodeAuthError.createNoLoopbackServerExistsError();
2362
2062
  }
2363
-
2364
2063
  const address = this.server.address();
2365
-
2366
2064
  if (!address || typeof address === "string" || !address.port) {
2367
2065
  this.closeServer();
2368
2066
  throw NodeAuthError.createInvalidLoopbackAddressTypeError();
2369
2067
  }
2370
-
2371
2068
  const port = address && address.port;
2372
2069
  return `${Constants.HTTP_PROTOCOL}${Constants.LOCALHOST}:${port}`;
2373
2070
  }
2374
2071
  /**
2375
2072
  * Close the loopback server
2376
2073
  */
2377
-
2378
-
2379
2074
  closeServer() {
2380
2075
  if (!!this.server) {
2381
2076
  this.server.close();
2382
2077
  }
2383
2078
  }
2384
-
2385
2079
  }
2386
2080
 
2387
2081
  /*
@@ -2393,7 +2087,6 @@ class LoopbackClient {
2393
2087
  * are not trusted to safely store application secrets, and therefore can only request tokens in the name of an user.
2394
2088
  * @public
2395
2089
  */
2396
-
2397
2090
  class PublicClientApplication extends ClientApplication {
2398
2091
  /**
2399
2092
  * Important attributes in the Configuration object for auth are:
@@ -2424,13 +2117,10 @@ class PublicClientApplication extends ClientApplication {
2424
2117
  * Since the client cannot receive incoming requests, it polls the authorization server repeatedly
2425
2118
  * until the end-user completes input of credentials.
2426
2119
  */
2427
-
2428
-
2429
2120
  async acquireTokenByDeviceCode(request) {
2430
2121
  this.logger.info("acquireTokenByDeviceCode called", request.correlationId);
2431
2122
  const validRequest = Object.assign(request, await this.initializeBaseRequest(request));
2432
2123
  const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByDeviceCode, validRequest.correlationId);
2433
-
2434
2124
  try {
2435
2125
  const deviceCodeConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, serverTelemetryManager, undefined, request.azureCloudOptions);
2436
2126
  const deviceCodeClient = new msalCommon.DeviceCodeClient(deviceCodeConfig);
@@ -2440,7 +2130,6 @@ class PublicClientApplication extends ClientApplication {
2440
2130
  if (e instanceof msalCommon.AuthError) {
2441
2131
  e.setCorrelationId(validRequest.correlationId);
2442
2132
  }
2443
-
2444
2133
  serverTelemetryManager.cacheFailedRequest(e);
2445
2134
  throw e;
2446
2135
  }
@@ -2448,8 +2137,6 @@ class PublicClientApplication extends ClientApplication {
2448
2137
  /**
2449
2138
  * Acquires a token by requesting an Authorization code then exchanging it for a token.
2450
2139
  */
2451
-
2452
-
2453
2140
  async acquireTokenInteractive(request) {
2454
2141
  const {
2455
2142
  verifier,
@@ -2464,7 +2151,8 @@ class PublicClientApplication extends ClientApplication {
2464
2151
  const loopbackClient = new LoopbackClient();
2465
2152
  const authCodeListener = loopbackClient.listenForAuthCode(successTemplate, errorTemplate);
2466
2153
  const redirectUri = loopbackClient.getRedirectUri();
2467
- const validRequest = { ...remainingProperties,
2154
+ const validRequest = {
2155
+ ...remainingProperties,
2468
2156
  scopes: request.scopes || msalCommon.OIDC_DEFAULT_SCOPES,
2469
2157
  redirectUri: redirectUri,
2470
2158
  responseMode: msalCommon.ResponseMode.QUERY,
@@ -2476,13 +2164,11 @@ class PublicClientApplication extends ClientApplication {
2476
2164
  const authCodeResponse = await authCodeListener.finally(() => {
2477
2165
  loopbackClient.closeServer();
2478
2166
  });
2479
-
2480
2167
  if (authCodeResponse.error) {
2481
2168
  throw new msalCommon.ServerError(authCodeResponse.error, authCodeResponse.error_description, authCodeResponse.suberror);
2482
2169
  } else if (!authCodeResponse.code) {
2483
2170
  throw NodeAuthError.createNoAuthCodeInResponseError();
2484
2171
  }
2485
-
2486
2172
  const clientInfo = authCodeResponse.client_info;
2487
2173
  const tokenRequest = {
2488
2174
  code: authCodeResponse.code,
@@ -2492,7 +2178,6 @@ class PublicClientApplication extends ClientApplication {
2492
2178
  };
2493
2179
  return this.acquireTokenByCode(tokenRequest);
2494
2180
  }
2495
-
2496
2181
  }
2497
2182
 
2498
2183
  /*
@@ -2503,7 +2188,6 @@ class PublicClientApplication extends ClientApplication {
2503
2188
  * Client assertion of type jwt-bearer used in confidential client flows
2504
2189
  * @public
2505
2190
  */
2506
-
2507
2191
  class ClientAssertion {
2508
2192
  /**
2509
2193
  * Initialize the ClientAssertion class from the clientAssertion passed by the user
@@ -2520,17 +2204,13 @@ class ClientAssertion {
2520
2204
  * @param privateKey - secret key
2521
2205
  * @param publicCertificate - electronic document provided to prove the ownership of the public key
2522
2206
  */
2523
-
2524
-
2525
2207
  static fromCertificate(thumbprint, privateKey, publicCertificate) {
2526
2208
  const clientAssertion = new ClientAssertion();
2527
2209
  clientAssertion.privateKey = privateKey;
2528
2210
  clientAssertion.thumbprint = thumbprint;
2529
-
2530
2211
  if (publicCertificate) {
2531
2212
  clientAssertion.publicCertificate = this.parseCertificate(publicCertificate);
2532
2213
  }
2533
-
2534
2214
  return clientAssertion;
2535
2215
  }
2536
2216
  /**
@@ -2539,34 +2219,26 @@ class ClientAssertion {
2539
2219
  * @param issuer - iss claim
2540
2220
  * @param jwtAudience - aud claim
2541
2221
  */
2542
-
2543
-
2544
2222
  getJwt(cryptoProvider, issuer, jwtAudience) {
2545
2223
  // if assertion was created from certificate, check if jwt is expired and create new one.
2546
2224
  if (this.privateKey && this.thumbprint) {
2547
2225
  if (this.jwt && !this.isExpired() && issuer === this.issuer && jwtAudience === this.jwtAudience) {
2548
2226
  return this.jwt;
2549
2227
  }
2550
-
2551
2228
  return this.createJwt(cryptoProvider, issuer, jwtAudience);
2552
2229
  }
2553
2230
  /*
2554
2231
  * if assertion was created by caller, then we just append it. It is up to the caller to
2555
2232
  * ensure that it contains necessary claims and that it is not expired.
2556
2233
  */
2557
-
2558
-
2559
2234
  if (this.jwt) {
2560
2235
  return this.jwt;
2561
2236
  }
2562
-
2563
2237
  throw msalCommon.ClientAuthError.createInvalidAssertionError();
2564
2238
  }
2565
2239
  /**
2566
2240
  * JWT format and required claims specified: https://tools.ietf.org/html/rfc7523#section-3
2567
2241
  */
2568
-
2569
-
2570
2242
  createJwt(cryptoProvider, issuer, jwtAudience) {
2571
2243
  this.issuer = issuer;
2572
2244
  this.jwtAudience = jwtAudience;
@@ -2576,13 +2248,11 @@ class ClientAssertion {
2576
2248
  alg: JwtConstants.RSA_256,
2577
2249
  x5t: EncodingUtils.base64EncodeUrl(this.thumbprint, "hex")
2578
2250
  };
2579
-
2580
2251
  if (this.publicCertificate) {
2581
2252
  Object.assign(header, {
2582
2253
  x5c: this.publicCertificate
2583
2254
  });
2584
2255
  }
2585
-
2586
2256
  const payload = {
2587
2257
  [JwtConstants.AUDIENCE]: this.jwtAudience,
2588
2258
  [JwtConstants.EXPIRATION_TIME]: this.expirationTime,
@@ -2599,8 +2269,6 @@ class ClientAssertion {
2599
2269
  /**
2600
2270
  * Utility API to check expiration
2601
2271
  */
2602
-
2603
-
2604
2272
  isExpired() {
2605
2273
  return this.expirationTime < msalCommon.TimeUtils.nowSeconds();
2606
2274
  }
@@ -2608,8 +2276,6 @@ class ClientAssertion {
2608
2276
  * Extracts the raw certs from a given certificate string and returns them in an array.
2609
2277
  * @param publicCertificate - electronic document provided to prove the ownership of the public key
2610
2278
  */
2611
-
2612
-
2613
2279
  static parseCertificate(publicCertificate) {
2614
2280
  /**
2615
2281
  * This is regex to identify the certs in a given certificate string.
@@ -2621,15 +2287,12 @@ class ClientAssertion {
2621
2287
  const regexToFindCerts = /-----BEGIN CERTIFICATE-----\r*\n(.+?)\r*\n-----END CERTIFICATE-----/gs;
2622
2288
  const certs = [];
2623
2289
  let matches;
2624
-
2625
2290
  while ((matches = regexToFindCerts.exec(publicCertificate)) !== null) {
2626
2291
  // matches[1] represents the first parens capture group in the regex.
2627
2292
  certs.push(matches[1].replace(/\r*\n/g, msalCommon.Constants.EMPTY_STRING));
2628
2293
  }
2629
-
2630
2294
  return certs;
2631
2295
  }
2632
-
2633
2296
  }
2634
2297
 
2635
2298
  /*
@@ -2641,7 +2304,6 @@ class ClientAssertion {
2641
2304
  * will configure application secrets, client certificates/assertions as applicable
2642
2305
  * @public
2643
2306
  */
2644
-
2645
2307
  class ConfidentialClientApplication extends ClientApplication {
2646
2308
  /**
2647
2309
  * Constructor for the ConfidentialClientApplication
@@ -2673,34 +2335,30 @@ class ConfidentialClientApplication extends ClientApplication {
2673
2335
  *
2674
2336
  * @param IAppTokenProvider - Extensibility interface, which allows the app developer to return a token from a custom source.
2675
2337
  */
2676
-
2677
-
2678
2338
  SetAppTokenProvider(provider) {
2679
2339
  this.appTokenProvider = provider;
2680
2340
  }
2681
2341
  /**
2682
2342
  * Acquires tokens from the authority for the application (not for an end user).
2683
2343
  */
2684
-
2685
-
2686
2344
  async acquireTokenByClientCredential(request) {
2687
- 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
2688
-
2345
+ this.logger.info("acquireTokenByClientCredential called", request.correlationId);
2346
+ // If there is a client assertion present in the request, it overrides the one present in the client configuration
2689
2347
  let clientAssertion;
2690
-
2691
2348
  if (request.clientAssertion) {
2692
2349
  clientAssertion = {
2693
2350
  assertion: request.clientAssertion,
2694
2351
  assertionType: Constants.JWT_BEARER_ASSERTION_TYPE
2695
2352
  };
2696
2353
  }
2697
-
2698
- const baseRequest = await this.initializeBaseRequest(request); // valid base request should not contain oidc scopes in this grant type
2699
-
2700
- const validBaseRequest = { ...baseRequest,
2354
+ const baseRequest = await this.initializeBaseRequest(request);
2355
+ // valid base request should not contain oidc scopes in this grant type
2356
+ const validBaseRequest = {
2357
+ ...baseRequest,
2701
2358
  scopes: baseRequest.scopes.filter(scope => !msalCommon.OIDC_DEFAULT_SCOPES.includes(scope))
2702
2359
  };
2703
- const validRequest = { ...request,
2360
+ const validRequest = {
2361
+ ...request,
2704
2362
  ...validBaseRequest,
2705
2363
  clientAssertion
2706
2364
  };
@@ -2709,7 +2367,6 @@ class ConfidentialClientApplication extends ClientApplication {
2709
2367
  environmentRegion: process.env[REGION_ENVIRONMENT_VARIABLE]
2710
2368
  };
2711
2369
  const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByClientCredential, validRequest.correlationId, validRequest.skipCache);
2712
-
2713
2370
  try {
2714
2371
  const clientCredentialConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, serverTelemetryManager, azureRegionConfiguration, request.azureCloudOptions);
2715
2372
  const clientCredentialClient = new msalCommon.ClientCredentialClient(clientCredentialConfig, this.appTokenProvider);
@@ -2719,7 +2376,6 @@ class ConfidentialClientApplication extends ClientApplication {
2719
2376
  if (e instanceof msalCommon.AuthError) {
2720
2377
  e.setCorrelationId(validRequest.correlationId);
2721
2378
  }
2722
-
2723
2379
  serverTelemetryManager.cacheFailedRequest(e);
2724
2380
  throw e;
2725
2381
  }
@@ -2735,14 +2391,12 @@ class ConfidentialClientApplication extends ClientApplication {
2735
2391
  * See how to gain consent upfront for your middle-tier app from this article.
2736
2392
  * https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow#gaining-consent-for-the-middle-tier-application
2737
2393
  */
2738
-
2739
-
2740
2394
  async acquireTokenOnBehalfOf(request) {
2741
2395
  this.logger.info("acquireTokenOnBehalfOf called", request.correlationId);
2742
- const validRequest = { ...request,
2396
+ const validRequest = {
2397
+ ...request,
2743
2398
  ...(await this.initializeBaseRequest(request))
2744
2399
  };
2745
-
2746
2400
  try {
2747
2401
  const onBehalfOfConfig = await this.buildOauthClientConfiguration(validRequest.authority, validRequest.correlationId, undefined, undefined, request.azureCloudOptions);
2748
2402
  const oboClient = new msalCommon.OnBehalfOfClient(onBehalfOfConfig);
@@ -2752,11 +2406,9 @@ class ConfidentialClientApplication extends ClientApplication {
2752
2406
  if (e instanceof msalCommon.AuthError) {
2753
2407
  e.setCorrelationId(validRequest.correlationId);
2754
2408
  }
2755
-
2756
2409
  throw e;
2757
2410
  }
2758
2411
  }
2759
-
2760
2412
  setClientCredential(configuration) {
2761
2413
  const clientSecretNotEmpty = !msalCommon.StringUtils.isEmpty(configuration.auth.clientSecret);
2762
2414
  const clientAssertionNotEmpty = !msalCommon.StringUtils.isEmpty(configuration.auth.clientAssertion);
@@ -2769,35 +2421,28 @@ class ConfidentialClientApplication extends ClientApplication {
2769
2421
  * If app developer configures this callback, they don't need a credential
2770
2422
  * i.e. AzureSDK can get token from Managed Identity without a cert / secret
2771
2423
  */
2772
-
2773
2424
  if (this.appTokenProvider) {
2774
2425
  return;
2775
- } // Check that at most one credential is set on the application
2776
-
2777
-
2426
+ }
2427
+ // Check that at most one credential is set on the application
2778
2428
  if (clientSecretNotEmpty && clientAssertionNotEmpty || clientAssertionNotEmpty && certificateNotEmpty || clientSecretNotEmpty && certificateNotEmpty) {
2779
2429
  throw msalCommon.ClientAuthError.createInvalidCredentialError();
2780
2430
  }
2781
-
2782
2431
  if (configuration.auth.clientSecret) {
2783
2432
  this.clientSecret = configuration.auth.clientSecret;
2784
2433
  return;
2785
2434
  }
2786
-
2787
2435
  if (configuration.auth.clientAssertion) {
2788
2436
  this.clientAssertion = ClientAssertion.fromAssertion(configuration.auth.clientAssertion);
2789
2437
  return;
2790
2438
  }
2791
-
2792
2439
  if (!certificateNotEmpty) {
2793
2440
  throw msalCommon.ClientAuthError.createInvalidCredentialError();
2794
2441
  } else {
2795
2442
  var _configuration$auth$c;
2796
-
2797
2443
  this.clientAssertion = ClientAssertion.fromCertificate(certificate.thumbprint, certificate.privateKey, (_configuration$auth$c = configuration.auth.clientCertificate) == null ? void 0 : _configuration$auth$c.x5c);
2798
2444
  }
2799
2445
  }
2800
-
2801
2446
  }
2802
2447
 
2803
2448
  /*
@@ -2809,18 +2454,15 @@ class DistributedCachePlugin {
2809
2454
  this.client = client;
2810
2455
  this.partitionManager = partitionManager;
2811
2456
  }
2812
-
2813
2457
  async beforeCacheAccess(cacheContext) {
2814
2458
  const partitionKey = await this.partitionManager.getKey();
2815
2459
  const cacheData = await this.client.get(partitionKey);
2816
2460
  cacheContext.tokenCache.deserialize(cacheData);
2817
2461
  }
2818
-
2819
2462
  async afterCacheAccess(cacheContext) {
2820
2463
  if (cacheContext.cacheHasChanged) {
2821
2464
  const kvStore = cacheContext.tokenCache.getKVStore();
2822
2465
  const accountEntities = Object.values(kvStore).filter(value => msalCommon.AccountEntity.isAccountEntity(value));
2823
-
2824
2466
  if (accountEntities.length > 0) {
2825
2467
  const accountEntity = accountEntities[0];
2826
2468
  const partitionKey = await this.partitionManager.extractKey(accountEntity);
@@ -2828,7 +2470,6 @@ class DistributedCachePlugin {
2828
2470
  }
2829
2471
  }
2830
2472
  }
2831
-
2832
2473
  }
2833
2474
 
2834
2475
  Object.defineProperty(exports, 'AuthError', {