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

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/CHANGELOG.json +261 -0
  2. package/CHANGELOG.md +111 -0
  3. package/LICENSE +21 -21
  4. package/README.md +193 -42
  5. package/binding.gyp +29 -0
  6. package/dist/error/PersistenceError.d.ts +32 -4
  7. package/dist/index.d.ts +3 -0
  8. package/dist/msal-node-extensions.cjs.development.js +615 -849
  9. package/dist/msal-node-extensions.cjs.development.js.map +1 -1
  10. package/dist/msal-node-extensions.cjs.production.min.js +1 -1
  11. package/dist/msal-node-extensions.cjs.production.min.js.map +1 -1
  12. package/dist/msal-node-extensions.esm.js +625 -864
  13. package/dist/msal-node-extensions.esm.js.map +1 -1
  14. package/dist/persistence/BasePersistence.d.ts +5 -0
  15. package/dist/persistence/FilePersistence.d.ts +4 -2
  16. package/dist/persistence/FilePersistenceWithDataProtection.d.ts +3 -1
  17. package/dist/persistence/IPersistence.d.ts +3 -1
  18. package/dist/persistence/IPersistenceConfiguration.d.ts +8 -0
  19. package/dist/persistence/KeychainPersistence.d.ts +3 -1
  20. package/dist/persistence/LibSecretPersistence.d.ts +3 -1
  21. package/dist/persistence/PersistenceCachePlugin.d.ts +11 -7
  22. package/dist/persistence/PersistenceCreator.d.ts +5 -0
  23. package/dist/utils/Constants.d.ts +31 -0
  24. package/dist/utils/Environment.d.ts +16 -0
  25. package/package.json +28 -15
  26. package/src/dpapi-addon/Dpapi.ts +17 -12
  27. package/src/dpapi-addon/dpapi_addon.h +6 -6
  28. package/src/dpapi-addon/dpapi_not_supported.cpp +19 -19
  29. package/src/dpapi-addon/dpapi_win.cpp +114 -114
  30. package/src/dpapi-addon/main.cpp +32 -32
  31. package/src/error/PersistenceError.ts +101 -65
  32. package/src/index.ts +16 -8
  33. package/src/lock/CrossPlatformLock.ts +89 -82
  34. package/src/lock/CrossPlatformLockOptions.ts +15 -15
  35. package/src/persistence/BasePersistence.ts +41 -0
  36. package/src/persistence/DataProtectionScope.ts +20 -20
  37. package/src/persistence/FilePersistence.ts +140 -134
  38. package/src/persistence/FilePersistenceWithDataProtection.ts +92 -84
  39. package/src/persistence/IPersistence.ts +17 -15
  40. package/src/persistence/IPersistenceConfiguration.ts +14 -0
  41. package/src/persistence/KeychainPersistence.ts +86 -78
  42. package/src/persistence/LibSecretPersistence.ts +87 -79
  43. package/src/persistence/PersistenceCachePlugin.ts +106 -96
  44. package/src/persistence/PersistenceCreator.ts +73 -0
  45. package/src/utils/Constants.ts +62 -24
  46. package/src/utils/Environment.ts +99 -0
  47. package/changelog.md +0 -8
