@azure/msal-node-extensions 1.0.0-alpha.3 → 1.0.0-alpha.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +156 -5
  2. package/binding.gyp +11 -1
  3. package/dist/{dpapi-addon/Dpapi.d.ts → Dpapi.d.ts} +0 -0
  4. package/dist/error/PersistenceError.d.ts +28 -0
  5. package/dist/index.d.ts +3 -0
  6. package/dist/msal-node-extensions.cjs.development.js +603 -859
  7. package/dist/msal-node-extensions.cjs.development.js.map +1 -1
  8. package/dist/msal-node-extensions.cjs.production.min.js +1 -1
  9. package/dist/msal-node-extensions.cjs.production.min.js.map +1 -1
  10. package/dist/msal-node-extensions.esm.js +613 -874
  11. package/dist/msal-node-extensions.esm.js.map +1 -1
  12. package/dist/packageMetadata.d.ts +2 -0
  13. package/dist/persistence/BasePersistence.d.ts +5 -0
  14. package/dist/persistence/FilePersistence.d.ts +4 -2
  15. package/dist/persistence/FilePersistenceWithDataProtection.d.ts +3 -1
  16. package/dist/persistence/IPersistence.d.ts +3 -1
  17. package/dist/persistence/IPersistenceConfiguration.d.ts +10 -0
  18. package/dist/persistence/KeychainPersistence.d.ts +3 -1
  19. package/dist/persistence/LibSecretPersistence.d.ts +3 -1
  20. package/dist/persistence/PersistenceCachePlugin.d.ts +11 -7
  21. package/dist/persistence/PersistenceCreator.d.ts +5 -0
  22. package/dist/utils/Constants.d.ts +26 -0
  23. package/dist/utils/Environment.d.ts +16 -0
  24. package/package.json +27 -15
  25. package/src/{dpapi-addon/Dpapi.ts → Dpapi.ts} +12 -12
  26. package/src/dpapi-addon/dpapi_addon.h +2 -1
  27. package/src/dpapi-addon/dpapi_not_supported.cpp +4 -10
  28. package/src/dpapi-addon/dpapi_win.cpp +25 -33
  29. package/src/dpapi-addon/main.cpp +14 -16
  30. package/src/error/PersistenceError.ts +101 -61
  31. package/src/index.ts +16 -8
  32. package/src/lock/CrossPlatformLock.ts +89 -89
  33. package/src/lock/CrossPlatformLockOptions.ts +15 -15
  34. package/src/packageMetadata.ts +3 -0
  35. package/src/persistence/BasePersistence.ts +43 -0
  36. package/src/persistence/FilePersistence.ts +140 -134
  37. package/src/persistence/FilePersistenceWithDataProtection.ts +92 -84
  38. package/src/persistence/IPersistence.ts +4 -2
  39. package/src/persistence/IPersistenceConfiguration.ts +17 -0
  40. package/src/persistence/KeychainPersistence.ts +89 -78
  41. package/src/persistence/LibSecretPersistence.ts +90 -79
  42. package/src/persistence/PersistenceCachePlugin.ts +40 -30
  43. package/src/persistence/PersistenceCreator.ts +78 -0
  44. package/src/utils/Constants.ts +62 -30
  45. package/src/utils/Environment.ts +101 -0
  46. package/CHANGELOG.json +0 -50
  47. package/changelog.md +0 -28
@@ -2,203 +2,20 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
+ function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
6
+
5
7
  var fs = require('fs');
6
- var process = require('process');
8
+ var process$1 = require('process');
7
9
  var path = require('path');
10
+ var path__default = _interopDefault(path);
8
11
  var msalCommon = require('@azure/msal-common');
9
12
  var keytar = require('keytar');
10
13
 
11
- // A type of promise-like that resolves synchronously and supports only one observer
12
- const _Pact = /*#__PURE__*/(function() {
13
- function _Pact() {}
14
- _Pact.prototype.then = function(onFulfilled, onRejected) {
15
- const result = new _Pact();
16
- const state = this.s;
17
- if (state) {
18
- const callback = state & 1 ? onFulfilled : onRejected;
19
- if (callback) {
20
- try {
21
- _settle(result, 1, callback(this.v));
22
- } catch (e) {
23
- _settle(result, 2, e);
24
- }
25
- return result;
26
- } else {
27
- return this;
28
- }
29
- }
30
- this.o = function(_this) {
31
- try {
32
- const value = _this.v;
33
- if (_this.s & 1) {
34
- _settle(result, 1, onFulfilled ? onFulfilled(value) : value);
35
- } else if (onRejected) {
36
- _settle(result, 1, onRejected(value));
37
- } else {
38
- _settle(result, 2, value);
39
- }
40
- } catch (e) {
41
- _settle(result, 2, e);
42
- }
43
- };
44
- return result;
45
- };
46
- return _Pact;
47
- })();
48
-
49
- // Settles a pact synchronously
50
- function _settle(pact, state, value) {
51
- if (!pact.s) {
52
- if (value instanceof _Pact) {
53
- if (value.s) {
54
- if (state & 1) {
55
- state = value.s;
56
- }
57
- value = value.v;
58
- } else {
59
- value.o = _settle.bind(null, pact, state);
60
- return;
61
- }
62
- }
63
- if (value && value.then) {
64
- value.then(_settle.bind(null, pact, state), _settle.bind(null, pact, 2));
65
- return;
66
- }
67
- pact.s = state;
68
- pact.v = value;
69
- const observer = pact.o;
70
- if (observer) {
71
- observer(pact);
72
- }
73
- }
74
- }
75
-
76
- function _isSettledPact(thenable) {
77
- return thenable instanceof _Pact && thenable.s & 1;
78
- }
79
-
80
- const _iteratorSymbol = /*#__PURE__*/ typeof Symbol !== "undefined" ? (Symbol.iterator || (Symbol.iterator = Symbol("Symbol.iterator"))) : "@@iterator";
81
-
82
- const _asyncIteratorSymbol = /*#__PURE__*/ typeof Symbol !== "undefined" ? (Symbol.asyncIterator || (Symbol.asyncIterator = Symbol("Symbol.asyncIterator"))) : "@@asyncIterator";
83
-
84
- // Asynchronously implement a generic for loop
85
- function _for(test, update, body) {
86
- var stage;
87
- for (;;) {
88
- var shouldContinue = test();
89
- if (_isSettledPact(shouldContinue)) {
90
- shouldContinue = shouldContinue.v;
91
- }
92
- if (!shouldContinue) {
93
- return result;
94
- }
95
- if (shouldContinue.then) {
96
- stage = 0;
97
- break;
98
- }
99
- var result = body();
100
- if (result && result.then) {
101
- if (_isSettledPact(result)) {
102
- result = result.s;
103
- } else {
104
- stage = 1;
105
- break;
106
- }
107
- }
108
- if (update) {
109
- var updateValue = update();
110
- if (updateValue && updateValue.then && !_isSettledPact(updateValue)) {
111
- stage = 2;
112
- break;
113
- }
114
- }
115
- }
116
- var pact = new _Pact();
117
- var reject = _settle.bind(null, pact, 2);
118
- (stage === 0 ? shouldContinue.then(_resumeAfterTest) : stage === 1 ? result.then(_resumeAfterBody) : updateValue.then(_resumeAfterUpdate)).then(void 0, reject);
119
- return pact;
120
- function _resumeAfterBody(value) {
121
- result = value;
122
- do {
123
- if (update) {
124
- updateValue = update();
125
- if (updateValue && updateValue.then && !_isSettledPact(updateValue)) {
126
- updateValue.then(_resumeAfterUpdate).then(void 0, reject);
127
- return;
128
- }
129
- }
130
- shouldContinue = test();
131
- if (!shouldContinue || (_isSettledPact(shouldContinue) && !shouldContinue.v)) {
132
- _settle(pact, 1, result);
133
- return;
134
- }
135
- if (shouldContinue.then) {
136
- shouldContinue.then(_resumeAfterTest).then(void 0, reject);
137
- return;
138
- }
139
- result = body();
140
- if (_isSettledPact(result)) {
141
- result = result.v;
142
- }
143
- } while (!result || !result.then);
144
- result.then(_resumeAfterBody).then(void 0, reject);
145
- }
146
- function _resumeAfterTest(shouldContinue) {
147
- if (shouldContinue) {
148
- result = body();
149
- if (result && result.then) {
150
- result.then(_resumeAfterBody).then(void 0, reject);
151
- } else {
152
- _resumeAfterBody(result);
153
- }
154
- } else {
155
- _settle(pact, 1, result);
156
- }
157
- }
158
- function _resumeAfterUpdate() {
159
- if (shouldContinue = test()) {
160
- if (shouldContinue.then) {
161
- shouldContinue.then(_resumeAfterTest).then(void 0, reject);
162
- } else {
163
- _resumeAfterTest(shouldContinue);
164
- }
165
- } else {
166
- _settle(pact, 1, result);
167
- }
168
- }
169
- }
170
-
171
- // Asynchronously call a function and send errors to recovery continuation
172
- function _catch(body, recover) {
173
- try {
174
- var result = body();
175
- } catch(e) {
176
- return recover(e);
177
- }
178
- if (result && result.then) {
179
- return result.then(void 0, recover);
180
- }
181
- return result;
182
- }
183
-
184
- // Asynchronously await a promise and pass the result to a finally continuation
185
- function _finallyRethrows(body, finalizer) {
186
- try {
187
- var result = body();
188
- } catch (e) {
189
- return finalizer(true, e);
190
- }
191
- if (result && result.then) {
192
- return result.then(finalizer.bind(null, false), finalizer.bind(null, true));
193
- }
194
- return finalizer(false, result);
195
- }
196
-
197
14
  /*
198
15
  * Copyright (c) Microsoft Corporation. All rights reserved.
199
16
  * Licensed under the MIT License.
200
17
  */
