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