@azure/msal-node-extensions 1.0.0-alpha.9 → 1.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/README.md +174 -8
  2. package/bin/arm64/dpapi.node +0 -0
  3. package/bin/ia32/dpapi.node +0 -0
  4. package/bin/x64/dpapi.node +0 -0
  5. package/dist/{dpapi-addon/Dpapi.d.ts → Dpapi.d.ts} +4 -4
  6. package/dist/Dpapi.esm.js +24 -0
  7. package/dist/Dpapi.esm.js.map +1 -0
  8. package/dist/Dpapi.js +24 -0
  9. package/dist/Dpapi.js.map +1 -0
  10. package/dist/broker/NativeBrokerPlugin.d.ts +20 -0
  11. package/dist/broker/NativeBrokerPlugin.esm.js +408 -0
  12. package/dist/broker/NativeBrokerPlugin.esm.js.map +1 -0
  13. package/dist/broker/NativeBrokerPlugin.js +410 -0
  14. package/dist/broker/NativeBrokerPlugin.js.map +1 -0
  15. package/dist/error/NativeAuthError.d.ts +6 -0
  16. package/dist/error/NativeAuthError.esm.js +20 -0
  17. package/dist/error/NativeAuthError.esm.js.map +1 -0
  18. package/dist/error/NativeAuthError.js +22 -0
  19. package/dist/error/NativeAuthError.js.map +1 -0
  20. package/dist/error/PersistenceError.esm.js +89 -0
  21. package/dist/error/PersistenceError.esm.js.map +1 -0
  22. package/{src/error/PersistenceError.ts → dist/error/PersistenceError.js} +23 -33
  23. package/dist/error/PersistenceError.js.map +1 -0
  24. package/dist/index.d.ts +1 -0
  25. package/dist/index.esm.js +12 -0
  26. package/dist/index.esm.js.map +1 -0
  27. package/dist/index.js +24 -6
  28. package/dist/index.js.map +1 -0
  29. package/dist/lock/CrossPlatformLock.esm.js +94 -0
  30. package/dist/lock/CrossPlatformLock.esm.js.map +1 -0
  31. package/dist/lock/CrossPlatformLock.js +96 -0
  32. package/dist/lock/CrossPlatformLock.js.map +1 -0
  33. package/dist/lock/CrossPlatformLockOptions.d.ts +1 -1
  34. package/dist/packageMetadata.d.ts +2 -0
  35. package/dist/packageMetadata.esm.js +8 -0
  36. package/dist/packageMetadata.esm.js.map +1 -0
  37. package/dist/packageMetadata.js +11 -0
  38. package/dist/packageMetadata.js.map +1 -0
  39. package/{src/persistence/BasePersistence.ts → dist/persistence/BasePersistence.esm.js} +18 -23
  40. package/dist/persistence/BasePersistence.esm.js.map +1 -0
  41. package/dist/persistence/BasePersistence.js +38 -0
  42. package/dist/persistence/BasePersistence.js.map +1 -0
  43. package/dist/persistence/DataProtectionScope.d.ts +5 -4
  44. package/{src/persistence/DataProtectionScope.ts → dist/persistence/DataProtectionScope.esm.js} +9 -5
  45. package/dist/persistence/DataProtectionScope.esm.js.map +1 -0
  46. package/dist/persistence/DataProtectionScope.js +26 -0
  47. package/dist/persistence/DataProtectionScope.js.map +1 -0
  48. package/dist/persistence/FilePersistence.d.ts +1 -0
  49. package/dist/persistence/FilePersistence.esm.js +173 -0
  50. package/dist/persistence/FilePersistence.esm.js.map +1 -0
  51. package/dist/persistence/FilePersistence.js +175 -0
  52. package/dist/persistence/FilePersistence.js.map +1 -0
  53. package/dist/persistence/FilePersistenceWithDataProtection.esm.js +84 -0
  54. package/dist/persistence/FilePersistenceWithDataProtection.esm.js.map +1 -0
  55. package/dist/persistence/FilePersistenceWithDataProtection.js +86 -0
  56. package/dist/persistence/FilePersistenceWithDataProtection.js.map +1 -0
  57. package/dist/persistence/IPersistenceConfiguration.d.ts +2 -0
  58. package/dist/persistence/KeychainPersistence.d.ts +2 -2
  59. package/dist/persistence/KeychainPersistence.esm.js +90 -0
  60. package/dist/persistence/KeychainPersistence.esm.js.map +1 -0
  61. package/dist/persistence/KeychainPersistence.js +92 -0
  62. package/dist/persistence/KeychainPersistence.js.map +1 -0
  63. package/dist/persistence/LibSecretPersistence.d.ts +2 -2
  64. package/dist/persistence/LibSecretPersistence.esm.js +91 -0
  65. package/dist/persistence/LibSecretPersistence.esm.js.map +1 -0
  66. package/dist/persistence/LibSecretPersistence.js +93 -0
  67. package/dist/persistence/LibSecretPersistence.js.map +1 -0
  68. package/dist/persistence/PersistenceCachePlugin.d.ts +1 -1
  69. package/{src/persistence/PersistenceCachePlugin.ts → dist/persistence/PersistenceCachePlugin.esm.js} +27 -34
  70. package/dist/persistence/PersistenceCachePlugin.esm.js.map +1 -0
  71. package/dist/persistence/PersistenceCachePlugin.js +101 -0
  72. package/dist/persistence/PersistenceCachePlugin.js.map +1 -0
  73. package/dist/persistence/PersistenceCreator.d.ts +1 -1
  74. package/dist/persistence/PersistenceCreator.esm.js +63 -0
  75. package/dist/persistence/PersistenceCreator.esm.js.map +1 -0
  76. package/dist/persistence/PersistenceCreator.js +65 -0
  77. package/dist/persistence/PersistenceCreator.js.map +1 -0
  78. package/dist/utils/Constants.d.ts +12 -5
  79. package/{src/utils/Constants.ts → dist/utils/Constants.esm.js} +17 -17
  80. package/dist/utils/Constants.esm.js.map +1 -0
  81. package/dist/utils/Constants.js +66 -0
  82. package/dist/utils/Constants.js.map +1 -0
  83. package/dist/utils/Environment.d.ts +1 -1
  84. package/{src/utils/Environment.ts → dist/utils/Environment.esm.js} +44 -49
  85. package/dist/utils/Environment.esm.js.map +1 -0
  86. package/dist/utils/Environment.js +96 -0
  87. package/dist/utils/Environment.js.map +1 -0
  88. package/dist/utils/TypeGuards.d.ts +5 -0
  89. package/dist/utils/TypeGuards.esm.js +16 -0
  90. package/dist/utils/TypeGuards.esm.js.map +1 -0
  91. package/dist/utils/TypeGuards.js +18 -0
  92. package/dist/utils/TypeGuards.js.map +1 -0
  93. package/package.json +70 -52
  94. package/CHANGELOG.json +0 -167
  95. package/binding.gyp +0 -29
  96. package/changelog.md +0 -77
  97. package/dist/msal-node-extensions.cjs.development.js +0 -902
  98. package/dist/msal-node-extensions.cjs.development.js.map +0 -1
  99. package/dist/msal-node-extensions.cjs.production.min.js +0 -2
  100. package/dist/msal-node-extensions.cjs.production.min.js.map +0 -1
  101. package/dist/msal-node-extensions.esm.js +0 -902
  102. package/dist/msal-node-extensions.esm.js.map +0 -1
  103. package/src/dpapi-addon/Dpapi.ts +0 -12
  104. package/src/dpapi-addon/dpapi_addon.h +0 -6
  105. package/src/dpapi-addon/dpapi_not_supported.cpp +0 -19
  106. package/src/dpapi-addon/dpapi_win.cpp +0 -114
  107. package/src/dpapi-addon/main.cpp +0 -32
  108. package/src/index.ts +0 -16
  109. package/src/lock/CrossPlatformLock.ts +0 -89
  110. package/src/lock/CrossPlatformLockOptions.ts +0 -15
  111. package/src/persistence/FilePersistence.ts +0 -140
  112. package/src/persistence/FilePersistenceWithDataProtection.ts +0 -92
  113. package/src/persistence/IPersistence.ts +0 -17
  114. package/src/persistence/IPersistenceConfiguration.ts +0 -14
  115. package/src/persistence/KeychainPersistence.ts +0 -86
  116. package/src/persistence/LibSecretPersistence.ts +0 -87
  117. package/src/persistence/PersistenceCreator.ts +0 -73