201
- var Constants = {
18
+ const Constants = {
202
19
  /**
203
20
  * An existing file was the target of an operation that required that the target not exist
204
21
  */
@@ -220,106 +37,40 @@ var Constants = {
220
37
  /**
221
38
  * Default service name for using MSAL Keytar
222
39
  */
223
- DEFAULT_SERVICE_NAME: "msal-node-extensions"
224
- };
225
-
226
- function _inheritsLoose(subClass, superClass) {
227
- subClass.prototype = Object.create(superClass.prototype);
228
- subClass.prototype.constructor = subClass;
229
- subClass.__proto__ = superClass;
230
- }
231
-
232
- function _getPrototypeOf(o) {
233
- _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
234
- return o.__proto__ || Object.getPrototypeOf(o);
235
- };
236
- return _getPrototypeOf(o);
237
- }
238
-
239
- function _setPrototypeOf(o, p) {
240
- _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
241
- o.__proto__ = p;
242
- return o;
243
- };
244
-
245
- return _setPrototypeOf(o, p);
246
- }
247
-
248
- function _isNativeReflectConstruct() {
249
- if (typeof Reflect === "undefined" || !Reflect.construct) return false;
250
- if (Reflect.construct.sham) return false;
251
- if (typeof Proxy === "function") return true;
252
-
253
- try {
254
- Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
255
- return true;
256
- } catch (e) {
257
- return false;
258
- }
259
- }
260
-
261
- function _construct(Parent, args, Class) {
262
- if (_isNativeReflectConstruct()) {
263
- _construct = Reflect.construct;
264
- } else {
265
- _construct = function _construct(Parent, args, Class) {
266
- var a = [null];
267
- a.push.apply(a, args);
268
- var Constructor = Function.bind.apply(Parent, a);
269
- var instance = new Constructor();
270
- if (Class) _setPrototypeOf(instance, Class.prototype);
271
- return instance;
272
- };
273
- }
274
-
275
- return _construct.apply(null, arguments);
276
- }
277
-
278
- function _isNativeFunction(fn) {
279
- return Function.toString.call(fn).indexOf("[native code]") !== -1;
280
- }
281
-
282
- function _wrapNativeSuper(Class) {
283
- var _cache = typeof Map === "function" ? new Map() : undefined;
284
-
285
- _wrapNativeSuper = function _wrapNativeSuper(Class) {
286
- if (Class === null || !_isNativeFunction(Class)) return Class;
287
-
288
- if (typeof Class !== "function") {
289
- throw new TypeError("Super expression must either be null or a function");
290
- }
291
-
292
- if (typeof _cache !== "undefined") {
293
- if (_cache.has(Class)) return _cache.get(Class);
294
-
295
- _cache.set(Class, Wrapper);
296
- }
297
-
298
- function Wrapper() {
299
- return _construct(Class, arguments, _getPrototypeOf(this).constructor);
300
- }
40
+ DEFAULT_SERVICE_NAME: "msal-node-extensions",
301
41
 
302
- Wrapper.prototype = Object.create(Class.prototype, {
303
- constructor: {
304
- value: Wrapper,
305
- enumerable: false,
306
- writable: true,
307
- configurable: true
308
- }
309
- });
310
- return _setPrototypeOf(Wrapper, Class);
311
- };
42
+ /**
43
+ * Test data used to verify underlying persistence mechanism
44
+ */
45
+ PERSISTENCE_TEST_DATA: "Dummy data to verify underlying persistence mechanism",
312
46
 
313
- return _wrapNativeSuper(Class);
314
- }
47
+ /**
48
+ * This is the value of a the guid if the process is being ran by the root user
49
+ */
50
+ LINUX_ROOT_USER_GUID: 0,
315
51
 
316
- function _assertThisInitialized(self) {
317
- if (self === void 0) {
318
- throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
319
- }
52
+ /**
53
+ * List of environment variables
54
+ */
55
+ ENVIRONMENT: {
56
+ HOME: "HOME",
57
+ LOGNAME: "LOGNAME",
58
+ USER: "USER",
59
+ LNAME: "LNAME",
60
+ USERNAME: "USERNAME",
61
+ PLATFORM: "platform",
62
+ LOCAL_APPLICATION_DATA: "LOCALAPPDATA"
63
+ },
64
+ // Name of the default cache file
65
+ DEFAULT_CACHE_FILE_NAME: "cache.json"
66
+ };
67
+ var Platform;
320
68
 
321
- return self;
322
- }
69
+ (function (Platform) {
70
+ Platform["WINDOWS"] = "win32";
71
+ Platform["LINUX"] = "linux";
72
+ Platform["MACOS"] = "darwin";
73
+ })(Platform || (Platform = {}));
323
74
 
324
75
  /*
325
76
  * Copyright (c) Microsoft Corporation. All rights reserved.
@@ -329,71 +80,113 @@ function _assertThisInitialized(self) {
329
80
  /**
330
81
  * Error thrown when trying to write MSAL cache to persistence.
331
82
  */