@@ -1,96 +1,106 @@
1
- /*
2
- * Copyright (c) Microsoft Corporation. All rights reserved.
3
- * Licensed under the MIT License.
4
- */
5
-
6
- import { IPersistence } from "../persistence/IPersistence";
7
- import { CrossPlatformLock } from "../lock/CrossPlatformLock";
8
- import { CrossPlatformLockOptions } from "../lock/CrossPlatformLockOptions";
9
- import { pid } from "process";
10
- import { Logger } from "@azure/msal-common";
11
-
12
- /**
13
- * MSAL cache plugin which enables callers to write the MSAL cache to disk on Windows,
14
- * macOs, and Linux.
15
- *
16
- * - Persistence can be one of:
17
- * - FilePersistence: Writes and reads from an unencrypted file. Can be used on Windows,
18
- * macOs, or Linux.
19
- * - FilePersistenceWithDataProtection: Used on Windows, writes and reads from file encrypted
20
- * with windows dpapi-addon.
21
- * - KeychainPersistence: Used on macOs, writes and reads from keychain.
22
- * - LibSecretPersistence: Used on linux, writes and reads from secret service API. Requires
23
- * libsecret be installed.
24
- */
25
- export class PersistenceCachePlugin {
26
-
27
- public persistence: IPersistence;
28
- public lastSync: number;
29
- public currentCache: string;
30
- public lockFilePath: string;
31
-
32
- private crossPlatformLock: CrossPlatformLock;
33
-
34
- private logger: Logger;
35
-
36
- constructor(persistence: IPersistence, lockOptions?: CrossPlatformLockOptions) {
37
- this.persistence = persistence;
38
-
39
- // initialize logger
40
- this.logger = persistence.getLogger();
41
-
42
- // create file lock
43
- this.lockFilePath = `${this.persistence.getFilePath()}.lockfile`;
44
- this.crossPlatformLock = new CrossPlatformLock(this.lockFilePath, this.logger, lockOptions);
45
-
46
- // initialize default values
47
- this.lastSync = 0;
48
- this.currentCache = null;
49
- }
50
-
51
- /**
52
- * Reads from storage and avoids saves an in memory copy. If persistence has not been updated
53
- * since last time data was read, in memory copy is used.
54
- */
55
- public async readFromStorage(): Promise<string> {
56
- this.logger.info("Reading from storage");
57
- if (await this.persistence.reloadNecessary(this.lastSync) || this.currentCache == null) {
58
- try {
59
- this.logger.info(`Reload necessary. Last sync time: ${this.lastSync}`);
60
- await this.crossPlatformLock.lock();
61
-
62
- this.currentCache = await this.persistence.load();
63
- this.lastSync = new Date().getTime();
64
- this.logger.info(`Last sync time updated to: ${this.lastSync}`);
65
- } finally {
66
- await this.crossPlatformLock.unlock();
67
- this.logger.info(`Pid ${pid} Released lock`);
68
- }
69
- }
70
- return this.currentCache;
71
- }
72
-
73
- /**
74
- * Writes to storage. If persistence has not been updated since last time data was read,
75
- * reads and latest state from persistence, sends state via callback, and updates in memory copy.
76
- */
77
- public async writeToStorage(callback: (diskState: string) => string): Promise<void> {
78
- try {
79
- this.logger.info("Writing to storage");
80
- await this.crossPlatformLock.lock();
81
-
82
- if (await this.persistence.reloadNecessary(this.lastSync)) {
83
- this.logger.info(`Reload necessary. Last sync time: ${this.lastSync}`);
84
- this.currentCache = await this.persistence.load();
85
- this.lastSync = new Date().getTime();
86
- this.logger.info(`Last sync time updated to: ${this.lastSync}`);
87
- }
88
-
89
- this.currentCache = await callback(this.currentCache);
90
- await this.persistence.save(this.currentCache);
91
- } finally {
92
- await this.crossPlatformLock.unlock();
93
- this.logger.info(`Pid ${pid} Released lock`);
94
- }
95
- }
96
- }
1
+ /*
2
+ * Copyright (c) Microsoft Corporation. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+
6
+ import { IPersistence } from "./IPersistence";
7
+ import { CrossPlatformLock } from "../lock/CrossPlatformLock";
8
+ import { CrossPlatformLockOptions } from "../lock/CrossPlatformLockOptions";
9
+ import { pid } from "process";
10
+ import { TokenCacheContext, ICachePlugin, Logger } from "@azure/msal-common";
11
+
12
+ /**
13
+ * MSAL cache plugin which enables callers to write the MSAL cache to disk on Windows,
14
+ * macOs, and Linux.
15
+ *
16
+ * - Persistence can be one of:
17
+ * - FilePersistence: Writes and reads from an unencrypted file. Can be used on Windows,
18
+ * macOs, or Linux.
19
+ * - FilePersistenceWithDataProtection: Used on Windows, writes and reads from file encrypted
20
+ * with windows dpapi-addon.
21
+ * - KeychainPersistence: Used on macOs, writes and reads from keychain.
22
+ * - LibSecretPersistence: Used on linux, writes and reads from secret service API. Requires
23
+ * libsecret be installed.
24
+ */
25
+ export class PersistenceCachePlugin implements ICachePlugin {
26
+
27
+ public persistence: IPersistence;
28
+ public lastSync: number;
29
+ public currentCache: string;
30
+ public lockFilePath: string;
31
+
32
+ private crossPlatformLock: CrossPlatformLock;
33
+
34
+ private logger: Logger;
35
+
36
+ constructor(persistence: IPersistence, lockOptions?: CrossPlatformLockOptions) {
37
+ this.persistence = persistence;
38
+
39
+ // initialize logger
40
+ this.logger = persistence.getLogger();
41
+
42
+ // create file lock
43
+ this.lockFilePath = `${this.persistence.getFilePath()}.lockfile`;
44
+ this.crossPlatformLock = new CrossPlatformLock(this.lockFilePath, this.logger, lockOptions);
45
+
46
+ // initialize default values
47
+ this.lastSync = 0;
48
+ this.currentCache = null;
49
+ }
50
+
51
+ /**
52
+ * Reads from storage and saves an in-memory copy. If persistence has not been updated
53
+ * since last time data was read, in memory copy is used.
54
+ *
55
+ * If cacheContext.cacheHasChanged === true, then file lock is created and not deleted until
56
+ * afterCacheAccess() is called, to prevent the cache file from changing in between
57
+ * beforeCacheAccess() and afterCacheAccess().
58
+ */
59
+ public async beforeCacheAccess(cacheContext: TokenCacheContext): Promise<void> {
60
+ this.logger.info("Executing before cache access");
61
+ const reloadNecessary = await this.persistence.reloadNecessary(this.lastSync);
62
+ if (!reloadNecessary && this.currentCache !== null) {
63
+ if (cacheContext.cacheHasChanged) {
64
+ this.logger.verbose("Cache context has changed");
65
+ await this.crossPlatformLock.lock();
66
+ }
67
+ return;
68
+ }
69
+ try {
70
+ this.logger.info(`Reload necessary. Last sync time: ${this.lastSync}`);
71
+ await this.crossPlatformLock.lock();
72
+
73
+ this.currentCache = await this.persistence.load();
74
+ this.lastSync = new Date().getTime();
75
+ cacheContext.tokenCache.deserialize(this.currentCache);
76
+
77
+ this.logger.info(`Last sync time updated to: ${this.lastSync}`);
78
+ } finally {
79
+ if (!cacheContext.cacheHasChanged) {
80
+ await this.crossPlatformLock.unlock();
81
+ this.logger.info(`Pid ${pid} released lock`);
82
+ } else {
83
+ this.logger.info(`Pid ${pid} beforeCacheAccess did not release lock`);
84
+ }
85
+ }
86
+ }
87
+
88
+ /**
89
+ * Writes to storage if MSAL in memory copy of cache has been changed.
90
+ */
91
+ public async afterCacheAccess(cacheContext: TokenCacheContext): Promise<void> {
92
+ this.logger.info("Executing after cache access");
93
+ try {
94
+ if (cacheContext.cacheHasChanged) {
95
+ this.logger.info("Msal in-memory cache has changed. Writing changes to persistence");
96
+ this.currentCache = cacheContext.tokenCache.serialize();
97
+ await this.persistence.save(this.currentCache);
98
+ } else {
99
+ this.logger.info("Msal in-memory cache has not changed. Did not write to persistence");
100
+ }
101
+ } finally {
102
+ await this.crossPlatformLock.unlock();
103
+ this.logger.info(`Pid ${pid} afterCacheAccess released lock`);
104
+ }
105
+ }
106
+ }
@@ -0,0 +1,73 @@
1
+ /*
2
+ * Copyright (c) Microsoft Corporation. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+
6
+ import { FilePersistenceWithDataProtection } from "../persistence/FilePersistenceWithDataProtection";
7
+ import { LibSecretPersistence } from "../persistence/LibSecretPersistence";
8
+ import { KeychainPersistence } from "../persistence/KeychainPersistence";
9
+ import { DataProtectionScope } from "../persistence/DataProtectionScope";
10
+ import { Environment } from "../utils/Environment";
11
+ import { IPersistence } from "./IPersistence";
12
+ import { FilePersistence } from "./FilePersistence";
13
+ import { PersistenceError } from "../error/PersistenceError";
14
+ import { IPersistenceConfiguration } from "../persistence/IPersistenceConfiguration";
15
+
16
+ export class PersistenceCreator {
17
+ static async createPersistence(config: IPersistenceConfiguration): Promise<IPersistence> {
18
+ let peristence: IPersistence;
19
+
20
+ // On Windows, uses a DPAPI encrypted file
21
+ if (Environment.isWindowsPlatform()) {
22
+ if (!config.cachePath || !config.dataProtectionScope) {
23
+ throw PersistenceError.createPersistenceNotValidatedError(`Cache path and/or data protection scope not provided for the FilePersistenceWithDataProtection cache plugin`);
24
+ }
25
+
26
+ peristence = await FilePersistenceWithDataProtection.create(config.cachePath, DataProtectionScope.CurrentUser);
27
+ }
28
+
29
+ // On Mac, uses keychain.
30
+ else if (Environment.isMacPlatform()) {
31
+ if (!config.cachePath || !config.serviceName || !config.accountName) {
32
+ throw PersistenceError.createPersistenceNotValidatedError(`Cache path, service name and/or account name not provided for the KeychainPersistence cache plugin`);
33
+ }
34
+
35
+ peristence = await KeychainPersistence.create(config.cachePath, config.serviceName, config.accountName);
36
+ }
37
+
38
+ // On Linux, uses libsecret to store to secret service. Libsecret has to be installed.
39
+ else if (Environment.isLinuxPlatform()) {
40
+ if (!config.cachePath || !config.serviceName || !config.accountName) {
41
+ throw PersistenceError.createPersistenceNotValidatedError(`Cache path, service name and/or account name not provided for the LibSecretPersistence cache plugin`);
42
+ }
43
+
44
+ peristence = await LibSecretPersistence.create(config.cachePath, config.serviceName, config.accountName);
45
+ }
46
+
47
+ else {
48
+ throw PersistenceError.createNotSupportedError("The current environment is not supported by msal-node-extensions yet.");
49
+ }
50
+
51
+ // Initially suppress the error thrown during persistence verification to allow us to fallback to plain text
52
+ const isPersistenceVerified = await peristence.verifyPersistence().catch(() => false);
53
+
54
+ if (!isPersistenceVerified) {
55
+ if (Environment.isLinuxPlatform() && config.usePlaintextFileOnLinux) {
56
+ if (!config.cachePath) {
57
+ throw PersistenceError.createPersistenceNotValidatedError(`Cache path not provided for the FilePersistence cache plugin`);
58
+ }
59
+
60
+ peristence = await FilePersistence.create(config.cachePath);
61
+
62
+ const isFilePersistenceVerified = await peristence.verifyPersistence();
63
+ if (isFilePersistenceVerified) {
64
+ return peristence;
65
+ }
66
+ }
67
+
68
+ throw PersistenceError.createPersistenceNotVerifiedError("Persistence could not be verified");
69
+ }
70
+
71
+ return peristence;
72
+ }
73
+ }
@@ -1,24 +1,62 @@
1
- /*
2
- * Copyright (c) Microsoft Corporation. All rights reserved.
3
- * Licensed under the MIT License.
4
- */
5
-
6
- export const Constants = {
7
-
8
- /**
9
- * An existing file was the target of an operation that required that the target not exist
10
- */
11
- EEXIST_ERROR: "EEXIST",
12
-
13
- /**
14
- * No such file or directory: Commonly raised by fs operations to indicate that a component
15
- * of the specified pathname does not exist. No entity (file or directory) could be found
16
- * by the given path
17
- */
18
- ENOENT_ERROR: "ENOENT",
19
-
20
- /**
21
- * Default service name for using MSAL Keytar
22
- */
23
- DEFAULT_SERVICE_NAME: "msal-node-extensions",
24
- };
1
+ /*
2
+ * Copyright (c) Microsoft Corporation. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+
6
+ export const Constants = {
7
+
8
+ /**
9
+ * An existing file was the target of an operation that required that the target not exist
10
+ */
11
+ EEXIST_ERROR: "EEXIST",
12
+
13
+ /**
14
+ * No such file or directory: Commonly raised by fs operations to indicate that a component
15
+ * of the specified pathname does not exist. No entity (file or directory) could be found
16
+ * by the given path
17
+ */
18
+ ENOENT_ERROR: "ENOENT",
19
+
20
+ /**
21
+ * Operation not permitted. An attempt was made to perform an operation that requires
22
+ * elevated privileges.
23
+ */
24
+ EPERM_ERROR: "EPERM",
25
+
26
+ /**
27
+ * Default service name for using MSAL Keytar
28
+ */
29
+ DEFAULT_SERVICE_NAME: "msal-node-extensions",
30
+
31
+ /**
32
+ * Test data used to verify underlying persistence mechanism
33
+ */
34
+ PERSISTENCE_TEST_DATA: "Dummy data to verify underlying persistence mechanism",
35
+
36
+ /**
37
+ * This is the value of a the guid if the process is being ran by the root user
38
+ */
39
+ LINUX_ROOT_USER_GUID: 0,
40
+
41
+ /**
42
+ * List of environment variables
43
+ */
44
+ ENVIRONMENT: {
45
+ HOME: "HOME",
46
+ LOGNAME: "LOGNAME",
47
+ USER: "USER",
48
+ LNAME: "LNAME",
49
+ USERNAME: "USERNAME",
50
+ PLATFORM: "platform",
51
+ LOCAL_APPLICATION_DATA: "LOCALAPPDATA"
52
+ },
53
+
54
+ // Name of the default cache file
55
+ DEFAULT_CACHE_FILE_NAME: "cache.json"
56
+ };
57
+
58
+ export enum Platform {
59
+ WINDOWS = "win32",
60
+ LINUX = "linux",
61
+ MACOS = "darwin"
62
+ };
@@ -0,0 +1,99 @@
1
+ /*
2
+ * Copyright (c) Microsoft Corporation. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+
6
+ import path from "path";
7
+ import { Constants, Platform } from "./Constants";
8
+ import { PersistenceError } from "../error/PersistenceError";
9
+ import { StringUtils } from "@azure/msal-common";
10
+
11
+ export class Environment {
12
+ static get homeEnvVar() {
13
+ return this.getEnvironmentVariable(Constants.ENVIRONMENT.HOME);
14
+ }
15
+
16
+ static get lognameEnvVar() {
17
+ return this.getEnvironmentVariable(Constants.ENVIRONMENT.LOGNAME);
18
+ }
19
+
20
+ static get userEnvVar() {
21
+ return this.getEnvironmentVariable(Constants.ENVIRONMENT.USER);
22
+ }
23
+
24
+ static get lnameEnvVar() {
25
+ return this.getEnvironmentVariable(Constants.ENVIRONMENT.LNAME);
26
+ }
27
+
28
+ static get usernameEnvVar() {
29
+ return this.getEnvironmentVariable(Constants.ENVIRONMENT.USERNAME);
30
+ }
31
+
32
+ static getEnvironmentVariable(name: string): string {
33
+ return process.env[name];
34
+ }
35
+
36
+ static getEnvironmentPlatform(): string {
37
+ return process.platform;
38
+ }
39
+
40
+ static isWindowsPlatform(): boolean {
41
+ return this.getEnvironmentPlatform() === Platform.WINDOWS;
42
+ }
43
+
44
+ static isLinuxPlatform(): boolean {
45
+ return this.getEnvironmentPlatform() === Platform.LINUX;
46
+ }
47
+
48
+ static isMacPlatform(): boolean {
49
+ return this.getEnvironmentPlatform() === Platform.MACOS;
50
+ }
51
+
52
+ static isLinuxRootUser(): boolean {
53
+ return process.getuid() == Constants.LINUX_ROOT_USER_GUID;
54
+ }
55
+
56
+ static getUserRootDirectory(): string {
57
+ return !this.isWindowsPlatform ?
58
+ this.getUserHomeDirOnUnix() :
59
+ this.getUserHomeDirOnWindows()
60
+ }
61
+
62
+ static getUserHomeDirOnWindows(): string {
63
+ return this.getEnvironmentVariable(Constants.ENVIRONMENT.LOCAL_APPLICATION_DATA);
64
+ }
65
+
66
+ static getUserHomeDirOnUnix(): string | null {
67
+ if (this.isWindowsPlatform()) {
68
+ throw PersistenceError.createNotSupportedError("Getting the user home directory for unix is not supported in windows")
69
+ }
70
+
71
+ if (!StringUtils.isEmpty(this.homeEnvVar)) {
72
+ return this.homeEnvVar;
73
+ }
74
+
75
+ let username = null;
76
+ if (!StringUtils.isEmpty(this.lognameEnvVar)) {
77
+ username = this.lognameEnvVar;
78
+ } else if (!StringUtils.isEmpty(this.userEnvVar)) {
79
+ username = this.userEnvVar;
80
+ } else if (!StringUtils.isEmpty(this.lnameEnvVar)) {
81
+ username = this.lnameEnvVar;
82
+ } else if (!StringUtils.isEmpty(this.usernameEnvVar)) {
83
+ username = this.usernameEnvVar;
84
+ }
85
+
86
+ if (this.isMacPlatform()) {
87
+ return !StringUtils.isEmpty(username) ? path.join("/Users", username) : null;
88
+ } else if (this.isLinuxPlatform()) {
89
+ if (this.isLinuxRootUser()) {
90
+ return "/root";
91
+ } else {
92
+ return !StringUtils.isEmpty(username) ? path.join("/home", username) : null;
93
+ }
94
+ } else {
95
+ throw PersistenceError.createNotSupportedError("Getting the user home directory for unix is not supported in windows")
96
+ }
97
+
98
+ }
99
+ }
package/changelog.md DELETED
@@ -1,8 +0,0 @@
1
- # 1.0.0-alpha.0
2
-
3
- - Extensions 1: Sets directory structure, adds Windows DPAPI Node addon (#1830)
4
- - Extensions 2: Add cross process lock (#1831)
5
- - Extensions 3: Add cache persistence plugin, persistence on Windows, Linux, and Mac (#1832)
6
- - Extensions 4: Add sample (#1834)
7
- - Extensions 5: Add documentation, add logger (#1835)
8
- - Extensions 6: Add tests (#1849)