@@ -1,902 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
6
-
7
- var fs = require('fs');
8
- var process$1 = require('process');
9
- var path = require('path');
10
- var path__default = _interopDefault(path);
11
- var msalCommon = require('@azure/msal-common');
12
- var keytar = require('keytar');
13
-
14
- /*
15
- * Copyright (c) Microsoft Corporation. All rights reserved.
16
- * Licensed under the MIT License.
17
- */
18
- const Constants = {
19
- /**
20
- * An existing file was the target of an operation that required that the target not exist
21
- */
22
- EEXIST_ERROR: "EEXIST",
23
-
24
- /**
25
- * No such file or directory: Commonly raised by fs operations to indicate that a component
26
- * of the specified pathname does not exist. No entity (file or directory) could be found
27
- * by the given path
28
- */
29
- ENOENT_ERROR: "ENOENT",
30
-
31
- /**
32
- * Operation not permitted. An attempt was made to perform an operation that requires
33
- * elevated privileges.
34
- */
35
- EPERM_ERROR: "EPERM",
36
-
37
- /**
38
- * Default service name for using MSAL Keytar
39
- */
40
- DEFAULT_SERVICE_NAME: "msal-node-extensions",
41
-
42
- /**
43
- * Test data used to verify underlying persistence mechanism
44
- */
45
- PERSISTENCE_TEST_DATA: "Dummy data to verify underlying persistence mechanism",
46
-
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,
51
-
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;
68
-
69
- (function (Platform) {
70
- Platform["WINDOWS"] = "win32";
71
- Platform["LINUX"] = "linux";
72
- Platform["MACOS"] = "darwin";
73
- })(Platform || (Platform = {}));
74
-
75
- /*
76
- * Copyright (c) Microsoft Corporation. All rights reserved.
77
- * Licensed under the MIT License.
78
- */
79
-
80
- /**
81
- * Error thrown when trying to write MSAL cache to persistence.
82
- */
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";
91
- }
92
- /**
93
- * Error thrown when trying to access the file system.
94
- */
95
-
96
-
97
- static createFileSystemError(errorCode, errorMessage) {
98
- return new PersistenceError(errorCode, errorMessage);
99
- }
100
- /**
101
- * Error thrown when trying to write, load, or delete data from secret service on linux.
102
- * Libsecret is used to access secret service.
103
- */
104
-
105
-
106
- static createLibSecretError(errorMessage) {
107
- return new PersistenceError("GnomeKeyringError", errorMessage);
108
- }
109
- /**
110
- * Error thrown when trying to write, load, or delete data from keychain on macOs.
111
- */
112
-
113
-
114
- static createKeychainPersistenceError(errorMessage) {
115
- return new PersistenceError("KeychainError", errorMessage);
116
- }
117
- /**
118
- * Error thrown when trying to encrypt or decrypt data using DPAPI on Windows.
119
- */
120
-
121
-
122
- static createFilePersistenceWithDPAPIError(errorMessage) {
123
- return new PersistenceError("DPAPIEncryptedFileError", errorMessage);
124
- }
125
- /**
126
- * Error thrown when using the cross platform lock.
127
- */
128
-
129
-
130
- static createCrossPlatformLockError(errorMessage) {
131
- return new PersistenceError("CrossPlatformLockError", errorMessage);
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
- }
177
-
178
- }
179
-
180
- /*
181
- * Copyright (c) Microsoft Corporation. All rights reserved.
182
- * Licensed under the MIT License.
183
- */
184
- /**
185
- * Cross-process lock that works on all platforms.
186
- */
187
-
188
- class CrossPlatformLock {
189
- constructor(lockFilePath, logger, lockOptions) {
190
- this.lockFilePath = lockFilePath;
191
- this.retryNumber = lockOptions ? lockOptions.retryNumber : 500;
192
- this.retryDelay = lockOptions ? lockOptions.retryDelay : 100;
193
- this.logger = logger;
194
- }
195
- /**
196
- * Locks cache from read or writes by creating file with same path and name as
197
- * cache file but with .lockfile extension. If another process has already created
198
- * the lockfile, will back off and retry based on configuration settings set by CrossPlatformLockOptions
199
- */
200
-
201
-
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
- }
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");
223
- }
224
- /**
225
- * unlocks cache file by deleting .lockfile.
226
- */
227
-
228
-
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
- }
246
- }
247
- }
248
-
249
- sleep(ms) {
250
- return new Promise(resolve => {
251
- setTimeout(resolve, ms);
252
- });
253
- }
254
-
255
- }
256
-
257
- /*
258
- * Copyright (c) Microsoft Corporation. All rights reserved.
259
- * Licensed under the MIT License.
260
- */
261
- /**
262
- * MSAL cache plugin which enables callers to write the MSAL cache to disk on Windows,
263
- * macOs, and Linux.
264
- *
265
- * - Persistence can be one of:
266
- * - FilePersistence: Writes and reads from an unencrypted file. Can be used on Windows,
267
- * macOs, or Linux.
268
- * - FilePersistenceWithDataProtection: Used on Windows, writes and reads from file encrypted
269
- * with windows dpapi-addon.
270
- * - KeychainPersistence: Used on macOs, writes and reads from keychain.
271
- * - LibSecretPersistence: Used on linux, writes and reads from secret service API. Requires
272
- * libsecret be installed.
273
- */
274
-
275
- class PersistenceCachePlugin {
276
- constructor(persistence, lockOptions) {
277
- this.persistence = persistence; // initialize logger
278
-
279
- this.logger = persistence.getLogger(); // create file lock
280
-
281
- this.lockFilePath = `${this.persistence.getFilePath()}.lockfile`;
282
- this.crossPlatformLock = new CrossPlatformLock(this.lockFilePath, this.logger, lockOptions); // initialize default values
283
-
284
- this.lastSync = 0;
285
- this.currentCache = null;
286
- }
287
- /**
288
- * Reads from storage and saves an in-memory copy. If persistence has not been updated
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().
294
- */
295
-
296
-
297
- async beforeCacheAccess(cacheContext) {
298
- this.logger.info("Executing before cache access");
299
- const reloadNecessary = await this.persistence.reloadNecessary(this.lastSync);
300
-
301
- if (!reloadNecessary && this.currentCache !== null) {
302
- if (cacheContext.cacheHasChanged) {
303
- this.logger.verbose("Cache context has changed");
304
- await this.crossPlatformLock.lock();
305
- }
306
-
307
- return;
308
- }
309
-
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
- }
324
- }
325
- }
326
- /**
327
- * Writes to storage if MSAL in memory copy of cache has been changed.
328
- */
329
-
330
-
331
- async afterCacheAccess(cacheContext) {
332
- this.logger.info("Executing after cache access");
333
-
334
- try {
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 because it cannot be started over SSH.");
365
- }
366
-
367
- if (retrievedDummyData !== Constants.PERSISTENCE_TEST_DATA) {
368
- throw PersistenceError.createCachePersistenceError(`Persistence check failed. Data written ${Constants.PERSISTENCE_TEST_DATA} is different from data read ${retrievedDummyData}`);
369
- }
370
-
371
- await persistenceValidator.delete();
372
- return true;
373
- } catch (e) {
374
- throw PersistenceError.createCachePersistenceError(`Verifing persistence failed with the error: ${e}`);
375
- }
376
- }
377
-
378
- }
379
-
380
- /*
381
- * Copyright (c) Microsoft Corporation. All rights reserved.
382
- * Licensed under the MIT License.
383
- */
384
- /**
385
- * Reads and writes data to file specified by file location. File contents are not
386
- * encrypted.
387
- *
388
- * If file or directory has not been created, it FilePersistence.create() will create
389
- * file and any directories in the path recursively.
390
- */
391
-
392
- class FilePersistence extends BasePersistence {
393
- static async create(fileLocation, loggerOptions) {
394
- const filePersistence = new FilePersistence();
395
- filePersistence.filePath = fileLocation;
396
- filePersistence.logger = new msalCommon.Logger(loggerOptions || FilePersistence.createDefaultLoggerOptions());
397
- await filePersistence.createCacheFile();
398
- return filePersistence;
399
- }
400
-
401
- async save(contents) {
402
- try {
403
- await fs.promises.writeFile(this.getFilePath(), contents, "utf-8");
404
- } catch (err) {
405
- throw PersistenceError.createFileSystemError(err.code, err.message);
406
- }
407
- }
408
-
409
- async saveBuffer(contents) {
410
- try {
411
- await fs.promises.writeFile(this.getFilePath(), contents);
412
- } catch (err) {
413
- throw PersistenceError.createFileSystemError(err.code, err.message);
414
- }
415
- }
416
-
417
- async load() {
418
- try {
419
- return await fs.promises.readFile(this.getFilePath(), "utf-8");
420
- } catch (err) {
421
- throw PersistenceError.createFileSystemError(err.code, err.message);
422
- }
423
- }
424
-
425
- async loadBuffer() {
426
- try {
427
- return await fs.promises.readFile(this.getFilePath());
428
- } catch (err) {
429
- throw PersistenceError.createFileSystemError(err.code, err.message);
430
- }
431
- }
432
-
433
- async delete() {
434
- try {
435
- await fs.promises.unlink(this.getFilePath());
436
- return true;
437
- } catch (err) {
438
- if (err.code === Constants.ENOENT_ERROR) {
439
- // file does not exist, so it was not deleted
440
- this.logger.warning("Cache file does not exist, so it could not be deleted");
441
- return false;
442
- }
443
-
444
- throw PersistenceError.createFileSystemError(err.code, err.message);
445
- }
446
- }
447
-
448
- getFilePath() {
449
- return this.filePath;
450
- }
451
-
452
- async reloadNecessary(lastSync) {
453
- return lastSync < (await this.timeLastModified());
454
- }
455
-
456
- getLogger() {
457
- return this.logger;
458
- }
459
-
460
- createForPersistenceValidation() {
461
- const testCacheFileLocation = `${path.dirname(this.filePath)}/test.cache`;
462
- return FilePersistence.create(testCacheFileLocation);
463
- }
464
-
465
- static createDefaultLoggerOptions() {
466
- return {
467
- loggerCallback: () => {// allow users to not set loggerCallback
468
- },
469
- piiLoggingEnabled: false,
470
- logLevel: msalCommon.LogLevel.Info
471
- };
472
- }
473
-
474
- async timeLastModified() {
475
- try {
476
- const stats = await fs.promises.stat(this.filePath);
477
- return stats.mtime.getTime();
478
- } catch (err) {
479
- if (err.code === Constants.ENOENT_ERROR) {
480
- // file does not exist, so it's never been modified
481
- this.logger.verbose("Cache file does not exist");
482
- return 0;
483
- }
484
-
485
- throw PersistenceError.createFileSystemError(err.code, err.message);
486
- }
487
- }
488
-
489
- async createCacheFile() {
490
- await this.createFileDirectory(); // File is created only if it does not exist
491
-
492
- const fileHandle = await fs.promises.open(this.filePath, "a");
493
- await fileHandle.close();
494
- this.logger.info(`File created at ${this.filePath}`);
495
- }
496
-
497
- async createFileDirectory() {
498
- try {
499
- await fs.promises.mkdir(path.dirname(this.filePath), {
500
- recursive: true
501
- });
502
- } catch (err) {
503
- if (err.code === Constants.EEXIST_ERROR) {
504
- this.logger.info(`Directory ${path.dirname(this.filePath)} already exists`);
505
- } else {
506
- throw PersistenceError.createFileSystemError(err.code, err.message);
507
- }
508
- }
509
- }
510
-
511
- }
512
-
513
- /*
514
- * Copyright (c) Microsoft Corporation. All rights reserved.
515
- * Licensed under the MIT License.
516
- */
517
-
518
- /* eslint-disable-next-line @typescript-eslint/no-var-requires, no-var */
519
- var Dpapi = /*#__PURE__*/require("bindings")("dpapi");
520
-
521
- /*
522
- * Copyright (c) Microsoft Corporation. All rights reserved.
523
- * Licensed under the MIT License.
524
- */
525
-
526
- (function (DataProtectionScope) {
527
- DataProtectionScope["CurrentUser"] = "CurrentUser";
528
- DataProtectionScope["LocalMachine"] = "LocalMachine";
529
- })(exports.DataProtectionScope || (exports.DataProtectionScope = {}));
530
-
531
- /*
532
- * Copyright (c) Microsoft Corporation. All rights reserved.
533
- * Licensed under the MIT License.
534
- */
535
- /**
536
- * Uses CryptProtectData and CryptUnprotectData on Windows to encrypt and decrypt file contents.
537
- *
538
- * scope: Scope of the data protection. Either local user or the current machine
539
- * optionalEntropy: Password or other additional entropy used to encrypt the data
540
- */
541
-
542
- class FilePersistenceWithDataProtection extends BasePersistence {
543
- constructor(scope, optionalEntropy) {
544
- super();
545
- this.scope = scope;
546
- this.optionalEntropy = optionalEntropy ? Buffer.from(optionalEntropy, "utf-8") : null;
547
- }
548
-
549
- static async create(fileLocation, scope, optionalEntropy, loggerOptions) {
550
- const persistence = new FilePersistenceWithDataProtection(scope, optionalEntropy);
551
- persistence.filePersistence = await FilePersistence.create(fileLocation, loggerOptions);
552
- return persistence;
553
- }
554
-
555
- async save(contents) {
556
- try {
557
- const encryptedContents = Dpapi.protectData(Buffer.from(contents, "utf-8"), this.optionalEntropy, this.scope.toString());
558
- await this.filePersistence.saveBuffer(encryptedContents);
559
- } catch (err) {
560
- throw PersistenceError.createFilePersistenceWithDPAPIError(err.message);
561
- }
562
- }
563
-
564
- async load() {
565
- try {
566
- const encryptedContents = await this.filePersistence.loadBuffer();
567
-
568
- if (typeof encryptedContents === "undefined" || !encryptedContents || 0 === encryptedContents.length) {
569
- this.filePersistence.getLogger().info("Encrypted contents loaded from file were null or empty");
570
- return null;
571
- }
572
-
573
- return Dpapi.unprotectData(encryptedContents, this.optionalEntropy, this.scope.toString()).toString();
574
- } catch (err) {
575
- throw PersistenceError.createFilePersistenceWithDPAPIError(err.message);
576
- }
577
- }
578
-
579
- async delete() {
580
- return this.filePersistence.delete();
581
- }
582
-
583
- async reloadNecessary(lastSync) {
584
- return this.filePersistence.reloadNecessary(lastSync);
585
- }
586
-
587
- getFilePath() {
588
- return this.filePersistence.getFilePath();
589
- }
590
-
591
- getLogger() {
592
- return this.filePersistence.getLogger();
593
- }
594
-
595
- createForPersistenceValidation() {
596
- const testCacheFileLocation = `${path.dirname(this.filePersistence.getFilePath())}/test.cache`;
597
- return FilePersistenceWithDataProtection.create(testCacheFileLocation, exports.DataProtectionScope.CurrentUser);
598
- }
599
-
600
- }
601
-
602
- /*
603
- * Copyright (c) Microsoft Corporation. All rights reserved.
604
- * Licensed under the MIT License.
605
- */
606
- /**
607
- * Uses reads and writes passwords to macOS keychain
608
- *
609
- * serviceName: Identifier used as key for whatever value is stored
610
- * accountName: Account under which password should be stored
611
- */
612
-
613
- class KeychainPersistence extends BasePersistence {
614
- constructor(serviceName, accountName) {
615
- super();
616
- this.serviceName = serviceName;
617
- this.accountName = accountName;
618
- }
619
-
620
- static async create(fileLocation, serviceName, accountName, loggerOptions) {
621
- const persistence = new KeychainPersistence(serviceName, accountName);
622
- persistence.filePersistence = await FilePersistence.create(fileLocation, loggerOptions);
623
- return persistence;
624
- }
625
-
626
- async save(contents) {
627
- try {
628
- await keytar.setPassword(this.serviceName, this.accountName, contents);
629
- } catch (err) {
630
- throw PersistenceError.createKeychainPersistenceError(err.message);
631
- } // Write dummy data to update file mtime
632
-
633
-
634
- await this.filePersistence.save("{}");
635
- }
636
-
637
- async load() {
638
- try {
639
- return await keytar.getPassword(this.serviceName, this.accountName);
640
- } catch (err) {
641
- throw PersistenceError.createKeychainPersistenceError(err.message);
642
- }
643
- }
644
-
645
- async delete() {
646
- try {
647
- await this.filePersistence.delete();
648
- return await keytar.deletePassword(this.serviceName, this.accountName);
649
- } catch (err) {
650
- throw PersistenceError.createKeychainPersistenceError(err.message);
651
- }
652
- }
653
-
654
- async reloadNecessary(lastSync) {
655
- return this.filePersistence.reloadNecessary(lastSync);
656
- }
657
-
658
- getFilePath() {
659
- return this.filePersistence.getFilePath();
660
- }
661
-
662
- getLogger() {
663
- return this.filePersistence.getLogger();
664
- }
665
-
666
- createForPersistenceValidation() {
667
- const testCacheFileLocation = `${path.dirname(this.filePersistence.getFilePath())}/test.cache`;
668
- return KeychainPersistence.create(testCacheFileLocation, "persistenceValidationServiceName", "persistencValidationAccountName");
669
- }
670
-
671
- }
672
-
673
- /*
674
- * Copyright (c) Microsoft Corporation. All rights reserved.
675
- * Licensed under the MIT License.
676
- */
677
- /**
678
- * Uses reads and writes passwords to Secret Service API/libsecret. Requires libsecret
679
- * to be installed.
680
- *
681
- * serviceName: Identifier used as key for whatever value is stored
682
- * accountName: Account under which password should be stored
683
- */
684
-
685
- class LibSecretPersistence extends BasePersistence {
686
- constructor(serviceName, accountName) {
687
- super();
688
- this.serviceName = serviceName;
689
- this.accountName = accountName;
690
- }
691
-
692
- static async create(fileLocation, serviceName, accountName, loggerOptions) {
693
- const persistence = new LibSecretPersistence(serviceName, accountName);
694
- persistence.filePersistence = await FilePersistence.create(fileLocation, loggerOptions);
695
- return persistence;
696
- }
697
-
698
- async save(contents) {
699
- try {
700
- await keytar.setPassword(this.serviceName, this.accountName, contents);
701
- } catch (err) {
702
- throw PersistenceError.createLibSecretError(err.message);
703
- } // Write dummy data to update file mtime
704
-
705
-
706
- await this.filePersistence.save("{}");
707
- }
708
-
709
- async load() {
710
- try {
711
- return await keytar.getPassword(this.serviceName, this.accountName);
712
- } catch (err) {
713
- throw PersistenceError.createLibSecretError(err.message);
714
- }
715
- }
716
-
717
- async delete() {
718
- try {
719
- await this.filePersistence.delete();
720
- return await keytar.deletePassword(this.serviceName, this.accountName);
721
- } catch (err) {
722
- throw PersistenceError.createLibSecretError(err.message);
723
- }
724
- }
725
-
726
- async reloadNecessary(lastSync) {
727
- return this.filePersistence.reloadNecessary(lastSync);
728
- }
729
-
730
- getFilePath() {
731
- return this.filePersistence.getFilePath();
732
- }
733
-
734
- getLogger() {
735
- return this.filePersistence.getLogger();
736
- }
737
-
738
- createForPersistenceValidation() {
739
- const testCacheFileLocation = `${path.dirname(this.filePersistence.getFilePath())}/test.cache`;
740
- return LibSecretPersistence.create(testCacheFileLocation, "persistenceValidationServiceName", "persistencValidationAccountName");
741
- }
742
-
743
- }
744
-
745
- /*
746
- * Copyright (c) Microsoft Corporation. All rights reserved.
747
- * Licensed under the MIT License.
748
- */
749
- class Environment {
750
- static get homeEnvVar() {
751
- return this.getEnvironmentVariable(Constants.ENVIRONMENT.HOME);
752
- }
753
-
754
- static get lognameEnvVar() {
755
- return this.getEnvironmentVariable(Constants.ENVIRONMENT.LOGNAME);
756
- }
757
-
758
- static get userEnvVar() {
759
- return this.getEnvironmentVariable(Constants.ENVIRONMENT.USER);
760
- }
761
-
762
- static get lnameEnvVar() {
763
- return this.getEnvironmentVariable(Constants.ENVIRONMENT.LNAME);
764
- }
765
-
766
- static get usernameEnvVar() {
767
- return this.getEnvironmentVariable(Constants.ENVIRONMENT.USERNAME);
768
- }
769
-
770
- static getEnvironmentVariable(name) {
771
- return process.env[name];
772
- }
773
-
774
- static getEnvironmentPlatform() {
775
- return process.platform;
776
- }
777
-
778
- static isWindowsPlatform() {
779
- return this.getEnvironmentPlatform() === Platform.WINDOWS;
780
- }
781
-
782
- static isLinuxPlatform() {
783
- return this.getEnvironmentPlatform() === Platform.LINUX;
784
- }
785
-
786
- static isMacPlatform() {
787
- return this.getEnvironmentPlatform() === Platform.MACOS;
788
- }
789
-
790
- static isLinuxRootUser() {
791
- return process.getuid() == Constants.LINUX_ROOT_USER_GUID;
792
- }
793
-
794
- static getUserRootDirectory() {
795
- return !this.isWindowsPlatform ? this.getUserHomeDirOnUnix() : this.getUserHomeDirOnWindows();
796
- }
797
-
798
- static getUserHomeDirOnWindows() {
799
- return this.getEnvironmentVariable(Constants.ENVIRONMENT.LOCAL_APPLICATION_DATA);
800
- }
801
-
802
- static getUserHomeDirOnUnix() {
803
- if (this.isWindowsPlatform()) {
804
- throw PersistenceError.createNotSupportedError("Getting the user home directory for unix is not supported in windows");
805
- }
806
-
807
- if (!msalCommon.StringUtils.isEmpty(this.homeEnvVar)) {
808
- return this.homeEnvVar;
809
- }
810
-
811
- let username = null;
812
-
813
- if (!msalCommon.StringUtils.isEmpty(this.lognameEnvVar)) {
814
- username = this.lognameEnvVar;
815
- } else if (!msalCommon.StringUtils.isEmpty(this.userEnvVar)) {
816
- username = this.userEnvVar;
817
- } else if (!msalCommon.StringUtils.isEmpty(this.lnameEnvVar)) {
818
- username = this.lnameEnvVar;
819
- } else if (!msalCommon.StringUtils.isEmpty(this.usernameEnvVar)) {
820
- username = this.usernameEnvVar;
821
- }
822
-
823
- if (this.isMacPlatform()) {
824
- return !msalCommon.StringUtils.isEmpty(username) ? path__default.join("/Users", username) : null;
825
- } else if (this.isLinuxPlatform()) {
826
- if (this.isLinuxRootUser()) {
827
- return "/root";
828
- } else {
829
- return !msalCommon.StringUtils.isEmpty(username) ? path__default.join("/home", username) : null;
830
- }
831
- } else {
832
- throw PersistenceError.createNotSupportedError("Getting the user home directory for unix is not supported in windows");
833
- }
834
- }
835
-
836
- }
837
-
838
- /*
839
- * Copyright (c) Microsoft Corporation. All rights reserved.
840
- * Licensed under the MIT License.
841
- */
842
- class PersistenceCreator {
843
- static async createPersistence(config) {
844
- let peristence; // On Windows, uses a DPAPI encrypted file
845
-
846
- if (Environment.isWindowsPlatform()) {
847
- if (!config.cachePath || !config.dataProtectionScope) {
848
- throw PersistenceError.createPersistenceNotValidatedError(`Cache path and/or data protection scope not provided for the FilePersistenceWithDataProtection cache plugin`);
849
- }
850
-
851
- peristence = await FilePersistenceWithDataProtection.create(config.cachePath, exports.DataProtectionScope.CurrentUser);
852
- } // On Mac, uses keychain.
853
- else if (Environment.isMacPlatform()) {
854
- if (!config.cachePath || !config.serviceName || !config.accountName) {
855
- throw PersistenceError.createPersistenceNotValidatedError(`Cache path, service name and/or account name not provided for the KeychainPersistence cache plugin`);
856
- }
857
-
858
- peristence = await KeychainPersistence.create(config.cachePath, config.serviceName, config.accountName);
859
- } // On Linux, uses libsecret to store to secret service. Libsecret has to be installed.
860
- else if (Environment.isLinuxPlatform()) {
861
- if (!config.cachePath || !config.serviceName || !config.accountName) {
862
- throw PersistenceError.createPersistenceNotValidatedError(`Cache path, service name and/or account name not provided for the LibSecretPersistence cache plugin`);
863
- }
864
-
865
- peristence = await LibSecretPersistence.create(config.cachePath, config.serviceName, config.accountName);
866
- } else {
867
- throw PersistenceError.createNotSupportedError("The current environment is not supported by msal-node-extensions yet.");
868
- } // Initially suppress the error thrown during persistence verification to allow us to fallback to plain text
869
-
870
-
871
- const isPersistenceVerified = await peristence.verifyPersistence().catch(() => false);
872
-
873
- if (!isPersistenceVerified) {
874
- if (Environment.isLinuxPlatform() && config.usePlaintextFileOnLinux) {
875
- if (!config.cachePath) {
876
- throw PersistenceError.createPersistenceNotValidatedError(`Cache path not provided for the FilePersistence cache plugin`);
877
- }
878
-
879
- peristence = await FilePersistence.create(config.cachePath);
880
- const isFilePersistenceVerified = await peristence.verifyPersistence();
881
-
882
- if (isFilePersistenceVerified) {
883
- return peristence;
884
- }
885
- }
886
-
887
- throw PersistenceError.createPersistenceNotVerifiedError("Persistence could not be verified");
888
- }
889
-
890
- return peristence;
891
- }
892
-
893
- }
894
-
895
- exports.Environment = Environment;
896
- exports.FilePersistence = FilePersistence;
897
- exports.FilePersistenceWithDataProtection = FilePersistenceWithDataProtection;
898
- exports.KeychainPersistence = KeychainPersistence;
899
- exports.LibSecretPersistence = LibSecretPersistence;
900
- exports.PersistenceCachePlugin = PersistenceCachePlugin;
901
- exports.PersistenceCreator = PersistenceCreator;
902
- //# sourceMappingURL=msal-node-extensions.cjs.development.js.map