332
- var PersistenceError = /*#__PURE__*/function (_Error) {
333
- _inheritsLoose(PersistenceError, _Error);
334
-
335
- function PersistenceError(errorCode, errorMessage) {
336
- var _this;
337
-
338
- var errorString = errorMessage ? errorCode + ": " + errorMessage : errorCode;
339
- _this = _Error.call(this, errorString) || this;
340
- Object.setPrototypeOf(_assertThisInitialized(_this), PersistenceError.prototype);
341
- _this.errorCode = errorCode;
342
- _this.errorMessage = errorMessage;
343
- _this.name = "PersistenceError";
344
- return _this;
83
+ class PersistenceError extends Error {
84
+ constructor(errorCode, errorMessage) {
85
+ const errorString = errorMessage ? `${errorCode}: ${errorMessage}` : errorCode;
86
+ super(errorString);
87
+ Object.setPrototypeOf(this, PersistenceError.prototype);
88
+ this.errorCode = errorCode;
89
+ this.errorMessage = errorMessage;
90
+ this.name = "PersistenceError";
345
91
  }
346
92
  /**
347
93
  * Error thrown when trying to access the file system.
348
94
  */
349
95
 
350
96
 
351
- PersistenceError.createFileSystemError = function createFileSystemError(errorCode, errorMessage) {
97
+ static createFileSystemError(errorCode, errorMessage) {
352
98
  return new PersistenceError(errorCode, errorMessage);
353
99
  }
354
100
  /**
355
101
  * Error thrown when trying to write, load, or delete data from secret service on linux.
356
102
  * Libsecret is used to access secret service.
357
103
  */
358
- ;
359
104
 
360
- PersistenceError.createLibSecretError = function createLibSecretError(errorMessage) {
105
+
106
+ static createLibSecretError(errorMessage) {
361
107
  return new PersistenceError("GnomeKeyringError", errorMessage);
362
108
  }
363
109
  /**
364
110
  * Error thrown when trying to write, load, or delete data from keychain on macOs.
365
111
  */
366
- ;
367
112
 
368
- PersistenceError.createKeychainPersistenceError = function createKeychainPersistenceError(errorMessage) {
113
+
114
+ static createKeychainPersistenceError(errorMessage) {
369
115
  return new PersistenceError("KeychainError", errorMessage);
370
116
  }
371
117
  /**
372
118
  * Error thrown when trying to encrypt or decrypt data using DPAPI on Windows.
373
119
  */
374
- ;
375
120
 
376
- PersistenceError.createFilePersistenceWithDPAPIError = function createFilePersistenceWithDPAPIError(errorMessage) {
121
+
122
+ static createFilePersistenceWithDPAPIError(errorMessage) {
377
123
  return new PersistenceError("DPAPIEncryptedFileError", errorMessage);
378
124
  }
379
125
  /**
380
126
  * Error thrown when using the cross platform lock.
381
127
  */
382
- ;
383
128
 
384
- PersistenceError.createCrossPlatformLockError = function createCrossPlatformLockError(errorMessage) {
129
+
130
+ static createCrossPlatformLockError(errorMessage) {
385
131
  return new PersistenceError("CrossPlatformLockError", errorMessage);
386
- };
132
+ }
133
+ /**
134
+ * Throw cache persistence error
135
+ *
136
+ * @param errorMessage string
137
+ * @returns PersistenceError
138
+ */
139
+
140
+
141
+ static createCachePersistenceError(errorMessage) {
142
+ return new PersistenceError("CachePersistenceError", errorMessage);
143
+ }
144
+ /**
145
+ * Throw unsupported error
146
+ *
147
+ * @param errorMessage string
148
+ * @returns PersistenceError
149
+ */
150
+
151
+
152
+ static createNotSupportedError(errorMessage) {
153
+ return new PersistenceError("NotSupportedError", errorMessage);
154
+ }
155
+ /**
156
+ * Throw persistence not verified error
157
+ *
158
+ * @param errorMessage string
159
+ * @returns PersistenceError
160
+ */
161
+
162
+
163
+ static createPersistenceNotVerifiedError(errorMessage) {
164
+ return new PersistenceError("PersistenceNotVerifiedError", errorMessage);
165
+ }
166
+ /**
167
+ * Throw persistence creation validation error
168
+ *
169
+ * @param errorMessage string
170
+ * @returns PersistenceError
171
+ */
172
+
173
+
174
+ static createPersistenceNotValidatedError(errorMessage) {
175
+ return new PersistenceError("PersistenceNotValidatedError", errorMessage);
176
+ }
387
177
 
388
- return PersistenceError;
389
- }( /*#__PURE__*/_wrapNativeSuper(Error));
178
+ }
390
179
 
180
+ /*
181
+ * Copyright (c) Microsoft Corporation. All rights reserved.
182
+ * Licensed under the MIT License.
183
+ */
391
184
  /**
392
185
  * Cross-process lock that works on all platforms.
393
186
  */
394
187
 
395
- var CrossPlatformLock = /*#__PURE__*/function () {
396
- function CrossPlatformLock(lockFilePath, logger, lockOptions) {
188
+ class CrossPlatformLock {
189
+ constructor(lockFilePath, logger, lockOptions) {
397
190
  this.lockFilePath = lockFilePath;
398
191
  this.retryNumber = lockOptions ? lockOptions.retryNumber : 500;
399
192
  this.retryDelay = lockOptions ? lockOptions.retryDelay : 100;
@@ -406,108 +199,65 @@ var CrossPlatformLock = /*#__PURE__*/function () {
406
199
  */
407
200
 
408
201
 
409
- var _proto = CrossPlatformLock.prototype;
410
-
411
- _proto.lock = function lock() {
412
- try {
413
- var _temp3 = function _temp3(_result3) {
414
- if (_exit2) return _result3;
415
-
416
- _this2.logger.error(process.pid + " was not able to acquire lock. Exceeded amount of retries set in the options");
417
-
418
- throw PersistenceError.createCrossPlatformLockError("Not able to acquire lock. Exceeded amount of retries set in options");
419
- };
420
-
421
- var _exit2 = false;
422
-
423
- var _this2 = this;
424
-
425
- var _tryCount = 0;
426
-
427
- var _temp4 = _for(function () {
428
- return !_exit2 && _tryCount < _this2.retryNumber;
429
- }, function () {
430
- return _tryCount++;
431
- }, function () {
432
- return _catch(function () {
433
- _this2.logger.info("Pid " + process.pid + " trying to acquire lock");
434
-
435
- return Promise.resolve(fs.promises.open(_this2.lockFilePath, "wx+")).then(function (_fs$open) {
436
- _this2.lockFileHandle = _fs$open;
437
-
438
- _this2.logger.info("Pid " + process.pid + " acquired lock");
439
-
440
- return Promise.resolve(_this2.lockFileHandle.write(process.pid.toString())).then(function () {
441
- _exit2 = true;
442
- });
443
- });
444
- }, function (err) {
445
- return function () {
446
- if (err.code == Constants.EEXIST_ERROR || err.code == Constants.EPERM_ERROR) {
447
- _this2.logger.info(err);
448
-
449
- return Promise.resolve(_this2.sleep(_this2.retryDelay)).then(function () {});
450
- } else {
451
- _this2.logger.error(process.pid + " was not able to acquire lock. Ran into error: " + err.message);
452
-
453
- throw PersistenceError.createCrossPlatformLockError(err.message);
454
- }
455
- }();
456
- });
457
- });
458
-
459
- return Promise.resolve(_temp4 && _temp4.then ? _temp4.then(_temp3) : _temp3(_temp4));
460
- } catch (e) {
461
- return Promise.reject(e);
202
+ async lock() {
203
+ for (let tryCount = 0; tryCount < this.retryNumber; tryCount++) {
204
+ try {
205
+ this.logger.info(`Pid ${process$1.pid} trying to acquire lock`);
206
+ this.lockFileHandle = await fs.promises.open(this.lockFilePath, "wx+");
207
+ this.logger.info(`Pid ${process$1.pid} acquired lock`);
208
+ await this.lockFileHandle.write(process$1.pid.toString());
209
+ return;
210
+ } catch (err) {
211
+ if (err.code === Constants.EEXIST_ERROR || err.code === Constants.EPERM_ERROR) {
212
+ this.logger.info(err);
213
+ await this.sleep(this.retryDelay);
214
+ } else {
215
+ this.logger.error(`${process$1.pid} was not able to acquire lock. Ran into error: ${err.message}`);
216
+ throw PersistenceError.createCrossPlatformLockError(err.message);
217
+ }
218
+ }
462
219
  }
220
+
221
+ this.logger.error(`${process$1.pid} was not able to acquire lock. Exceeded amount of retries set in the options`);
222
+ throw PersistenceError.createCrossPlatformLockError("Not able to acquire lock. Exceeded amount of retries set in options");
463
223
  }
464
224
  /**
465
225
  * unlocks cache file by deleting .lockfile.
466
226
  */
467
- ;
468
-
469
- _proto.unlock = function unlock() {
470
- try {
471
- var _this4 = this;
472
-
473
- return Promise.resolve(_catch(function () {
474
- var _temp5 = function () {
475
- if (_this4.lockFileHandle) {
476
- // if we have a file handle to the .lockfile, delete lock file
477
- return Promise.resolve(fs.promises.unlink(_this4.lockFilePath)).then(function () {
478
- return Promise.resolve(_this4.lockFileHandle.close()).then(function () {
479
- _this4.logger.info("lockfile deleted");
480
- });
481
- });
482
- } else {
483
- _this4.logger.warning("lockfile handle does not exist, so lockfile could not be deleted");
484
- }
485
- }();
486
227
 
487
- if (_temp5 && _temp5.then) return _temp5.then(function () {});
488
- }, function (err) {
489
- if (err.code == Constants.ENOENT_ERROR) {
490
- _this4.logger.warning("Tried to unlock but lockfile does not exist");
491
- } else {
492
- _this4.logger.error(process.pid + " was not able to release lock. Ran into error: " + err.message);
493
228
 
494
- throw PersistenceError.createCrossPlatformLockError(err.message);
495
- }
496
- }));
497
- } catch (e) {
498
- return Promise.reject(e);
229
+ async unlock() {
230
+ try {
231
+ if (this.lockFileHandle) {
232
+ // if we have a file handle to the .lockfile, delete lock file
233
+ await fs.promises.unlink(this.lockFilePath);
234
+ await this.lockFileHandle.close();
235
+ this.logger.info("lockfile deleted");
236
+ } else {
237
+ this.logger.warning("lockfile handle does not exist, so lockfile could not be deleted");
238
+ }
239
+ } catch (err) {
240
+ if (err.code === Constants.ENOENT_ERROR) {
241
+ this.logger.info("Tried to unlock but lockfile does not exist");
242
+ } else {
243
+ this.logger.error(`${process$1.pid} was not able to release lock. Ran into error: ${err.message}`);
244
+ throw PersistenceError.createCrossPlatformLockError(err.message);
245
+ }
499
246
  }
500
- };
247
+ }
501
248
 
502
- _proto.sleep = function sleep(ms) {
503
- return new Promise(function (resolve) {
249
+ sleep(ms) {
250
+ return new Promise(resolve => {
504
251
  setTimeout(resolve, ms);
505
252
  });
506
- };
253
+ }
507
254
 
508
- return CrossPlatformLock;
509
- }();
255
+ }
510
256
 
257
+ /*
258
+ * Copyright (c) Microsoft Corporation. All rights reserved.
259
+ * Licensed under the MIT License.
260
+ */
511
261
  /**
512
262
  * MSAL cache plugin which enables callers to write the MSAL cache to disk on Windows,
513
263
  * macOs, and Linux.
@@ -522,125 +272,117 @@ var CrossPlatformLock = /*#__PURE__*/function () {
522
272
  * libsecret be installed.
523
273
  */
524
274
 
525
- var PersistenceCachePlugin = /*#__PURE__*/function () {
526
- function PersistenceCachePlugin(persistence, lockOptions) {
275
+ class PersistenceCachePlugin {
276
+ constructor(persistence, lockOptions) {
527
277
  this.persistence = persistence; // initialize logger
528
278
 
529
279
  this.logger = persistence.getLogger(); // create file lock
530
280
 
531
- this.lockFilePath = this.persistence.getFilePath() + ".lockfile";
281
+ this.lockFilePath = `${this.persistence.getFilePath()}.lockfile`;
532
282
  this.crossPlatformLock = new CrossPlatformLock(this.lockFilePath, this.logger, lockOptions); // initialize default values
533
283
 
534
284
  this.lastSync = 0;
535
285
  this.currentCache = null;
536
286
  }
537
287
  /**
538
- * Reads from storage and avoids saves an in memory copy. If persistence has not been updated
288
+ * Reads from storage and saves an in-memory copy. If persistence has not been updated
539
289
  * since last time data was read, in memory copy is used.
290
+ *
291
+ * If cacheContext.cacheHasChanged === true, then file lock is created and not deleted until
292
+ * afterCacheAccess() is called, to prevent the cache file from changing in between
293
+ * beforeCacheAccess() and afterCacheAccess().
540
294
  */
541
295
 
542
296
 
543
- var _proto = PersistenceCachePlugin.prototype;
544
-
545
- _proto.readFromStorage = function readFromStorage() {
546
- try {
547
- var _this2 = this;
548
-
549
- _this2.logger.info("Reading from storage");
297
+ async beforeCacheAccess(cacheContext) {
298
+ this.logger.info("Executing before cache access");
299
+ const reloadNecessary = await this.persistence.reloadNecessary(this.lastSync);
550
300
 
551
- return Promise.resolve(_this2.persistence.reloadNecessary(_this2.lastSync)).then(function (_this$persistence$rel) {
552
- function _temp3() {
553
- return _this2.currentCache;
554
- }
301
+ if (!reloadNecessary && this.currentCache !== null) {
302
+ if (cacheContext.cacheHasChanged) {
303
+ this.logger.verbose("Cache context has changed");
304
+ await this.crossPlatformLock.lock();
305
+ }
555
306
 
556
- var _temp2 = function () {
557
- if (_this$persistence$rel || _this2.currentCache == null) {
558
- var _temp4 = _finallyRethrows(function () {
559
- _this2.logger.info("Reload necessary. Last sync time: " + _this2.lastSync);
560
-
561
- return Promise.resolve(_this2.crossPlatformLock.lock()).then(function () {
562
- return Promise.resolve(_this2.persistence.load()).then(function (_this$persistence$loa) {
563
- _this2.currentCache = _this$persistence$loa;
564
- _this2.lastSync = new Date().getTime();
565
-
566
- _this2.logger.info("Last sync time updated to: " + _this2.lastSync);
567
- });
568
- });
569
- }, function (_wasThrown, _result) {
570
- return Promise.resolve(_this2.crossPlatformLock.unlock()).then(function () {
571
- _this2.logger.info("Pid " + process.pid + " Released lock");
572
-
573
- if (_wasThrown) throw _result;
574
- return _result;
575
- });
576
- });
577
-
578
- if (_temp4 && _temp4.then) return _temp4.then(function () {});
579
- }
580
- }();
307
+ return;
308
+ }
581
309
 
582
- return _temp2 && _temp2.then ? _temp2.then(_temp3) : _temp3(_temp2);
583
- });
584
- } catch (e) {
585
- return Promise.reject(e);
310
+ try {
311
+ this.logger.info(`Reload necessary. Last sync time: ${this.lastSync}`);
312
+ await this.crossPlatformLock.lock();
313
+ this.currentCache = await this.persistence.load();
314
+ this.lastSync = new Date().getTime();
315
+ cacheContext.tokenCache.deserialize(this.currentCache);
316
+ this.logger.info(`Last sync time updated to: ${this.lastSync}`);
317
+ } finally {
318
+ if (!cacheContext.cacheHasChanged) {
319
+ await this.crossPlatformLock.unlock();
320
+ this.logger.info(`Pid ${process$1.pid} released lock`);
321
+ } else {
322
+ this.logger.info(`Pid ${process$1.pid} beforeCacheAccess did not release lock`);
323
+ }
586
324
  }
587
325
  }
588
326
  /**
589
- * Writes to storage. If persistence has not been updated since last time data was read,
590
- * reads and latest state from persistence, sends state via callback, and updates in memory copy.
327
+ * Writes to storage if MSAL in memory copy of cache has been changed.
591
328
  */
592
- ;
593
329
 
594
- _proto.writeToStorage = function writeToStorage(callback) {
330
+
331
+ async afterCacheAccess(cacheContext) {
332
+ this.logger.info("Executing after cache access");
333
+
595
334
  try {
596
- var _this4 = this;
597
-
598
- var _temp8 = _finallyRethrows(function () {
599
- _this4.logger.info("Writing to storage");
600
-
601
- return Promise.resolve(_this4.crossPlatformLock.lock()).then(function () {
602
- return Promise.resolve(_this4.persistence.reloadNecessary(_this4.lastSync)).then(function (_this3$persistence$re) {
603
- function _temp6() {
604
- return Promise.resolve(callback(_this4.currentCache)).then(function (_callback) {
605
- _this4.currentCache = _callback;
606
- return Promise.resolve(_this4.persistence.save(_this4.currentCache)).then(function () {});
607
- });
608
- }
609
-
610
- var _temp5 = function () {
611
- if (_this3$persistence$re) {
612
- _this4.logger.info("Reload necessary. Last sync time: " + _this4.lastSync);
613
-
614
- return Promise.resolve(_this4.persistence.load()).then(function (_this3$persistence$lo) {
615
- _this4.currentCache = _this3$persistence$lo;
616
- _this4.lastSync = new Date().getTime();
617
-
618
- _this4.logger.info("Last sync time updated to: " + _this4.lastSync);
619
- });
620
- }
621
- }();
622
-
623
- return _temp5 && _temp5.then ? _temp5.then(_temp6) : _temp6(_temp5);
624
- });
625
- });
626
- }, function (_wasThrown2, _result2) {
627
- return Promise.resolve(_this4.crossPlatformLock.unlock()).then(function () {
628
- _this4.logger.info("Pid " + process.pid + " Released lock");
629
-
630
- if (_wasThrown2) throw _result2;
631
- return _result2;
632
- });
633
- });
335
+ if (cacheContext.cacheHasChanged) {
336
+ this.logger.info("Msal in-memory cache has changed. Writing changes to persistence");
337
+ this.currentCache = cacheContext.tokenCache.serialize();
338
+ await this.persistence.save(this.currentCache);
339
+ } else {
340
+ this.logger.info("Msal in-memory cache has not changed. Did not write to persistence");
341
+ }
342
+ } finally {
343
+ await this.crossPlatformLock.unlock();
344
+ this.logger.info(`Pid ${process$1.pid} afterCacheAccess released lock`);
345
+ }
346
+ }
347
+
348
+ }
349
+
350
+ /*
351
+ * Copyright (c) Microsoft Corporation. All rights reserved.
352
+ * Licensed under the MIT License.
353
+ */
354
+ class BasePersistence {
355
+ async verifyPersistence() {
356
+ // We are using a different location for the test to avoid overriding the functional cache
357
+ const persistenceValidator = await this.createForPersistenceValidation();
358
+
359
+ try {
360
+ await persistenceValidator.save(Constants.PERSISTENCE_TEST_DATA);
361
+ const retrievedDummyData = await persistenceValidator.load();
362
+
363
+ if (!retrievedDummyData) {
364
+ throw PersistenceError.createCachePersistenceError("Persistence check failed. Data was written but it could not be read. " + "Possible cause: on Linux, LibSecret is installed but D-Bus isn't running \
365
+ because it cannot be started over SSH.");
366
+ }
367
+
368
+ if (retrievedDummyData !== Constants.PERSISTENCE_TEST_DATA) {
369
+ throw PersistenceError.createCachePersistenceError(`Persistence check failed. Data written ${Constants.PERSISTENCE_TEST_DATA} is different \
370
+ from data read ${retrievedDummyData}`);
371
+ }
634
372
 
635
- return Promise.resolve(_temp8 && _temp8.then ? _temp8.then(function () {}) : void 0);
373
+ await persistenceValidator.delete();
374
+ return true;
636
375
  } catch (e) {
637
- return Promise.reject(e);
376
+ throw PersistenceError.createCachePersistenceError(`Verifing persistence failed with the error: ${e}`);
638
377
  }
639
- };
378
+ }
640
379
 
641
- return PersistenceCachePlugin;
642
- }();
380
+ }
643
381
 
382
+ /*
383
+ * Copyright (c) Microsoft Corporation. All rights reserved.
384
+ * Licensed under the MIT License.
385
+ */
644
386
  /**
645
387
  * Reads and writes data to file specified by file location. File contents are not
646
388
  * encrypted.
@@ -649,203 +391,149 @@ var PersistenceCachePlugin = /*#__PURE__*/function () {
649
391
  * file and any directories in the path recursively.
650
392
  */
651
393
 
652
- var FilePersistence = /*#__PURE__*/function () {
653
- function FilePersistence() {}
654
-
655
- FilePersistence.create = function create(fileLocation, loggerOptions) {
656
- try {
657
- var filePersistence = new FilePersistence();
658
- filePersistence.filePath = fileLocation;
659
- filePersistence.logger = new msalCommon.Logger(loggerOptions || FilePersistence.createDefaultLoggerOptions());
660
- return Promise.resolve(filePersistence.createCacheFile()).then(function () {
661
- return filePersistence;
662
- });
663
- } catch (e) {
664
- return Promise.reject(e);
665
- }
666
- };
667
-
668
- var _proto = FilePersistence.prototype;
394
+ class FilePersistence extends BasePersistence {
395
+ static async create(fileLocation, loggerOptions) {
396
+ const filePersistence = new FilePersistence();
397
+ filePersistence.filePath = fileLocation;
398
+ filePersistence.logger = new msalCommon.Logger(loggerOptions || FilePersistence.createDefaultLoggerOptions());
399
+ await filePersistence.createCacheFile();
400
+ return filePersistence;
401
+ }
669
402
 
670
- _proto.save = function save(contents) {
403
+ async save(contents) {
671
404
  try {
672
- var _this2 = this;
673
-
674
- return Promise.resolve(_catch(function () {
675
- return Promise.resolve(fs.promises.writeFile(_this2.getFilePath(), contents, "utf-8")).then(function () {});
676
- }, function (err) {
677
- throw PersistenceError.createFileSystemError(err.code, err.message);
678
- }));
679
- } catch (e) {
680
- return Promise.reject(e);
405
+ await fs.promises.writeFile(this.getFilePath(), contents, "utf-8");
406
+ } catch (err) {
407
+ throw PersistenceError.createFileSystemError(err.code, err.message);
681
408
  }
682
- };
409
+ }
683
410
 
684
- _proto.saveBuffer = function saveBuffer(contents) {
411
+ async saveBuffer(contents) {
685
412
  try {
686
- var _this4 = this;
687
-
688
- return Promise.resolve(_catch(function () {
689
- return Promise.resolve(fs.promises.writeFile(_this4.getFilePath(), contents)).then(function () {});
690
- }, function (err) {
691
- throw PersistenceError.createFileSystemError(err.code, err.message);
692
- }));
693
- } catch (e) {
694
- return Promise.reject(e);
413
+ await fs.promises.writeFile(this.getFilePath(), contents);
414
+ } catch (err) {
415
+ throw PersistenceError.createFileSystemError(err.code, err.message);
695
416
  }
696
- };
417
+ }
697
418
 
698
- _proto.load = function load() {
419
+ async load() {
699
420
  try {
700
- var _this6 = this;
701
-
702
- return Promise.resolve(_catch(function () {
703
- return Promise.resolve(fs.promises.readFile(_this6.getFilePath(), "utf-8"));
704
- }, function (err) {
705
- throw PersistenceError.createFileSystemError(err.code, err.message);
706
- }));
707
- } catch (e) {
708
- return Promise.reject(e);
421
+ return await fs.promises.readFile(this.getFilePath(), "utf-8");
422
+ } catch (err) {
423
+ throw PersistenceError.createFileSystemError(err.code, err.message);
709
424
  }
710
- };
425
+ }
711
426
 
712
- _proto.loadBuffer = function loadBuffer() {
427
+ async loadBuffer() {
713
428
  try {
714
- var _this8 = this;
715
-
716
- return Promise.resolve(_catch(function () {
717
- return Promise.resolve(fs.promises.readFile(_this8.getFilePath()));
718
- }, function (err) {
719
- throw PersistenceError.createFileSystemError(err.code, err.message);
720
- }));
721
- } catch (e) {
722
- return Promise.reject(e);
429
+ return await fs.promises.readFile(this.getFilePath());
430
+ } catch (err) {
431
+ throw PersistenceError.createFileSystemError(err.code, err.message);
723
432
  }
724
- };
433
+ }
725
434
 
726
- _proto["delete"] = function _delete() {
435
+ async delete() {
727
436
  try {
728
- var _this10 = this;
729
-
730
- return Promise.resolve(_catch(function () {
731
- return Promise.resolve(fs.promises.unlink(_this10.getFilePath())).then(function () {
732
- return true;
733
- });
734
- }, function (err) {
735
- if (err.code == Constants.ENOENT_ERROR) {
736
- // file does not exist, so it was not deleted
737
- _this10.logger.warning("Cache file does not exist, so it could not be deleted");
738
-
739
- return false;
740
- }
437
+ await fs.promises.unlink(this.getFilePath());
438
+ return true;
439
+ } catch (err) {
440
+ if (err.code === Constants.ENOENT_ERROR) {
441
+ // file does not exist, so it was not deleted
442
+ this.logger.warning("Cache file does not exist, so it could not be deleted");
443
+ return false;
444
+ }
741
445
 
742
- throw PersistenceError.createFileSystemError(err.code, err.message);
743
- }));
744
- } catch (e) {
745
- return Promise.reject(e);
446
+ throw PersistenceError.createFileSystemError(err.code, err.message);
746
447
  }
747
- };
448
+ }
748
449
 
749
- _proto.getFilePath = function getFilePath() {
450
+ getFilePath() {
750
451
  return this.filePath;
751
- };
752
-
753
- _proto.reloadNecessary = function reloadNecessary(lastSync) {
754
- try {
755
- var _this12 = this;
452
+ }
756
453
 
757
- return Promise.resolve(_this12.timeLastModified()).then(function (_this11$timeLastModif) {
758
- return lastSync < _this11$timeLastModif;
759
- });
760
- } catch (e) {
761
- return Promise.reject(e);
762
- }
763
- };
454
+ async reloadNecessary(lastSync) {
455
+ return lastSync < (await this.timeLastModified());
456
+ }
764
457
 
765
- _proto.getLogger = function getLogger() {
458
+ getLogger() {
766
459
  return this.logger;
767
- };
460
+ }
461
+
462
+ createForPersistenceValidation() {
463
+ const testCacheFileLocation = `${path.dirname(this.filePath)}/test.cache`;
464
+ return FilePersistence.create(testCacheFileLocation);
465
+ }
768
466
 
769
- FilePersistence.createDefaultLoggerOptions = function createDefaultLoggerOptions() {
467
+ static createDefaultLoggerOptions() {
770
468
  return {
771
- loggerCallback: function loggerCallback() {// allow users to not set loggerCallback
469
+ loggerCallback: () => {// allow users to not set loggerCallback
772
470
  },
773
471
  piiLoggingEnabled: false,
774
472
  logLevel: msalCommon.LogLevel.Info
775
473
  };
776
- };
474
+ }
777
475
 
778
- _proto.timeLastModified = function timeLastModified() {
476
+ async timeLastModified() {
779
477
  try {
780
- var _this14 = this;
781
-
782
- return Promise.resolve(_catch(function () {
783
- return Promise.resolve(fs.promises.stat(_this14.filePath)).then(function (stats) {
784
- return stats.mtime.getTime();
785
- });
786
- }, function (err) {
787
- if (err.code == Constants.ENOENT_ERROR) {
788
- // file does not exist, so it's never been modified
789
- _this14.logger.verbose("Cache file does not exist");
790
-
791
- return 0;
792
- }
478
+ const stats = await fs.promises.stat(this.filePath);
479
+ return stats.mtime.getTime();
480
+ } catch (err) {
481
+ if (err.code === Constants.ENOENT_ERROR) {
482
+ // file does not exist, so it's never been modified
483
+ this.logger.verbose("Cache file does not exist");
484
+ return 0;
485
+ }
793
486
 
794
- throw PersistenceError.createFileSystemError(err.code, err.message);
795
- }));
796
- } catch (e) {
797
- return Promise.reject(e);
487
+ throw PersistenceError.createFileSystemError(err.code, err.message);
798
488
  }
799
- };
489
+ }
490
+
491
+ async createCacheFile() {
492
+ await this.createFileDirectory(); // File is created only if it does not exist
493
+
494
+ const fileHandle = await fs.promises.open(this.filePath, "a");
495
+ await fileHandle.close();
496
+ this.logger.info(`File created at ${this.filePath}`);
497
+ }
800
498
 
801
- _proto.createCacheFile = function createCacheFile() {
499
+ async createFileDirectory() {
802
500
  try {
803
- var _this16 = this;
804
-
805
- return Promise.resolve(_this16.createFileDirectory()).then(function () {
806
- // File is created only if it does not exist
807
- return Promise.resolve(fs.promises.open(_this16.filePath, "a")).then(function (fileHandle) {
808
- return Promise.resolve(fileHandle.close()).then(function () {
809
- _this16.logger.info("File created at " + _this16.filePath);
810
- });
811
- });
501
+ await fs.promises.mkdir(path.dirname(this.filePath), {
502
+ recursive: true
812
503
  });
813
- } catch (e) {
814
- return Promise.reject(e);
504
+ } catch (err) {
505
+ if (err.code === Constants.EEXIST_ERROR) {
506
+ this.logger.info(`Directory ${path.dirname(this.filePath)} already exists`);
507
+ } else {
508
+ throw PersistenceError.createFileSystemError(err.code, err.message);
509
+ }
815
510
  }
816
- };
511
+ }
817
512
 
818
- _proto.createFileDirectory = function createFileDirectory() {
819
- try {
820
- var _this18 = this;
821
-
822
- return Promise.resolve(_catch(function () {
823
- return Promise.resolve(fs.promises.mkdir(path.dirname(_this18.filePath), {
824
- recursive: true
825
- })).then(function () {});
826
- }, function (err) {
827
- if (err.code == Constants.EEXIST_ERROR) {
828
- _this18.logger.info("Directory " + path.dirname(_this18.filePath) + " already exists");
829
- } else {
830
- throw PersistenceError.createFileSystemError(err.code, err.message);
831
- }
832
- }));
833
- } catch (e) {
834
- return Promise.reject(e);
835
- }
836
- };
513
+ }
514
+
515
+ /*
516
+ * Copyright (c) Microsoft Corporation. All rights reserved.
517
+ * Licensed under the MIT License.
518
+ */
837
519
 
838
- return FilePersistence;
839
- }();
520
+ /* eslint-disable-next-line @typescript-eslint/no-var-requires, no-var, import/no-commonjs */
521
+ var Dpapi = /*#__PURE__*/require("../build/Release/dpapi.node");
840
522
 
841
523
  /*
842
524
  * Copyright (c) Microsoft Corporation. All rights reserved.
843
525
  * Licensed under the MIT License.
844
526
  */
845
527
 
846
- /* eslint-disable-next-line @typescript-eslint/no-var-requires, no-var */
847
- var Dpapi = /*#__PURE__*/require("bindings")("dpapi");
528
+ (function (DataProtectionScope) {
529
+ DataProtectionScope["CurrentUser"] = "CurrentUser";
530
+ DataProtectionScope["LocalMachine"] = "LocalMachine";
531
+ })(exports.DataProtectionScope || (exports.DataProtectionScope = {}));
848
532
 
533
+ /*
534
+ * Copyright (c) Microsoft Corporation. All rights reserved.
535
+ * Licensed under the MIT License.
536
+ */
849
537
  /**
850
538
  * Uses CryptProtectData and CryptUnprotectData on Windows to encrypt and decrypt file contents.
851
539
  *
@@ -853,104 +541,70 @@ var Dpapi = /*#__PURE__*/require("bindings")("dpapi");
853
541
  * optionalEntropy: Password or other additional entropy used to encrypt the data
854
542
  */
855
543
 
856
- var FilePersistenceWithDataProtection = /*#__PURE__*/function () {
857
- function FilePersistenceWithDataProtection(scope, optionalEntropy) {
544
+ class FilePersistenceWithDataProtection extends BasePersistence {
545
+ constructor(scope, optionalEntropy) {
546
+ super();
858
547
  this.scope = scope;
859
548
  this.optionalEntropy = optionalEntropy ? Buffer.from(optionalEntropy, "utf-8") : null;
860
549
  }
861
550
 
862
- FilePersistenceWithDataProtection.create = function create(fileLocation, scope, optionalEntropy, loggerOptions) {
863
- try {
864
- var persistence = new FilePersistenceWithDataProtection(scope, optionalEntropy);
865
- return Promise.resolve(FilePersistence.create(fileLocation, loggerOptions)).then(function (_FilePersistence$crea) {
866
- persistence.filePersistence = _FilePersistence$crea;
867
- return persistence;
868
- });
869
- } catch (e) {
870
- return Promise.reject(e);
871
- }
872
- };
873
-
874
- var _proto = FilePersistenceWithDataProtection.prototype;
551
+ static async create(fileLocation, scope, optionalEntropy, loggerOptions) {
552
+ const persistence = new FilePersistenceWithDataProtection(scope, optionalEntropy);
553
+ persistence.filePersistence = await FilePersistence.create(fileLocation, loggerOptions);
554
+ return persistence;
555
+ }
875
556
 
876
- _proto.save = function save(contents) {
557
+ async save(contents) {
877
558
  try {
878
- var _this2 = this;
879
-
880
- return Promise.resolve(_catch(function () {
881
- var encryptedContents = Dpapi.protectData(Buffer.from(contents, "utf-8"), _this2.optionalEntropy, _this2.scope.toString());
882
- return Promise.resolve(_this2.filePersistence.saveBuffer(encryptedContents)).then(function () {});
883
- }, function (err) {
884
- throw PersistenceError.createFilePersistenceWithDPAPIError(err.message);
885
- }));
886
- } catch (e) {
887
- return Promise.reject(e);
559
+ const encryptedContents = Dpapi.protectData(Buffer.from(contents, "utf-8"), this.optionalEntropy, this.scope.toString());
560
+ await this.filePersistence.saveBuffer(encryptedContents);
561
+ } catch (err) {
562
+ throw PersistenceError.createFilePersistenceWithDPAPIError(err.message);
888
563
  }
889
- };
564
+ }
890
565
 
891
- _proto.load = function load() {
566
+ async load() {
892
567
  try {
893
- var _this4 = this;
894
-
895
- return Promise.resolve(_catch(function () {
896
- return Promise.resolve(_this4.filePersistence.loadBuffer()).then(function (encryptedContents) {
897
- if (typeof encryptedContents === "undefined" || !encryptedContents || 0 === encryptedContents.length) {
898
- _this4.filePersistence.getLogger().info("Encrypted contents loaded from file were null or empty");
899
-
900
- return null;
901
- }
902
-
903
- return Dpapi.unprotectData(encryptedContents, _this4.optionalEntropy, _this4.scope.toString()).toString();
904
- });
905
- }, function (err) {
906
- throw PersistenceError.createFilePersistenceWithDPAPIError(err.message);
907
- }));
908
- } catch (e) {
909
- return Promise.reject(e);
910
- }
911
- };
568
+ const encryptedContents = await this.filePersistence.loadBuffer();
912
569
 
913
- _proto["delete"] = function _delete() {
914
- try {
915
- var _this6 = this;
570
+ if (typeof encryptedContents === "undefined" || !encryptedContents || 0 === encryptedContents.length) {
571
+ this.filePersistence.getLogger().info("Encrypted contents loaded from file were null or empty");
572
+ return null;
573
+ }
916
574
 
917
- return Promise.resolve(_this6.filePersistence["delete"]());
918
- } catch (e) {
919
- return Promise.reject(e);
575
+ return Dpapi.unprotectData(encryptedContents, this.optionalEntropy, this.scope.toString()).toString();
576
+ } catch (err) {
577
+ throw PersistenceError.createFilePersistenceWithDPAPIError(err.message);
920
578
  }
921
- };
579
+ }
922
580
 
923
- _proto.reloadNecessary = function reloadNecessary(lastSync) {
924
- try {
925
- var _this8 = this;
581
+ async delete() {
582
+ return this.filePersistence.delete();
583
+ }
926
584
 
927
- return Promise.resolve(_this8.filePersistence.reloadNecessary(lastSync));
928
- } catch (e) {
929
- return Promise.reject(e);
930
- }
931
- };
585
+ async reloadNecessary(lastSync) {
586
+ return this.filePersistence.reloadNecessary(lastSync);
587
+ }
932
588
 
933
- _proto.getFilePath = function getFilePath() {
589
+ getFilePath() {
934
590
  return this.filePersistence.getFilePath();
935
- };
591
+ }
936
592
 
937
- _proto.getLogger = function getLogger() {
593
+ getLogger() {
938
594
  return this.filePersistence.getLogger();
939
- };
595
+ }
940
596
 
941
- return FilePersistenceWithDataProtection;
942
- }();
597
+ createForPersistenceValidation() {
598
+ const testCacheFileLocation = `${path.dirname(this.filePersistence.getFilePath())}/test.cache`;
599
+ return FilePersistenceWithDataProtection.create(testCacheFileLocation, exports.DataProtectionScope.CurrentUser);
600
+ }
601
+
602
+ }
943
603
 
944
604
  /*
945
605
  * Copyright (c) Microsoft Corporation. All rights reserved.
946
606
  * Licensed under the MIT License.
947
607
  */
948
-
949
- (function (DataProtectionScope) {
950
- DataProtectionScope["CurrentUser"] = "CurrentUser";
951
- DataProtectionScope["LocalMachine"] = "LocalMachine";
952
- })(exports.DataProtectionScope || (exports.DataProtectionScope = {}));
953
-
954
608
  /**
955
609
  * Uses reads and writes passwords to macOS keychain
956
610
  *
@@ -958,99 +612,70 @@ var FilePersistenceWithDataProtection = /*#__PURE__*/function () {
958
612
  * accountName: Account under which password should be stored
959
613
  */
960
614
 
961
- var KeychainPersistence = /*#__PURE__*/function () {
962
- function KeychainPersistence(serviceName, accountName) {
615
+ class KeychainPersistence extends BasePersistence {
616
+ constructor(serviceName, accountName) {
617
+ super();
963
618
  this.serviceName = serviceName;
964
619
  this.accountName = accountName;
965
620
  }
966
621
 
967
- KeychainPersistence.create = function create(fileLocation, serviceName, accountName, loggerOptions) {
968
- try {
969
- var persistence = new KeychainPersistence(serviceName, accountName);
970
- return Promise.resolve(FilePersistence.create(fileLocation, loggerOptions)).then(function (_FilePersistence$crea) {
971
- persistence.filePersistence = _FilePersistence$crea;
972
- return persistence;
973
- });
974
- } catch (e) {
975
- return Promise.reject(e);
976
- }
977
- };
978
-
979
- var _proto = KeychainPersistence.prototype;
622
+ static async create(fileLocation, serviceName, accountName, loggerOptions) {
623
+ const persistence = new KeychainPersistence(serviceName, accountName);
624
+ persistence.filePersistence = await FilePersistence.create(fileLocation, loggerOptions);
625
+ return persistence;
626
+ }
980
627
 
981
- _proto.save = function save(contents) {
628
+ async save(contents) {
982
629
  try {
983
- var _temp3 = function _temp3(_result) {
984
- return _exit2 ? _result : Promise.resolve(_this2.filePersistence.save("{}")).then(function () {});
985
- };
630
+ await keytar.setPassword(this.serviceName, this.accountName, contents);
631
+ } catch (err) {
632
+ throw PersistenceError.createKeychainPersistenceError(err.message);
633
+ } // Write dummy data to update file mtime
986
634
 
987
- var _exit2 = false;
988
-
989
- var _this2 = this;
990
-
991
- var _temp4 = _catch(function () {
992
- return Promise.resolve(keytar.setPassword(_this2.serviceName, _this2.accountName, contents)).then(function () {});
993
- }, function (err) {
994
- throw PersistenceError.createKeychainPersistenceError(err.message);
995
- });
996
635
 
997
- return Promise.resolve(_temp4 && _temp4.then ? _temp4.then(_temp3) : _temp3(_temp4)); // Write dummy data to update file mtime
998
- } catch (e) {
999
- return Promise.reject(e);
1000
- }
1001
- };
636
+ await this.filePersistence.save("{}");
637
+ }
1002
638
 
1003
- _proto.load = function load() {
639
+ async load() {
1004
640
  try {
1005
- var _this4 = this;
1006
-
1007
- return Promise.resolve(_catch(function () {
1008
- return Promise.resolve(keytar.getPassword(_this4.serviceName, _this4.accountName));
1009
- }, function (err) {
1010
- throw PersistenceError.createKeychainPersistenceError(err.message);
1011
- }));
1012
- } catch (e) {
1013
- return Promise.reject(e);
641
+ return await keytar.getPassword(this.serviceName, this.accountName);
642
+ } catch (err) {
643
+ throw PersistenceError.createKeychainPersistenceError(err.message);
1014
644
  }
1015
- };
645
+ }
1016
646
 
1017
- _proto["delete"] = function _delete() {
647
+ async delete() {
1018
648
  try {
1019
- var _this6 = this;
1020
-
1021
- return Promise.resolve(_catch(function () {
1022
- return Promise.resolve(_this6.filePersistence["delete"]()).then(function () {
1023
- return Promise.resolve(keytar.deletePassword(_this6.serviceName, _this6.accountName));
1024
- });
1025
- }, function (err) {
1026
- throw PersistenceError.createKeychainPersistenceError(err.message);
1027
- }));
1028
- } catch (e) {
1029
- return Promise.reject(e);
649
+ await this.filePersistence.delete();
650
+ return await keytar.deletePassword(this.serviceName, this.accountName);
651
+ } catch (err) {
652
+ throw PersistenceError.createKeychainPersistenceError(err.message);
1030
653
  }
1031
- };
1032
-
1033
- _proto.reloadNecessary = function reloadNecessary(lastSync) {
1034
- try {
1035
- var _this8 = this;
654
+ }
1036
655
 
1037
- return Promise.resolve(_this8.filePersistence.reloadNecessary(lastSync));
1038
- } catch (e) {
1039
- return Promise.reject(e);
1040
- }
1041
- };
656
+ async reloadNecessary(lastSync) {
657
+ return this.filePersistence.reloadNecessary(lastSync);
658
+ }
1042
659
 
1043
- _proto.getFilePath = function getFilePath() {
660
+ getFilePath() {
1044
661
  return this.filePersistence.getFilePath();
1045
- };
662
+ }
1046
663
 
1047
- _proto.getLogger = function getLogger() {
664
+ getLogger() {
1048
665
  return this.filePersistence.getLogger();
1049
- };
666
+ }
1050
667
 
1051
- return KeychainPersistence;
1052
- }();
668
+ createForPersistenceValidation() {
669
+ const testCacheFileLocation = `${path.dirname(this.filePersistence.getFilePath())}/test.cache`;
670
+ return KeychainPersistence.create(testCacheFileLocation, "persistenceValidationServiceName", "persistencValidationAccountName");
671
+ }
672
+
673
+ }
1053
674
 
675
+ /*
676
+ * Copyright (c) Microsoft Corporation. All rights reserved.
677
+ * Licensed under the MIT License.
678
+ */
1054
679
  /**
1055
680
  * Uses reads and writes passwords to Secret Service API/libsecret. Requires libsecret
1056
681
  * to be installed.
@@ -1059,102 +684,221 @@ var KeychainPersistence = /*#__PURE__*/function () {
1059
684
  * accountName: Account under which password should be stored
1060
685
  */
1061
686
 
1062
- var LibSecretPersistence = /*#__PURE__*/function () {
1063
- function LibSecretPersistence(serviceName, accountName) {
687
+ class LibSecretPersistence extends BasePersistence {
688
+ constructor(serviceName, accountName) {
689
+ super();
1064
690
  this.serviceName = serviceName;
1065
691
  this.accountName = accountName;
1066
692
  }
1067
693
 
1068
- LibSecretPersistence.create = function create(fileLocation, serviceName, accountName, loggerOptions) {
694
+ static async create(fileLocation, serviceName, accountName, loggerOptions) {
695
+ const persistence = new LibSecretPersistence(serviceName, accountName);
696
+ persistence.filePersistence = await FilePersistence.create(fileLocation, loggerOptions);
697
+ return persistence;
698
+ }
699
+
700
+ async save(contents) {
1069
701
  try {
1070
- var persistence = new LibSecretPersistence(serviceName, accountName);
1071
- return Promise.resolve(FilePersistence.create(fileLocation, loggerOptions)).then(function (_FilePersistence$crea) {
1072
- persistence.filePersistence = _FilePersistence$crea;
1073
- return persistence;
1074
- });
1075
- } catch (e) {
1076
- return Promise.reject(e);
1077
- }
1078
- };
702
+ await keytar.setPassword(this.serviceName, this.accountName, contents);
703
+ } catch (err) {
704
+ throw PersistenceError.createLibSecretError(err.message);
705
+ } // Write dummy data to update file mtime
1079
706
 
1080
- var _proto = LibSecretPersistence.prototype;
1081
707
 
1082
- _proto.save = function save(contents) {
708
+ await this.filePersistence.save("{}");
709
+ }
710
+
711
+ async load() {
1083
712
  try {
1084
- var _temp3 = function _temp3(_result) {
1085
- return _exit2 ? _result : Promise.resolve(_this2.filePersistence.save("{}")).then(function () {});
1086
- };
713
+ return await keytar.getPassword(this.serviceName, this.accountName);
714
+ } catch (err) {
715
+ throw PersistenceError.createLibSecretError(err.message);
716
+ }
717
+ }
1087
718
 
1088
- var _exit2 = false;
719
+ async delete() {
720
+ try {
721
+ await this.filePersistence.delete();
722
+ return await keytar.deletePassword(this.serviceName, this.accountName);
723
+ } catch (err) {
724
+ throw PersistenceError.createLibSecretError(err.message);
725
+ }
726
+ }
1089
727
 
1090
- var _this2 = this;
728
+ async reloadNecessary(lastSync) {
729
+ return this.filePersistence.reloadNecessary(lastSync);
730
+ }
1091
731
 
1092
- var _temp4 = _catch(function () {
1093
- return Promise.resolve(keytar.setPassword(_this2.serviceName, _this2.accountName, contents)).then(function () {});
1094
- }, function (err) {
1095
- throw PersistenceError.createLibSecretError(err.message);
1096
- });
732
+ getFilePath() {
733
+ return this.filePersistence.getFilePath();
734
+ }
1097
735
 
1098
- return Promise.resolve(_temp4 && _temp4.then ? _temp4.then(_temp3) : _temp3(_temp4)); // Write dummy data to update file mtime
1099
- } catch (e) {
1100
- return Promise.reject(e);
1101
- }
1102
- };
736
+ getLogger() {
737
+ return this.filePersistence.getLogger();
738
+ }
1103
739
 
1104
- _proto.load = function load() {
1105
- try {
1106
- var _this4 = this;
740
+ createForPersistenceValidation() {
741
+ const testCacheFileLocation = `${path.dirname(this.filePersistence.getFilePath())}/test.cache`;
742
+ return LibSecretPersistence.create(testCacheFileLocation, "persistenceValidationServiceName", "persistencValidationAccountName");
743
+ }
1107
744
 
1108
- return Promise.resolve(_catch(function () {
1109
- return Promise.resolve(keytar.getPassword(_this4.serviceName, _this4.accountName));
1110
- }, function (err) {
1111
- throw PersistenceError.createLibSecretError(err.message);
1112
- }));
1113
- } catch (e) {
1114
- return Promise.reject(e);
745
+ }
746
+
747
+ /*
748
+ * Copyright (c) Microsoft Corporation. All rights reserved.
749
+ * Licensed under the MIT License.
750
+ */
751
+ class Environment {
752
+ static get homeEnvVar() {
753
+ return this.getEnvironmentVariable(Constants.ENVIRONMENT.HOME);
754
+ }
755
+
756
+ static get lognameEnvVar() {
757
+ return this.getEnvironmentVariable(Constants.ENVIRONMENT.LOGNAME);
758
+ }
759
+
760
+ static get userEnvVar() {
761
+ return this.getEnvironmentVariable(Constants.ENVIRONMENT.USER);
762
+ }
763
+
764
+ static get lnameEnvVar() {
765
+ return this.getEnvironmentVariable(Constants.ENVIRONMENT.LNAME);
766
+ }
767
+
768
+ static get usernameEnvVar() {
769
+ return this.getEnvironmentVariable(Constants.ENVIRONMENT.USERNAME);
770
+ }
771
+
772
+ static getEnvironmentVariable(name) {
773
+ return process.env[name];
774
+ }
775
+
776
+ static getEnvironmentPlatform() {
777
+ return process.platform;
778
+ }
779
+
780
+ static isWindowsPlatform() {
781
+ return this.getEnvironmentPlatform() === Platform.WINDOWS;
782
+ }
783
+
784
+ static isLinuxPlatform() {
785
+ return this.getEnvironmentPlatform() === Platform.LINUX;
786
+ }
787
+
788
+ static isMacPlatform() {
789
+ return this.getEnvironmentPlatform() === Platform.MACOS;
790
+ }
791
+
792
+ static isLinuxRootUser() {
793
+ return process.getuid() === Constants.LINUX_ROOT_USER_GUID;
794
+ }
795
+
796
+ static getUserRootDirectory() {
797
+ return !this.isWindowsPlatform ? this.getUserHomeDirOnUnix() : this.getUserHomeDirOnWindows();
798
+ }
799
+
800
+ static getUserHomeDirOnWindows() {
801
+ return this.getEnvironmentVariable(Constants.ENVIRONMENT.LOCAL_APPLICATION_DATA);
802
+ }
803
+
804
+ static getUserHomeDirOnUnix() {
805
+ if (this.isWindowsPlatform()) {
806
+ throw PersistenceError.createNotSupportedError("Getting the user home directory for unix is not supported in windows");
1115
807
  }
1116
- };
1117
808
 
1118
- _proto["delete"] = function _delete() {
1119
- try {
1120
- var _this6 = this;
1121
-
1122
- return Promise.resolve(_catch(function () {
1123
- return Promise.resolve(_this6.filePersistence["delete"]()).then(function () {
1124
- return Promise.resolve(keytar.deletePassword(_this6.serviceName, _this6.accountName));
1125
- });
1126
- }, function (err) {
1127
- throw PersistenceError.createLibSecretError(err.message);
1128
- }));
1129
- } catch (e) {
1130
- return Promise.reject(e);
809
+ if (!msalCommon.StringUtils.isEmpty(this.homeEnvVar)) {
810
+ return this.homeEnvVar;
1131
811
  }
1132
- };
1133
812
 
1134
- _proto.reloadNecessary = function reloadNecessary(lastSync) {
1135
- try {
1136
- var _this8 = this;
813
+ let username = null;
1137
814
 
1138
- return Promise.resolve(_this8.filePersistence.reloadNecessary(lastSync));
1139
- } catch (e) {
1140
- return Promise.reject(e);
815
+ if (!msalCommon.StringUtils.isEmpty(this.lognameEnvVar)) {
816
+ username = this.lognameEnvVar;
817
+ } else if (!msalCommon.StringUtils.isEmpty(this.userEnvVar)) {
818
+ username = this.userEnvVar;
819
+ } else if (!msalCommon.StringUtils.isEmpty(this.lnameEnvVar)) {
820
+ username = this.lnameEnvVar;
821
+ } else if (!msalCommon.StringUtils.isEmpty(this.usernameEnvVar)) {
822
+ username = this.usernameEnvVar;
1141
823
  }
1142
- };
1143
824
 
1144
- _proto.getFilePath = function getFilePath() {
1145
- return this.filePersistence.getFilePath();
1146
- };
825
+ if (this.isMacPlatform()) {
826
+ return !msalCommon.StringUtils.isEmpty(username) ? path__default.join("/Users", username) : null;
827
+ } else if (this.isLinuxPlatform()) {
828
+ if (this.isLinuxRootUser()) {
829
+ return "/root";
830
+ } else {
831
+ return !msalCommon.StringUtils.isEmpty(username) ? path__default.join("/home", username) : null;
832
+ }
833
+ } else {
834
+ throw PersistenceError.createNotSupportedError("Getting the user home directory for unix is not supported in windows");
835
+ }
836
+ }
1147
837
 
1148
- _proto.getLogger = function getLogger() {
1149
- return this.filePersistence.getLogger();
1150
- };
838
+ }
1151
839
 
1152
- return LibSecretPersistence;
1153
- }();
840
+ /*
841
+ * Copyright (c) Microsoft Corporation. All rights reserved.
842
+ * Licensed under the MIT License.
843
+ */
844
+ class PersistenceCreator {
845
+ static async createPersistence(config) {
846
+ let peristence; // On Windows, uses a DPAPI encrypted file
847
+
848
+ if (Environment.isWindowsPlatform()) {
849
+ if (!config.cachePath || !config.dataProtectionScope) {
850
+ throw PersistenceError.createPersistenceNotValidatedError("Cache path and/or data protection scope not provided for the FilePersistenceWithDataProtection cache plugin");
851
+ }
852
+
853
+ peristence = await FilePersistenceWithDataProtection.create(config.cachePath, exports.DataProtectionScope.CurrentUser, undefined, config.loggerOptions);
854
+ } // On Mac, uses keychain.
855
+ else if (Environment.isMacPlatform()) {
856
+ if (!config.cachePath || !config.serviceName || !config.accountName) {
857
+ throw PersistenceError.createPersistenceNotValidatedError("Cache path, service name and/or account name not provided for the KeychainPersistence cache plugin");
858
+ }
859
+
860
+ peristence = await KeychainPersistence.create(config.cachePath, config.serviceName, config.accountName, config.loggerOptions);
861
+ } // On Linux, uses libsecret to store to secret service. Libsecret has to be installed.
862
+ else if (Environment.isLinuxPlatform()) {
863
+ if (!config.cachePath || !config.serviceName || !config.accountName) {
864
+ throw PersistenceError.createPersistenceNotValidatedError("Cache path, service name and/or account name not provided for the LibSecretPersistence cache plugin");
865
+ }
866
+
867
+ peristence = await LibSecretPersistence.create(config.cachePath, config.serviceName, config.accountName, config.loggerOptions);
868
+ } else {
869
+ throw PersistenceError.createNotSupportedError("The current environment is not supported by msal-node-extensions yet.");
870
+ } // Initially suppress the error thrown during persistence verification to allow us to fallback to plain text
871
+
872
+
873
+ const isPersistenceVerified = await peristence.verifyPersistence().catch(() => false);
874
+
875
+ if (!isPersistenceVerified) {
876
+ if (Environment.isLinuxPlatform() && config.usePlaintextFileOnLinux) {
877
+ if (!config.cachePath) {
878
+ throw PersistenceError.createPersistenceNotValidatedError("Cache path not provided for the FilePersistence cache plugin");
879
+ }
880
+
881
+ peristence = await FilePersistence.create(config.cachePath, config.loggerOptions);
882
+ const isFilePersistenceVerified = await peristence.verifyPersistence();
883
+
884
+ if (isFilePersistenceVerified) {
885
+ return peristence;
886
+ }
887
+ }
888
+
889
+ throw PersistenceError.createPersistenceNotVerifiedError("Persistence could not be verified");
890
+ }
891
+
892
+ return peristence;
893
+ }
894
+
895
+ }
1154
896
 
897
+ exports.Environment = Environment;
1155
898
  exports.FilePersistence = FilePersistence;
1156
899
  exports.FilePersistenceWithDataProtection = FilePersistenceWithDataProtection;
1157
900
  exports.KeychainPersistence = KeychainPersistence;
1158
901
  exports.LibSecretPersistence = LibSecretPersistence;
1159
902
  exports.PersistenceCachePlugin = PersistenceCachePlugin;
903
+ exports.PersistenceCreator = PersistenceCreator;
1160
904
  //# sourceMappingURL=msal-node-extensions.cjs.development.js.map