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

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.
@@ -1 +1 @@
1
- {"version":3,"file":"msal-node-extensions.cjs.development.js","sources":["../src/utils/Constants.ts","../src/error/PersistenceError.ts","../src/lock/CrossPlatformLock.ts","../src/persistence/PersistenceCachePlugin.ts","../src/persistence/BasePersistence.ts","../src/persistence/FilePersistence.ts","../src/Dpapi.ts","../src/persistence/DataProtectionScope.ts","../src/persistence/FilePersistenceWithDataProtection.ts","../src/persistence/KeychainPersistence.ts","../src/persistence/LibSecretPersistence.ts","../src/utils/Environment.ts","../src/persistence/PersistenceCreator.ts"],"sourcesContent":["/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nexport const Constants = {\n\n /**\n * An existing file was the target of an operation that required that the target not exist\n */\n EEXIST_ERROR: \"EEXIST\",\n\n /**\n * No such file or directory: Commonly raised by fs operations to indicate that a component\n * of the specified pathname does not exist. No entity (file or directory) could be found\n * by the given path\n */\n ENOENT_ERROR: \"ENOENT\",\n\n /**\n * Operation not permitted. An attempt was made to perform an operation that requires \n * elevated privileges. \n */\n EPERM_ERROR: \"EPERM\",\n \n /**\n * Default service name for using MSAL Keytar\n */\n DEFAULT_SERVICE_NAME: \"msal-node-extensions\",\n\n /**\n * Test data used to verify underlying persistence mechanism\n */\n PERSISTENCE_TEST_DATA: \"Dummy data to verify underlying persistence mechanism\",\n\n /**\n * This is the value of a the guid if the process is being ran by the root user\n */\n LINUX_ROOT_USER_GUID: 0,\n\n /**\n * List of environment variables\n */\n ENVIRONMENT: {\n HOME: \"HOME\",\n LOGNAME: \"LOGNAME\",\n USER: \"USER\",\n LNAME: \"LNAME\",\n USERNAME: \"USERNAME\",\n PLATFORM: \"platform\",\n LOCAL_APPLICATION_DATA: \"LOCALAPPDATA\"\n },\n\n // Name of the default cache file\n DEFAULT_CACHE_FILE_NAME: \"cache.json\"\n};\n\nexport enum Platform {\n WINDOWS = \"win32\",\n LINUX = \"linux\",\n MACOS = \"darwin\"\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\n/**\n * Error thrown when trying to write MSAL cache to persistence.\n */\nexport class PersistenceError extends Error {\n\n // Short string denoting error\n errorCode: string;\n // Detailed description of error\n errorMessage: string;\n\n constructor(errorCode: string, errorMessage: string) {\n const errorString = errorMessage ? `${errorCode}: ${errorMessage}` : errorCode;\n super(errorString);\n Object.setPrototypeOf(this, PersistenceError.prototype);\n\n this.errorCode = errorCode;\n this.errorMessage = errorMessage;\n this.name = \"PersistenceError\";\n }\n\n /**\n * Error thrown when trying to access the file system.\n */\n static createFileSystemError(errorCode: string, errorMessage: string): PersistenceError {\n return new PersistenceError(errorCode, errorMessage);\n }\n\n /**\n * Error thrown when trying to write, load, or delete data from secret service on linux.\n * Libsecret is used to access secret service.\n */\n static createLibSecretError(errorMessage: string): PersistenceError {\n return new PersistenceError(\"GnomeKeyringError\", errorMessage);\n }\n\n /**\n * Error thrown when trying to write, load, or delete data from keychain on macOs.\n */\n static createKeychainPersistenceError(errorMessage: string): PersistenceError {\n return new PersistenceError(\"KeychainError\", errorMessage);\n }\n\n /**\n * Error thrown when trying to encrypt or decrypt data using DPAPI on Windows.\n */\n static createFilePersistenceWithDPAPIError(errorMessage: string): PersistenceError {\n return new PersistenceError(\"DPAPIEncryptedFileError\", errorMessage);\n }\n\n /**\n * Error thrown when using the cross platform lock.\n */\n static createCrossPlatformLockError(errorMessage: string): PersistenceError {\n return new PersistenceError(\"CrossPlatformLockError\", errorMessage);\n }\n\n /**\n * Throw cache persistence error\n * \n * @param errorMessage string\n * @returns PersistenceError\n */\n static createCachePersistenceError(errorMessage: string): PersistenceError {\n return new PersistenceError(\"CachePersistenceError\", errorMessage);\n }\n\n /**\n * Throw unsupported error\n * \n * @param errorMessage string\n * @returns PersistenceError\n */\n static createNotSupportedError(errorMessage: string): PersistenceError {\n return new PersistenceError(\"NotSupportedError\", errorMessage);\n }\n\n /**\n * Throw persistence not verified error\n * \n * @param errorMessage string\n * @returns PersistenceError\n */\n static createPersistenceNotVerifiedError(errorMessage: string): PersistenceError {\n return new PersistenceError(\"PersistenceNotVerifiedError\", errorMessage);\n }\n\n /**\n * Throw persistence creation validation error\n * \n * @param errorMessage string\n * @returns PersistenceError\n */\n static createPersistenceNotValidatedError(errorMessage: string): PersistenceError {\n return new PersistenceError(\"PersistenceNotValidatedError\", errorMessage);\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { promises as fs } from \"fs\";\nimport { pid } from \"process\";\nimport { CrossPlatformLockOptions } from \"./CrossPlatformLockOptions\";\nimport { Constants } from \"../utils/Constants\";\nimport { PersistenceError } from \"../error/PersistenceError\";\nimport { Logger } from \"@azure/msal-common\";\n\n/**\n * Cross-process lock that works on all platforms.\n */\nexport class CrossPlatformLock {\n\n private readonly lockFilePath: string;\n private lockFileHandle: fs.FileHandle;\n private readonly retryNumber: number;\n private readonly retryDelay: number;\n\n private logger: Logger;\n\n constructor(lockFilePath: string, logger: Logger, lockOptions?: CrossPlatformLockOptions) {\n this.lockFilePath = lockFilePath;\n this.retryNumber = lockOptions ? lockOptions.retryNumber : 500;\n this.retryDelay = lockOptions ? lockOptions.retryDelay : 100;\n this.logger = logger;\n }\n\n /**\n * Locks cache from read or writes by creating file with same path and name as\n * cache file but with .lockfile extension. If another process has already created\n * the lockfile, will back off and retry based on configuration settings set by CrossPlatformLockOptions\n */\n public async lock(): Promise<void> {\n for (let tryCount = 0; tryCount < this.retryNumber; tryCount++) {\n try {\n this.logger.info(`Pid ${pid} trying to acquire lock`);\n this.lockFileHandle = await fs.open(this.lockFilePath, \"wx+\");\n\n this.logger.info(`Pid ${pid} acquired lock`);\n await this.lockFileHandle.write(pid.toString());\n return;\n } catch (err) {\n if (err.code === Constants.EEXIST_ERROR || err.code === Constants.EPERM_ERROR) {\n this.logger.info(err);\n await this.sleep(this.retryDelay);\n } else {\n this.logger.error(`${pid} was not able to acquire lock. Ran into error: ${err.message}`);\n throw PersistenceError.createCrossPlatformLockError(err.message);\n }\n }\n }\n this.logger.error(`${pid} was not able to acquire lock. Exceeded amount of retries set in the options`);\n throw PersistenceError.createCrossPlatformLockError(\n \"Not able to acquire lock. Exceeded amount of retries set in options\");\n }\n\n /**\n * unlocks cache file by deleting .lockfile.\n */\n public async unlock(): Promise<void> {\n try {\n if(this.lockFileHandle){\n // if we have a file handle to the .lockfile, delete lock file\n await fs.unlink(this.lockFilePath);\n await this.lockFileHandle.close();\n this.logger.info(\"lockfile deleted\");\n } else {\n this.logger.warning(\"lockfile handle does not exist, so lockfile could not be deleted\");\n }\n } catch (err) {\n if (err.code === Constants.ENOENT_ERROR) {\n this.logger.info(\"Tried to unlock but lockfile does not exist\");\n } else {\n this.logger.error(`${pid} was not able to release lock. Ran into error: ${err.message}`);\n throw PersistenceError.createCrossPlatformLockError(err.message);\n }\n }\n }\n\n private sleep(ms): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { IPersistence } from \"./IPersistence\";\nimport { CrossPlatformLock } from \"../lock/CrossPlatformLock\";\nimport { CrossPlatformLockOptions } from \"../lock/CrossPlatformLockOptions\";\nimport { pid } from \"process\";\nimport { TokenCacheContext, ICachePlugin, Logger } from \"@azure/msal-common\";\n\n/**\n * MSAL cache plugin which enables callers to write the MSAL cache to disk on Windows,\n * macOs, and Linux.\n *\n * - Persistence can be one of:\n * - FilePersistence: Writes and reads from an unencrypted file. Can be used on Windows,\n * macOs, or Linux.\n * - FilePersistenceWithDataProtection: Used on Windows, writes and reads from file encrypted\n * with windows dpapi-addon.\n * - KeychainPersistence: Used on macOs, writes and reads from keychain.\n * - LibSecretPersistence: Used on linux, writes and reads from secret service API. Requires\n * libsecret be installed.\n */\nexport class PersistenceCachePlugin implements ICachePlugin {\n\n public persistence: IPersistence;\n public lastSync: number;\n public currentCache: string;\n public lockFilePath: string;\n\n private crossPlatformLock: CrossPlatformLock;\n\n private logger: Logger;\n\n constructor(persistence: IPersistence, lockOptions?: CrossPlatformLockOptions) {\n this.persistence = persistence;\n\n // initialize logger\n this.logger = persistence.getLogger();\n\n // create file lock\n this.lockFilePath = `${this.persistence.getFilePath()}.lockfile`;\n this.crossPlatformLock = new CrossPlatformLock(this.lockFilePath, this.logger, lockOptions);\n\n // initialize default values\n this.lastSync = 0;\n this.currentCache = null;\n }\n\n /**\n * Reads from storage and saves an in-memory copy. If persistence has not been updated\n * since last time data was read, in memory copy is used.\n *\n * If cacheContext.cacheHasChanged === true, then file lock is created and not deleted until\n * afterCacheAccess() is called, to prevent the cache file from changing in between\n * beforeCacheAccess() and afterCacheAccess().\n */\n public async beforeCacheAccess(cacheContext: TokenCacheContext): Promise<void> {\n this.logger.info(\"Executing before cache access\");\n const reloadNecessary = await this.persistence.reloadNecessary(this.lastSync);\n if (!reloadNecessary && this.currentCache !== null) {\n if (cacheContext.cacheHasChanged) {\n this.logger.verbose(\"Cache context has changed\");\n await this.crossPlatformLock.lock();\n }\n return;\n }\n try {\n this.logger.info(`Reload necessary. Last sync time: ${this.lastSync}`);\n await this.crossPlatformLock.lock();\n\n this.currentCache = await this.persistence.load();\n this.lastSync = new Date().getTime();\n cacheContext.tokenCache.deserialize(this.currentCache);\n\n this.logger.info(`Last sync time updated to: ${this.lastSync}`);\n } finally {\n if (!cacheContext.cacheHasChanged) {\n await this.crossPlatformLock.unlock();\n this.logger.info(`Pid ${pid} released lock`);\n } else {\n this.logger.info(`Pid ${pid} beforeCacheAccess did not release lock`);\n }\n }\n }\n\n /**\n * Writes to storage if MSAL in memory copy of cache has been changed.\n */\n public async afterCacheAccess(cacheContext: TokenCacheContext): Promise<void> {\n this.logger.info(\"Executing after cache access\");\n try {\n if (cacheContext.cacheHasChanged) {\n this.logger.info(\"Msal in-memory cache has changed. Writing changes to persistence\");\n this.currentCache = cacheContext.tokenCache.serialize();\n await this.persistence.save(this.currentCache);\n } else {\n this.logger.info(\"Msal in-memory cache has not changed. Did not write to persistence\");\n }\n } finally {\n await this.crossPlatformLock.unlock();\n this.logger.info(`Pid ${pid} afterCacheAccess released lock`);\n }\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { PersistenceError } from \"../error/PersistenceError\";\nimport { Constants } from \"../utils/Constants\";\nimport { IPersistence } from \"./IPersistence\";\n\nexport abstract class BasePersistence {\n public abstract createForPersistenceValidation(): Promise<IPersistence>; \n\n public async verifyPersistence(): Promise<boolean> {\n // We are using a different location for the test to avoid overriding the functional cache\n const persistenceValidator = await this.createForPersistenceValidation();\n\n try {\n await persistenceValidator.save(Constants.PERSISTENCE_TEST_DATA);\n\n const retrievedDummyData = await persistenceValidator.load();\n\n if (!retrievedDummyData) {\n throw PersistenceError.createCachePersistenceError(\n \"Persistence check failed. Data was written but it could not be read. \" +\n \"Possible cause: on Linux, LibSecret is installed but D-Bus isn't running \\\n because it cannot be started over SSH.\"\n );\n }\n\n if (retrievedDummyData !== Constants.PERSISTENCE_TEST_DATA) {\n throw PersistenceError.createCachePersistenceError(\n `Persistence check failed. Data written ${Constants.PERSISTENCE_TEST_DATA} is different \\\n from data read ${retrievedDummyData}`\n );\n }\n await persistenceValidator.delete();\n return true;\n } catch (e) {\n throw PersistenceError.createCachePersistenceError(`Verifing persistence failed with the error: ${e}`);\n }\n }\n\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { promises as fs } from \"fs\";\nimport { dirname } from \"path\";\nimport { IPersistence } from \"./IPersistence\";\nimport { Constants } from \"../utils/Constants\";\nimport { PersistenceError } from \"../error/PersistenceError\";\nimport { Logger, LoggerOptions, LogLevel } from \"@azure/msal-common\";\nimport { BasePersistence } from \"./BasePersistence\";\n\n/**\n * Reads and writes data to file specified by file location. File contents are not\n * encrypted.\n *\n * If file or directory has not been created, it FilePersistence.create() will create\n * file and any directories in the path recursively.\n */\nexport class FilePersistence extends BasePersistence implements IPersistence {\n\n private filePath: string;\n private logger: Logger;\n\n public static async create(fileLocation: string, loggerOptions?: LoggerOptions): Promise<FilePersistence> {\n const filePersistence = new FilePersistence();\n filePersistence.filePath = fileLocation;\n filePersistence.logger = new Logger(loggerOptions || FilePersistence.createDefaultLoggerOptions());\n await filePersistence.createCacheFile();\n return filePersistence;\n }\n\n public async save(contents: string): Promise<void> {\n try {\n await fs.writeFile(this.getFilePath(), contents, \"utf-8\");\n } catch (err) {\n throw PersistenceError.createFileSystemError(err.code, err.message);\n }\n }\n\n public async saveBuffer(contents: Uint8Array): Promise<void> {\n try {\n await fs.writeFile(this.getFilePath(), contents);\n } catch (err) {\n throw PersistenceError.createFileSystemError(err.code, err.message);\n }\n }\n\n public async load(): Promise<string | null> {\n try {\n return await fs.readFile(this.getFilePath(), \"utf-8\");\n } catch (err) {\n throw PersistenceError.createFileSystemError(err.code, err.message);\n }\n }\n\n public async loadBuffer(): Promise<Uint8Array> {\n try {\n return await fs.readFile(this.getFilePath());\n } catch (err) {\n throw PersistenceError.createFileSystemError(err.code, err.message);\n }\n }\n\n public async delete(): Promise<boolean> {\n try {\n await fs.unlink(this.getFilePath());\n return true;\n } catch (err) {\n if (err.code === Constants.ENOENT_ERROR) {\n // file does not exist, so it was not deleted\n this.logger.warning(\"Cache file does not exist, so it could not be deleted\");\n return false;\n }\n throw PersistenceError.createFileSystemError(err.code, err.message);\n }\n }\n\n public getFilePath(): string {\n return this.filePath;\n }\n\n public async reloadNecessary(lastSync: number): Promise<boolean> {\n return lastSync < await this.timeLastModified();\n }\n\n public getLogger(): Logger {\n return this.logger;\n }\n\n public createForPersistenceValidation(): Promise<FilePersistence> {\n const testCacheFileLocation = `${dirname(this.filePath)}/test.cache`;\n return FilePersistence.create(testCacheFileLocation);\n }\n\n private static createDefaultLoggerOptions(): LoggerOptions {\n return {\n loggerCallback: () => {\n // allow users to not set loggerCallback\n },\n piiLoggingEnabled: false,\n logLevel: LogLevel.Info\n };\n }\n\n private async timeLastModified(): Promise<number> {\n try {\n const stats = await fs.stat(this.filePath);\n return stats.mtime.getTime();\n } catch (err) {\n if (err.code === Constants.ENOENT_ERROR) {\n // file does not exist, so it's never been modified\n this.logger.verbose(\"Cache file does not exist\");\n return 0;\n }\n throw PersistenceError.createFileSystemError(err.code, err.message);\n }\n }\n\n private async createCacheFile(): Promise<void> {\n await this.createFileDirectory();\n // File is created only if it does not exist\n const fileHandle = await fs.open(this.filePath, \"a\");\n await fileHandle.close();\n this.logger.info(`File created at ${this.filePath}`);\n }\n\n private async createFileDirectory(): Promise<void> {\n try {\n await fs.mkdir(dirname(this.filePath), {recursive: true});\n } catch (err) {\n if (err.code === Constants.EEXIST_ERROR) {\n this.logger.info(`Directory ${dirname(this.filePath)} already exists`);\n } else {\n throw PersistenceError.createFileSystemError(err.code, err.message);\n }\n }\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nexport interface DpapiBindings{\n protectData(dataToEncrypt: Uint8Array, optionalEntropy: Uint8Array, scope: string): Uint8Array\n unprotectData(encryptData: Uint8Array, optionalEntropy: Uint8Array, scope: string): Uint8Array\n}\n/* eslint-disable-next-line @typescript-eslint/no-var-requires, no-var, import/no-commonjs */\nexport var Dpapi: DpapiBindings = require(\"../build/Release/dpapi.node\");\nexport default Dpapi;\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\n/**\n * Specifies the scope of the data protection - either the current user or the local\n * machine.\n *\n * You do not need a key to protect or unprotect the data.\n * If you set the Scope to CurrentUser, only applications running on your credentials can\n * unprotect the data; however, that means that any application running on your credentials\n * can access the protected data. If you set the Scope to LocalMachine, any full-trust\n * application on the computer can unprotect, access, and modify the data.\n *\n */\nexport enum DataProtectionScope {\n CurrentUser = \"CurrentUser\",\n LocalMachine = \"LocalMachine\",\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { IPersistence } from \"./IPersistence\";\nimport { FilePersistence } from \"./FilePersistence\";\nimport { PersistenceError } from \"../error/PersistenceError\";\nimport { Dpapi } from \"../Dpapi\";\nimport { DataProtectionScope } from \"./DataProtectionScope\";\nimport { Logger, LoggerOptions } from \"@azure/msal-common\";\nimport { dirname } from \"path\";\nimport { BasePersistence } from \"./BasePersistence\";\n\n/**\n * Uses CryptProtectData and CryptUnprotectData on Windows to encrypt and decrypt file contents.\n *\n * scope: Scope of the data protection. Either local user or the current machine\n * optionalEntropy: Password or other additional entropy used to encrypt the data\n */\nexport class FilePersistenceWithDataProtection extends BasePersistence implements IPersistence {\n\n private filePersistence: FilePersistence;\n private scope: DataProtectionScope;\n private optionalEntropy: Uint8Array;\n\n private constructor(scope: DataProtectionScope, optionalEntropy?: string) {\n super();\n this.scope = scope;\n this.optionalEntropy = optionalEntropy ? Buffer.from(optionalEntropy, \"utf-8\") : null;\n }\n\n public static async create(\n fileLocation: string,\n scope: DataProtectionScope,\n optionalEntropy?: string,\n loggerOptions?: LoggerOptions): Promise<FilePersistenceWithDataProtection> {\n\n const persistence = new FilePersistenceWithDataProtection(scope, optionalEntropy);\n persistence.filePersistence = await FilePersistence.create(fileLocation, loggerOptions);\n return persistence;\n }\n\n public async save(contents: string): Promise<void> {\n try {\n const encryptedContents = Dpapi.protectData(\n Buffer.from(contents, \"utf-8\"),\n this.optionalEntropy,\n this.scope.toString());\n await this.filePersistence.saveBuffer(encryptedContents);\n } catch (err) {\n throw PersistenceError.createFilePersistenceWithDPAPIError(err.message);\n }\n }\n\n public async load(): Promise<string | null> {\n try {\n const encryptedContents = await this.filePersistence.loadBuffer();\n if (typeof encryptedContents === \"undefined\" || !encryptedContents || 0 === encryptedContents.length) {\n this.filePersistence.getLogger().info(\"Encrypted contents loaded from file were null or empty\");\n return null;\n }\n return Dpapi.unprotectData(\n encryptedContents,\n this.optionalEntropy,\n this.scope.toString()).toString();\n } catch (err) {\n throw PersistenceError.createFilePersistenceWithDPAPIError(err.message);\n }\n }\n\n public async delete(): Promise<boolean> {\n return this.filePersistence.delete();\n }\n\n public async reloadNecessary(lastSync: number): Promise<boolean> {\n return this.filePersistence.reloadNecessary(lastSync);\n }\n\n public getFilePath(): string {\n return this.filePersistence.getFilePath();\n }\n\n public getLogger(): Logger {\n return this.filePersistence.getLogger();\n }\n\n public createForPersistenceValidation(): Promise<FilePersistenceWithDataProtection> {\n const testCacheFileLocation = `${dirname(this.filePersistence.getFilePath())}/test.cache`;\n return FilePersistenceWithDataProtection.create(testCacheFileLocation, DataProtectionScope.CurrentUser);\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { setPassword, getPassword, deletePassword } from \"keytar\";\nimport { FilePersistence } from \"./FilePersistence\";\nimport { IPersistence } from \"./IPersistence\";\nimport { PersistenceError } from \"../error/PersistenceError\";\nimport { Logger, LoggerOptions } from \"@azure/msal-common\";\nimport { dirname } from \"path\";\nimport { BasePersistence } from \"./BasePersistence\";\n\n/**\n * Uses reads and writes passwords to macOS keychain\n *\n * serviceName: Identifier used as key for whatever value is stored\n * accountName: Account under which password should be stored\n */\nexport class KeychainPersistence extends BasePersistence implements IPersistence {\n\n protected readonly serviceName;\n protected readonly accountName;\n private filePersistence: FilePersistence;\n\n private constructor(serviceName: string, accountName: string) {\n super();\n this.serviceName = serviceName;\n this.accountName = accountName;\n }\n\n public static async create(\n fileLocation: string,\n serviceName: string,\n accountName: string,\n loggerOptions?: LoggerOptions): Promise<KeychainPersistence> {\n\n const persistence = new KeychainPersistence(serviceName, accountName);\n persistence.filePersistence = await FilePersistence.create(fileLocation, loggerOptions);\n return persistence;\n }\n\n public async save(contents: string): Promise<void> {\n try {\n await setPassword(this.serviceName, this.accountName, contents);\n } catch (err) {\n throw PersistenceError.createKeychainPersistenceError(err.message);\n }\n // Write dummy data to update file mtime\n await this.filePersistence.save(\"{}\");\n }\n\n public async load(): Promise<string | null> {\n try{\n return await getPassword(this.serviceName, this.accountName);\n } catch(err){\n throw PersistenceError.createKeychainPersistenceError(err.message);\n }\n }\n\n public async delete(): Promise<boolean> {\n try {\n await this.filePersistence.delete();\n return await deletePassword(this.serviceName, this.accountName);\n } catch (err) {\n throw PersistenceError.createKeychainPersistenceError(err.message);\n }\n }\n\n public async reloadNecessary(lastSync: number): Promise<boolean> {\n return this.filePersistence.reloadNecessary(lastSync);\n }\n\n public getFilePath(): string {\n return this.filePersistence.getFilePath();\n }\n\n public getLogger(): Logger {\n return this.filePersistence.getLogger();\n }\n \n public createForPersistenceValidation(): Promise<KeychainPersistence> {\n const testCacheFileLocation = `${dirname(this.filePersistence.getFilePath())}/test.cache`;\n return KeychainPersistence.create(\n testCacheFileLocation, \n \"persistenceValidationServiceName\", \"persistencValidationAccountName\"\n );\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { setPassword, getPassword, deletePassword } from \"keytar\";\nimport { FilePersistence } from \"./FilePersistence\";\nimport { IPersistence } from \"./IPersistence\";\nimport { PersistenceError } from \"../error/PersistenceError\";\nimport { Logger, LoggerOptions } from \"@azure/msal-common\";\nimport { dirname } from \"path\";\nimport { BasePersistence } from \"./BasePersistence\";\n\n/**\n * Uses reads and writes passwords to Secret Service API/libsecret. Requires libsecret\n * to be installed.\n *\n * serviceName: Identifier used as key for whatever value is stored\n * accountName: Account under which password should be stored\n */\nexport class LibSecretPersistence extends BasePersistence implements IPersistence {\n\n protected readonly serviceName;\n protected readonly accountName;\n private filePersistence: FilePersistence;\n\n private constructor(serviceName: string, accountName: string) {\n super();\n this.serviceName = serviceName;\n this.accountName = accountName;\n }\n\n public static async create(\n fileLocation: string,\n serviceName: string,\n accountName: string,\n loggerOptions?: LoggerOptions): Promise<LibSecretPersistence> {\n\n const persistence = new LibSecretPersistence(serviceName, accountName);\n persistence.filePersistence = await FilePersistence.create(fileLocation, loggerOptions);\n return persistence;\n }\n\n public async save(contents: string): Promise<void> {\n try {\n await setPassword(this.serviceName, this.accountName, contents);\n } catch (err) {\n throw PersistenceError.createLibSecretError(err.message);\n }\n // Write dummy data to update file mtime\n await this.filePersistence.save(\"{}\");\n }\n\n public async load(): Promise<string | null> {\n try {\n return await getPassword(this.serviceName, this.accountName);\n } catch (err) {\n throw PersistenceError.createLibSecretError(err.message);\n }\n }\n\n public async delete(): Promise<boolean> {\n try {\n await this.filePersistence.delete();\n return await deletePassword(this.serviceName, this.accountName);\n } catch (err) {\n throw PersistenceError.createLibSecretError(err.message);\n }\n }\n\n public async reloadNecessary(lastSync: number): Promise<boolean> {\n return this.filePersistence.reloadNecessary(lastSync);\n }\n\n public getFilePath(): string {\n return this.filePersistence.getFilePath();\n }\n\n public getLogger(): Logger {\n return this.filePersistence.getLogger();\n }\n \n public createForPersistenceValidation(): Promise<LibSecretPersistence> {\n const testCacheFileLocation = `${dirname(this.filePersistence.getFilePath())}/test.cache`;\n return LibSecretPersistence.create(\n testCacheFileLocation, \n \"persistenceValidationServiceName\", \"persistencValidationAccountName\"\n );\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport path from \"path\";\nimport { Constants, Platform } from \"./Constants\";\nimport { PersistenceError } from \"../error/PersistenceError\";\nimport { StringUtils } from \"@azure/msal-common\";\n\nexport class Environment {\n static get homeEnvVar(): string {\n return this.getEnvironmentVariable(Constants.ENVIRONMENT.HOME);\n }\n \n static get lognameEnvVar(): string {\n return this.getEnvironmentVariable(Constants.ENVIRONMENT.LOGNAME);\n }\n\n static get userEnvVar(): string {\n return this.getEnvironmentVariable(Constants.ENVIRONMENT.USER);\n }\n\n static get lnameEnvVar(): string {\n return this.getEnvironmentVariable(Constants.ENVIRONMENT.LNAME);\n }\n\n static get usernameEnvVar(): string {\n return this.getEnvironmentVariable(Constants.ENVIRONMENT.USERNAME);\n }\n\n static getEnvironmentVariable(name: string): string {\n return process.env[name];\n }\n\n static getEnvironmentPlatform(): string {\n return process.platform;\n }\n\n static isWindowsPlatform(): boolean {\n return this.getEnvironmentPlatform() === Platform.WINDOWS;\n }\n\n static isLinuxPlatform(): boolean {\n return this.getEnvironmentPlatform() === Platform.LINUX;\n }\n\n static isMacPlatform(): boolean {\n return this.getEnvironmentPlatform() === Platform.MACOS;\n }\n\n static isLinuxRootUser(): boolean {\n return process.getuid() === Constants.LINUX_ROOT_USER_GUID;\n }\n\n static getUserRootDirectory(): string {\n return !this.isWindowsPlatform ?\n this.getUserHomeDirOnUnix() :\n this.getUserHomeDirOnWindows();\n }\n\n static getUserHomeDirOnWindows(): string {\n return this.getEnvironmentVariable(Constants.ENVIRONMENT.LOCAL_APPLICATION_DATA);\n }\n\n static getUserHomeDirOnUnix(): string | null {\n if (this.isWindowsPlatform()) {\n throw PersistenceError.createNotSupportedError(\n \"Getting the user home directory for unix is not supported in windows\");\n }\n\n if (!StringUtils.isEmpty(this.homeEnvVar)) {\n return this.homeEnvVar;\n }\n\n let username = null;\n if (!StringUtils.isEmpty(this.lognameEnvVar)) {\n username = this.lognameEnvVar;\n } else if (!StringUtils.isEmpty(this.userEnvVar)) {\n username = this.userEnvVar;\n } else if (!StringUtils.isEmpty(this.lnameEnvVar)) {\n username = this.lnameEnvVar;\n } else if (!StringUtils.isEmpty(this.usernameEnvVar)) {\n username = this.usernameEnvVar;\n }\n\n if (this.isMacPlatform()) {\n return !StringUtils.isEmpty(username) ? path.join(\"/Users\", username) : null;\n } else if (this.isLinuxPlatform()) {\n if (this.isLinuxRootUser()) {\n return \"/root\";\n } else {\n return !StringUtils.isEmpty(username) ? path.join(\"/home\", username) : null;\n }\n } else {\n throw PersistenceError.createNotSupportedError(\n \"Getting the user home directory for unix is not supported in windows\");\n }\n\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { FilePersistenceWithDataProtection } from \"./FilePersistenceWithDataProtection\";\nimport { LibSecretPersistence } from \"./LibSecretPersistence\";\nimport { KeychainPersistence } from \"./KeychainPersistence\";\nimport { DataProtectionScope } from \"./DataProtectionScope\";\nimport { Environment } from \"../utils/Environment\";\nimport { IPersistence } from \"./IPersistence\";\nimport { FilePersistence } from \"./FilePersistence\";\nimport { PersistenceError } from \"../error/PersistenceError\";\nimport { IPersistenceConfiguration } from \"./IPersistenceConfiguration\";\n\nexport class PersistenceCreator {\n static async createPersistence(config: IPersistenceConfiguration): Promise<IPersistence> {\n let peristence: IPersistence;\n\n // On Windows, uses a DPAPI encrypted file\n if (Environment.isWindowsPlatform()) {\n if (!config.cachePath || !config.dataProtectionScope) {\n throw PersistenceError.createPersistenceNotValidatedError(\n \"Cache path and/or data protection scope not provided for the FilePersistenceWithDataProtection cache plugin\");\n }\n\n peristence = await FilePersistenceWithDataProtection.create(config.cachePath, DataProtectionScope.CurrentUser, undefined, config.loggerOptions);\n }\n\n // On Mac, uses keychain.\n else if (Environment.isMacPlatform()) {\n if (!config.cachePath || !config.serviceName || !config.accountName) {\n throw PersistenceError.createPersistenceNotValidatedError(\n \"Cache path, service name and/or account name not provided for the KeychainPersistence cache plugin\");\n }\n\n peristence = await KeychainPersistence.create(config.cachePath, config.serviceName, config.accountName, config.loggerOptions);\n }\n\n // On Linux, uses libsecret to store to secret service. Libsecret has to be installed.\n else if (Environment.isLinuxPlatform()) {\n if (!config.cachePath || !config.serviceName || !config.accountName) {\n throw PersistenceError.createPersistenceNotValidatedError(\n \"Cache path, service name and/or account name not provided for the LibSecretPersistence cache plugin\");\n }\n\n peristence = await LibSecretPersistence.create(config.cachePath, config.serviceName, config.accountName, config.loggerOptions);\n }\n\n else {\n throw PersistenceError.createNotSupportedError(\n \"The current environment is not supported by msal-node-extensions yet.\");\n }\n\n // Initially suppress the error thrown during persistence verification to allow us to fallback to plain text\n const isPersistenceVerified = await peristence.verifyPersistence().catch(() => false);\n\n if (!isPersistenceVerified) {\n if (Environment.isLinuxPlatform() && config.usePlaintextFileOnLinux) {\n if (!config.cachePath) {\n throw PersistenceError.createPersistenceNotValidatedError(\n \"Cache path not provided for the FilePersistence cache plugin\");\n }\n\n peristence = await FilePersistence.create(config.cachePath, config.loggerOptions);\n\n const isFilePersistenceVerified = await peristence.verifyPersistence();\n if (isFilePersistenceVerified) {\n return peristence;\n }\n }\n\n throw PersistenceError.createPersistenceNotVerifiedError(\"Persistence could not be verified\");\n }\n\n return peristence;\n }\n}\n"],"names":["Constants","EEXIST_ERROR","ENOENT_ERROR","EPERM_ERROR","DEFAULT_SERVICE_NAME","PERSISTENCE_TEST_DATA","LINUX_ROOT_USER_GUID","ENVIRONMENT","HOME","LOGNAME","USER","LNAME","USERNAME","PLATFORM","LOCAL_APPLICATION_DATA","DEFAULT_CACHE_FILE_NAME","Platform","PersistenceError","Error","constructor","errorCode","errorMessage","errorString","Object","setPrototypeOf","prototype","name","createFileSystemError","createLibSecretError","createKeychainPersistenceError","createFilePersistenceWithDPAPIError","createCrossPlatformLockError","createCachePersistenceError","createNotSupportedError","createPersistenceNotVerifiedError","createPersistenceNotValidatedError","CrossPlatformLock","lockFilePath","logger","lockOptions","retryNumber","retryDelay","lock","tryCount","info","pid","lockFileHandle","fs","open","write","toString","err","code","sleep","error","message","unlock","unlink","close","warning","ms","Promise","resolve","setTimeout","PersistenceCachePlugin","persistence","getLogger","getFilePath","crossPlatformLock","lastSync","currentCache","beforeCacheAccess","cacheContext","reloadNecessary","cacheHasChanged","verbose","load","Date","getTime","tokenCache","deserialize","afterCacheAccess","serialize","save","BasePersistence","verifyPersistence","persistenceValidator","createForPersistenceValidation","retrievedDummyData","delete","e","FilePersistence","create","fileLocation","loggerOptions","filePersistence","filePath","Logger","createDefaultLoggerOptions","createCacheFile","contents","writeFile","saveBuffer","readFile","loadBuffer","timeLastModified","testCacheFileLocation","dirname","loggerCallback","piiLoggingEnabled","logLevel","LogLevel","Info","stats","stat","mtime","createFileDirectory","fileHandle","mkdir","recursive","Dpapi","require","DataProtectionScope","FilePersistenceWithDataProtection","scope","optionalEntropy","Buffer","from","encryptedContents","protectData","length","unprotectData","CurrentUser","KeychainPersistence","serviceName","accountName","setPassword","getPassword","deletePassword","LibSecretPersistence","Environment","homeEnvVar","getEnvironmentVariable","lognameEnvVar","userEnvVar","lnameEnvVar","usernameEnvVar","process","env","getEnvironmentPlatform","platform","isWindowsPlatform","WINDOWS","isLinuxPlatform","LINUX","isMacPlatform","MACOS","isLinuxRootUser","getuid","getUserRootDirectory","getUserHomeDirOnUnix","getUserHomeDirOnWindows","StringUtils","isEmpty","username","path","join","PersistenceCreator","createPersistence","config","peristence","cachePath","dataProtectionScope","undefined","isPersistenceVerified","catch","usePlaintextFileOnLinux","isFilePersistenceVerified"],"mappings":";;;;;;;;;;;;;AAAA;;;;AAKO,MAAMA,SAAS,GAAG;AAErB;;;AAGAC,EAAAA,YAAY,EAAE,QALO;;AAOrB;;;;;AAKAC,EAAAA,YAAY,EAAE,QAZO;;AAcrB;;;;AAIAC,EAAAA,WAAW,EAAE,OAlBQ;;AAoBrB;;;AAGAC,EAAAA,oBAAoB,EAAE,sBAvBD;;AAyBrB;;;AAGAC,EAAAA,qBAAqB,EAAE,uDA5BF;;AA8BrB;;;AAGAC,EAAAA,oBAAoB,EAAE,CAjCD;;AAmCrB;;;AAGAC,EAAAA,WAAW,EAAE;AACTC,IAAAA,IAAI,EAAE,MADG;AAETC,IAAAA,OAAO,EAAE,SAFA;AAGTC,IAAAA,IAAI,EAAE,MAHG;AAITC,IAAAA,KAAK,EAAE,OAJE;AAKTC,IAAAA,QAAQ,EAAE,UALD;AAMTC,IAAAA,QAAQ,EAAE,UAND;AAOTC,IAAAA,sBAAsB,EAAE;AAPf,GAtCQ;AAgDrB;AACAC,EAAAA,uBAAuB,EAAE;AAjDJ,CAAlB;AAoDP,IAAYC,QAAZ;;AAAA,WAAYA;AACRA,EAAAA,mBAAA,UAAA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uB;AACnB,gBAAM1J,gBAAgB,CAACkB,kCAAjB,CACF,8DADE,CAAN;AAEH;;AAEDuI,QAAAA,UAAU,GAAG,MAAM/E,eAAe,CAACC,MAAhB,CAAuB6E,MAAM,CAACE,SAA9B,EAAyCF,MAAM,CAAC3E,aAAhD,CAAnB;AAEA,cAAMmF,yBAAyB,GAAG,MAAMP,UAAU,CAACrF,iBAAX,EAAxC;;AACA,YAAI4F,yBAAJ,EAA+B;AAC3B,iBAAOP,UAAP;AACH;AACJ;;AAED,YAAMzJ,gBAAgB,CAACiB,iCAAjB,CAAmD,mCAAnD,CAAN;AACH;;AAED,WAAOwI,UAAP;AACH;;;;;;;;;;;;"}
1
+ {"version":3,"file":"msal-node-extensions.cjs.development.js","sources":["../src/utils/Constants.ts","../src/error/PersistenceError.ts","../src/lock/CrossPlatformLock.ts","../src/persistence/PersistenceCachePlugin.ts","../src/persistence/BasePersistence.ts","../src/persistence/FilePersistence.ts","../src/Dpapi.ts","../src/persistence/DataProtectionScope.ts","../src/persistence/FilePersistenceWithDataProtection.ts","../src/persistence/KeychainPersistence.ts","../src/persistence/LibSecretPersistence.ts","../src/utils/Environment.ts","../src/persistence/PersistenceCreator.ts","../src/error/NativeAuthError.ts","../src/packageMetadata.ts","../src/broker/NativeBrokerPlugin.ts"],"sourcesContent":["/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nexport const Constants = {\n\n /**\n * An existing file was the target of an operation that required that the target not exist\n */\n EEXIST_ERROR: \"EEXIST\",\n\n /**\n * No such file or directory: Commonly raised by fs operations to indicate that a component\n * of the specified pathname does not exist. No entity (file or directory) could be found\n * by the given path\n */\n ENOENT_ERROR: \"ENOENT\",\n\n /**\n * Operation not permitted. An attempt was made to perform an operation that requires \n * elevated privileges. \n */\n EPERM_ERROR: \"EPERM\",\n \n /**\n * Default service name for using MSAL Keytar\n */\n DEFAULT_SERVICE_NAME: \"msal-node-extensions\",\n\n /**\n * Test data used to verify underlying persistence mechanism\n */\n PERSISTENCE_TEST_DATA: \"Dummy data to verify underlying persistence mechanism\",\n\n /**\n * This is the value of a the guid if the process is being ran by the root user\n */\n LINUX_ROOT_USER_GUID: 0,\n\n /**\n * List of environment variables\n */\n ENVIRONMENT: {\n HOME: \"HOME\",\n LOGNAME: \"LOGNAME\",\n USER: \"USER\",\n LNAME: \"LNAME\",\n USERNAME: \"USERNAME\",\n PLATFORM: \"platform\",\n LOCAL_APPLICATION_DATA: \"LOCALAPPDATA\"\n },\n\n // Name of the default cache file\n DEFAULT_CACHE_FILE_NAME: \"cache.json\"\n};\n\nexport enum Platform {\n WINDOWS = \"win32\",\n LINUX = \"linux\",\n MACOS = \"darwin\"\n}\n\nexport enum ErrorCodes {\n INTERATION_REQUIRED_ERROR_CODE = \"interaction_required\",\n SERVER_UNAVAILABLE = \"server_unavailable\"\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\n/**\n * Error thrown when trying to write MSAL cache to persistence.\n */\nexport class PersistenceError extends Error {\n\n // Short string denoting error\n errorCode: string;\n // Detailed description of error\n errorMessage: string;\n\n constructor(errorCode: string, errorMessage: string) {\n const errorString = errorMessage ? `${errorCode}: ${errorMessage}` : errorCode;\n super(errorString);\n Object.setPrototypeOf(this, PersistenceError.prototype);\n\n this.errorCode = errorCode;\n this.errorMessage = errorMessage;\n this.name = \"PersistenceError\";\n }\n\n /**\n * Error thrown when trying to access the file system.\n */\n static createFileSystemError(errorCode: string, errorMessage: string): PersistenceError {\n return new PersistenceError(errorCode, errorMessage);\n }\n\n /**\n * Error thrown when trying to write, load, or delete data from secret service on linux.\n * Libsecret is used to access secret service.\n */\n static createLibSecretError(errorMessage: string): PersistenceError {\n return new PersistenceError(\"GnomeKeyringError\", errorMessage);\n }\n\n /**\n * Error thrown when trying to write, load, or delete data from keychain on macOs.\n */\n static createKeychainPersistenceError(errorMessage: string): PersistenceError {\n return new PersistenceError(\"KeychainError\", errorMessage);\n }\n\n /**\n * Error thrown when trying to encrypt or decrypt data using DPAPI on Windows.\n */\n static createFilePersistenceWithDPAPIError(errorMessage: string): PersistenceError {\n return new PersistenceError(\"DPAPIEncryptedFileError\", errorMessage);\n }\n\n /**\n * Error thrown when using the cross platform lock.\n */\n static createCrossPlatformLockError(errorMessage: string): PersistenceError {\n return new PersistenceError(\"CrossPlatformLockError\", errorMessage);\n }\n\n /**\n * Throw cache persistence error\n * \n * @param errorMessage string\n * @returns PersistenceError\n */\n static createCachePersistenceError(errorMessage: string): PersistenceError {\n return new PersistenceError(\"CachePersistenceError\", errorMessage);\n }\n\n /**\n * Throw unsupported error\n * \n * @param errorMessage string\n * @returns PersistenceError\n */\n static createNotSupportedError(errorMessage: string): PersistenceError {\n return new PersistenceError(\"NotSupportedError\", errorMessage);\n }\n\n /**\n * Throw persistence not verified error\n * \n * @param errorMessage string\n * @returns PersistenceError\n */\n static createPersistenceNotVerifiedError(errorMessage: string): PersistenceError {\n return new PersistenceError(\"PersistenceNotVerifiedError\", errorMessage);\n }\n\n /**\n * Throw persistence creation validation error\n * \n * @param errorMessage string\n * @returns PersistenceError\n */\n static createPersistenceNotValidatedError(errorMessage: string): PersistenceError {\n return new PersistenceError(\"PersistenceNotValidatedError\", errorMessage);\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { promises as fs } from \"fs\";\nimport { pid } from \"process\";\nimport { CrossPlatformLockOptions } from \"./CrossPlatformLockOptions\";\nimport { Constants } from \"../utils/Constants\";\nimport { PersistenceError } from \"../error/PersistenceError\";\nimport { Logger } from \"@azure/msal-common\";\n\n/**\n * Cross-process lock that works on all platforms.\n */\nexport class CrossPlatformLock {\n\n private readonly lockFilePath: string;\n private lockFileHandle: fs.FileHandle;\n private readonly retryNumber: number;\n private readonly retryDelay: number;\n\n private logger: Logger;\n\n constructor(lockFilePath: string, logger: Logger, lockOptions?: CrossPlatformLockOptions) {\n this.lockFilePath = lockFilePath;\n this.retryNumber = lockOptions ? lockOptions.retryNumber : 500;\n this.retryDelay = lockOptions ? lockOptions.retryDelay : 100;\n this.logger = logger;\n }\n\n /**\n * Locks cache from read or writes by creating file with same path and name as\n * cache file but with .lockfile extension. If another process has already created\n * the lockfile, will back off and retry based on configuration settings set by CrossPlatformLockOptions\n */\n public async lock(): Promise<void> {\n for (let tryCount = 0; tryCount < this.retryNumber; tryCount++) {\n try {\n this.logger.info(`Pid ${pid} trying to acquire lock`);\n this.lockFileHandle = await fs.open(this.lockFilePath, \"wx+\");\n\n this.logger.info(`Pid ${pid} acquired lock`);\n await this.lockFileHandle.write(pid.toString());\n return;\n } catch (err) {\n if (err.code === Constants.EEXIST_ERROR || err.code === Constants.EPERM_ERROR) {\n this.logger.info(err);\n await this.sleep(this.retryDelay);\n } else {\n this.logger.error(`${pid} was not able to acquire lock. Ran into error: ${err.message}`);\n throw PersistenceError.createCrossPlatformLockError(err.message);\n }\n }\n }\n this.logger.error(`${pid} was not able to acquire lock. Exceeded amount of retries set in the options`);\n throw PersistenceError.createCrossPlatformLockError(\n \"Not able to acquire lock. Exceeded amount of retries set in options\");\n }\n\n /**\n * unlocks cache file by deleting .lockfile.\n */\n public async unlock(): Promise<void> {\n try {\n if(this.lockFileHandle){\n // if we have a file handle to the .lockfile, delete lock file\n await fs.unlink(this.lockFilePath);\n await this.lockFileHandle.close();\n this.logger.info(\"lockfile deleted\");\n } else {\n this.logger.warning(\"lockfile handle does not exist, so lockfile could not be deleted\");\n }\n } catch (err) {\n if (err.code === Constants.ENOENT_ERROR) {\n this.logger.info(\"Tried to unlock but lockfile does not exist\");\n } else {\n this.logger.error(`${pid} was not able to release lock. Ran into error: ${err.message}`);\n throw PersistenceError.createCrossPlatformLockError(err.message);\n }\n }\n }\n\n private sleep(ms): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { IPersistence } from \"./IPersistence\";\nimport { CrossPlatformLock } from \"../lock/CrossPlatformLock\";\nimport { CrossPlatformLockOptions } from \"../lock/CrossPlatformLockOptions\";\nimport { pid } from \"process\";\nimport { TokenCacheContext, ICachePlugin, Logger } from \"@azure/msal-common\";\n\n/**\n * MSAL cache plugin which enables callers to write the MSAL cache to disk on Windows,\n * macOs, and Linux.\n *\n * - Persistence can be one of:\n * - FilePersistence: Writes and reads from an unencrypted file. Can be used on Windows,\n * macOs, or Linux.\n * - FilePersistenceWithDataProtection: Used on Windows, writes and reads from file encrypted\n * with windows dpapi-addon.\n * - KeychainPersistence: Used on macOs, writes and reads from keychain.\n * - LibSecretPersistence: Used on linux, writes and reads from secret service API. Requires\n * libsecret be installed.\n */\nexport class PersistenceCachePlugin implements ICachePlugin {\n\n public persistence: IPersistence;\n public lastSync: number;\n public currentCache: string;\n public lockFilePath: string;\n\n private crossPlatformLock: CrossPlatformLock;\n\n private logger: Logger;\n\n constructor(persistence: IPersistence, lockOptions?: CrossPlatformLockOptions) {\n this.persistence = persistence;\n\n // initialize logger\n this.logger = persistence.getLogger();\n\n // create file lock\n this.lockFilePath = `${this.persistence.getFilePath()}.lockfile`;\n this.crossPlatformLock = new CrossPlatformLock(this.lockFilePath, this.logger, lockOptions);\n\n // initialize default values\n this.lastSync = 0;\n this.currentCache = null;\n }\n\n /**\n * Reads from storage and saves an in-memory copy. If persistence has not been updated\n * since last time data was read, in memory copy is used.\n *\n * If cacheContext.cacheHasChanged === true, then file lock is created and not deleted until\n * afterCacheAccess() is called, to prevent the cache file from changing in between\n * beforeCacheAccess() and afterCacheAccess().\n */\n public async beforeCacheAccess(cacheContext: TokenCacheContext): Promise<void> {\n this.logger.info(\"Executing before cache access\");\n const reloadNecessary = await this.persistence.reloadNecessary(this.lastSync);\n if (!reloadNecessary && this.currentCache !== null) {\n if (cacheContext.cacheHasChanged) {\n this.logger.verbose(\"Cache context has changed\");\n await this.crossPlatformLock.lock();\n }\n return;\n }\n try {\n this.logger.info(`Reload necessary. Last sync time: ${this.lastSync}`);\n await this.crossPlatformLock.lock();\n\n this.currentCache = await this.persistence.load();\n this.lastSync = new Date().getTime();\n cacheContext.tokenCache.deserialize(this.currentCache);\n\n this.logger.info(`Last sync time updated to: ${this.lastSync}`);\n } finally {\n if (!cacheContext.cacheHasChanged) {\n await this.crossPlatformLock.unlock();\n this.logger.info(`Pid ${pid} released lock`);\n } else {\n this.logger.info(`Pid ${pid} beforeCacheAccess did not release lock`);\n }\n }\n }\n\n /**\n * Writes to storage if MSAL in memory copy of cache has been changed.\n */\n public async afterCacheAccess(cacheContext: TokenCacheContext): Promise<void> {\n this.logger.info(\"Executing after cache access\");\n try {\n if (cacheContext.cacheHasChanged) {\n this.logger.info(\"Msal in-memory cache has changed. Writing changes to persistence\");\n this.currentCache = cacheContext.tokenCache.serialize();\n await this.persistence.save(this.currentCache);\n } else {\n this.logger.info(\"Msal in-memory cache has not changed. Did not write to persistence\");\n }\n } finally {\n await this.crossPlatformLock.unlock();\n this.logger.info(`Pid ${pid} afterCacheAccess released lock`);\n }\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { PersistenceError } from \"../error/PersistenceError\";\nimport { Constants } from \"../utils/Constants\";\nimport { IPersistence } from \"./IPersistence\";\n\nexport abstract class BasePersistence {\n public abstract createForPersistenceValidation(): Promise<IPersistence>; \n\n public async verifyPersistence(): Promise<boolean> {\n // We are using a different location for the test to avoid overriding the functional cache\n const persistenceValidator = await this.createForPersistenceValidation();\n\n try {\n await persistenceValidator.save(Constants.PERSISTENCE_TEST_DATA);\n\n const retrievedDummyData = await persistenceValidator.load();\n\n if (!retrievedDummyData) {\n throw PersistenceError.createCachePersistenceError(\n \"Persistence check failed. Data was written but it could not be read. \" +\n \"Possible cause: on Linux, LibSecret is installed but D-Bus isn't running \\\n because it cannot be started over SSH.\"\n );\n }\n\n if (retrievedDummyData !== Constants.PERSISTENCE_TEST_DATA) {\n throw PersistenceError.createCachePersistenceError(\n `Persistence check failed. Data written ${Constants.PERSISTENCE_TEST_DATA} is different \\\n from data read ${retrievedDummyData}`\n );\n }\n await persistenceValidator.delete();\n return true;\n } catch (e) {\n throw PersistenceError.createCachePersistenceError(`Verifing persistence failed with the error: ${e}`);\n }\n }\n\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { promises as fs } from \"fs\";\nimport { dirname } from \"path\";\nimport { IPersistence } from \"./IPersistence\";\nimport { Constants } from \"../utils/Constants\";\nimport { PersistenceError } from \"../error/PersistenceError\";\nimport { Logger, LoggerOptions, LogLevel } from \"@azure/msal-common\";\nimport { BasePersistence } from \"./BasePersistence\";\n\n/**\n * Reads and writes data to file specified by file location. File contents are not\n * encrypted.\n *\n * If file or directory has not been created, it FilePersistence.create() will create\n * file and any directories in the path recursively.\n */\nexport class FilePersistence extends BasePersistence implements IPersistence {\n\n private filePath: string;\n private logger: Logger;\n\n public static async create(fileLocation: string, loggerOptions?: LoggerOptions): Promise<FilePersistence> {\n const filePersistence = new FilePersistence();\n filePersistence.filePath = fileLocation;\n filePersistence.logger = new Logger(loggerOptions || FilePersistence.createDefaultLoggerOptions());\n await filePersistence.createCacheFile();\n return filePersistence;\n }\n\n public async save(contents: string): Promise<void> {\n try {\n await fs.writeFile(this.getFilePath(), contents, \"utf-8\");\n } catch (err) {\n throw PersistenceError.createFileSystemError(err.code, err.message);\n }\n }\n\n public async saveBuffer(contents: Uint8Array): Promise<void> {\n try {\n await fs.writeFile(this.getFilePath(), contents);\n } catch (err) {\n throw PersistenceError.createFileSystemError(err.code, err.message);\n }\n }\n\n public async load(): Promise<string | null> {\n try {\n return await fs.readFile(this.getFilePath(), \"utf-8\");\n } catch (err) {\n throw PersistenceError.createFileSystemError(err.code, err.message);\n }\n }\n\n public async loadBuffer(): Promise<Uint8Array> {\n try {\n return await fs.readFile(this.getFilePath());\n } catch (err) {\n throw PersistenceError.createFileSystemError(err.code, err.message);\n }\n }\n\n public async delete(): Promise<boolean> {\n try {\n await fs.unlink(this.getFilePath());\n return true;\n } catch (err) {\n if (err.code === Constants.ENOENT_ERROR) {\n // file does not exist, so it was not deleted\n this.logger.warning(\"Cache file does not exist, so it could not be deleted\");\n return false;\n }\n throw PersistenceError.createFileSystemError(err.code, err.message);\n }\n }\n\n public getFilePath(): string {\n return this.filePath;\n }\n\n public async reloadNecessary(lastSync: number): Promise<boolean> {\n return lastSync < await this.timeLastModified();\n }\n\n public getLogger(): Logger {\n return this.logger;\n }\n\n public createForPersistenceValidation(): Promise<FilePersistence> {\n const testCacheFileLocation = `${dirname(this.filePath)}/test.cache`;\n return FilePersistence.create(testCacheFileLocation);\n }\n\n private static createDefaultLoggerOptions(): LoggerOptions {\n return {\n loggerCallback: () => {\n // allow users to not set loggerCallback\n },\n piiLoggingEnabled: false,\n logLevel: LogLevel.Info\n };\n }\n\n private async timeLastModified(): Promise<number> {\n try {\n const stats = await fs.stat(this.filePath);\n return stats.mtime.getTime();\n } catch (err) {\n if (err.code === Constants.ENOENT_ERROR) {\n // file does not exist, so it's never been modified\n this.logger.verbose(\"Cache file does not exist\");\n return 0;\n }\n throw PersistenceError.createFileSystemError(err.code, err.message);\n }\n }\n\n private async createCacheFile(): Promise<void> {\n await this.createFileDirectory();\n // File is created only if it does not exist\n const fileHandle = await fs.open(this.filePath, \"a\");\n await fileHandle.close();\n this.logger.info(`File created at ${this.filePath}`);\n }\n\n private async createFileDirectory(): Promise<void> {\n try {\n await fs.mkdir(dirname(this.filePath), {recursive: true});\n } catch (err) {\n if (err.code === Constants.EEXIST_ERROR) {\n this.logger.info(`Directory ${dirname(this.filePath)} already exists`);\n } else {\n throw PersistenceError.createFileSystemError(err.code, err.message);\n }\n }\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nexport interface DpapiBindings{\n protectData(dataToEncrypt: Uint8Array, optionalEntropy: Uint8Array, scope: string): Uint8Array\n unprotectData(encryptData: Uint8Array, optionalEntropy: Uint8Array, scope: string): Uint8Array\n}\n/* eslint-disable-next-line @typescript-eslint/no-var-requires, no-var, import/no-commonjs */\nexport var Dpapi: DpapiBindings = require(\"../build/Release/dpapi.node\");\nexport default Dpapi;\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\n/**\n * Specifies the scope of the data protection - either the current user or the local\n * machine.\n *\n * You do not need a key to protect or unprotect the data.\n * If you set the Scope to CurrentUser, only applications running on your credentials can\n * unprotect the data; however, that means that any application running on your credentials\n * can access the protected data. If you set the Scope to LocalMachine, any full-trust\n * application on the computer can unprotect, access, and modify the data.\n *\n */\nexport enum DataProtectionScope {\n CurrentUser = \"CurrentUser\",\n LocalMachine = \"LocalMachine\",\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { IPersistence } from \"./IPersistence\";\nimport { FilePersistence } from \"./FilePersistence\";\nimport { PersistenceError } from \"../error/PersistenceError\";\nimport { Dpapi } from \"../Dpapi\";\nimport { DataProtectionScope } from \"./DataProtectionScope\";\nimport { Logger, LoggerOptions } from \"@azure/msal-common\";\nimport { dirname } from \"path\";\nimport { BasePersistence } from \"./BasePersistence\";\n\n/**\n * Uses CryptProtectData and CryptUnprotectData on Windows to encrypt and decrypt file contents.\n *\n * scope: Scope of the data protection. Either local user or the current machine\n * optionalEntropy: Password or other additional entropy used to encrypt the data\n */\nexport class FilePersistenceWithDataProtection extends BasePersistence implements IPersistence {\n\n private filePersistence: FilePersistence;\n private scope: DataProtectionScope;\n private optionalEntropy: Uint8Array;\n\n private constructor(scope: DataProtectionScope, optionalEntropy?: string) {\n super();\n this.scope = scope;\n this.optionalEntropy = optionalEntropy ? Buffer.from(optionalEntropy, \"utf-8\") : null;\n }\n\n public static async create(\n fileLocation: string,\n scope: DataProtectionScope,\n optionalEntropy?: string,\n loggerOptions?: LoggerOptions): Promise<FilePersistenceWithDataProtection> {\n\n const persistence = new FilePersistenceWithDataProtection(scope, optionalEntropy);\n persistence.filePersistence = await FilePersistence.create(fileLocation, loggerOptions);\n return persistence;\n }\n\n public async save(contents: string): Promise<void> {\n try {\n const encryptedContents = Dpapi.protectData(\n Buffer.from(contents, \"utf-8\"),\n this.optionalEntropy,\n this.scope.toString());\n await this.filePersistence.saveBuffer(encryptedContents);\n } catch (err) {\n throw PersistenceError.createFilePersistenceWithDPAPIError(err.message);\n }\n }\n\n public async load(): Promise<string | null> {\n try {\n const encryptedContents = await this.filePersistence.loadBuffer();\n if (typeof encryptedContents === \"undefined\" || !encryptedContents || 0 === encryptedContents.length) {\n this.filePersistence.getLogger().info(\"Encrypted contents loaded from file were null or empty\");\n return null;\n }\n return Dpapi.unprotectData(\n encryptedContents,\n this.optionalEntropy,\n this.scope.toString()).toString();\n } catch (err) {\n throw PersistenceError.createFilePersistenceWithDPAPIError(err.message);\n }\n }\n\n public async delete(): Promise<boolean> {\n return this.filePersistence.delete();\n }\n\n public async reloadNecessary(lastSync: number): Promise<boolean> {\n return this.filePersistence.reloadNecessary(lastSync);\n }\n\n public getFilePath(): string {\n return this.filePersistence.getFilePath();\n }\n\n public getLogger(): Logger {\n return this.filePersistence.getLogger();\n }\n\n public createForPersistenceValidation(): Promise<FilePersistenceWithDataProtection> {\n const testCacheFileLocation = `${dirname(this.filePersistence.getFilePath())}/test.cache`;\n return FilePersistenceWithDataProtection.create(testCacheFileLocation, DataProtectionScope.CurrentUser);\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { setPassword, getPassword, deletePassword } from \"keytar\";\nimport { FilePersistence } from \"./FilePersistence\";\nimport { IPersistence } from \"./IPersistence\";\nimport { PersistenceError } from \"../error/PersistenceError\";\nimport { Logger, LoggerOptions } from \"@azure/msal-common\";\nimport { dirname } from \"path\";\nimport { BasePersistence } from \"./BasePersistence\";\n\n/**\n * Uses reads and writes passwords to macOS keychain\n *\n * serviceName: Identifier used as key for whatever value is stored\n * accountName: Account under which password should be stored\n */\nexport class KeychainPersistence extends BasePersistence implements IPersistence {\n\n protected readonly serviceName;\n protected readonly accountName;\n private filePersistence: FilePersistence;\n\n private constructor(serviceName: string, accountName: string) {\n super();\n this.serviceName = serviceName;\n this.accountName = accountName;\n }\n\n public static async create(\n fileLocation: string,\n serviceName: string,\n accountName: string,\n loggerOptions?: LoggerOptions): Promise<KeychainPersistence> {\n\n const persistence = new KeychainPersistence(serviceName, accountName);\n persistence.filePersistence = await FilePersistence.create(fileLocation, loggerOptions);\n return persistence;\n }\n\n public async save(contents: string): Promise<void> {\n try {\n await setPassword(this.serviceName, this.accountName, contents);\n } catch (err) {\n throw PersistenceError.createKeychainPersistenceError(err.message);\n }\n // Write dummy data to update file mtime\n await this.filePersistence.save(\"{}\");\n }\n\n public async load(): Promise<string | null> {\n try{\n return await getPassword(this.serviceName, this.accountName);\n } catch(err){\n throw PersistenceError.createKeychainPersistenceError(err.message);\n }\n }\n\n public async delete(): Promise<boolean> {\n try {\n await this.filePersistence.delete();\n return await deletePassword(this.serviceName, this.accountName);\n } catch (err) {\n throw PersistenceError.createKeychainPersistenceError(err.message);\n }\n }\n\n public async reloadNecessary(lastSync: number): Promise<boolean> {\n return this.filePersistence.reloadNecessary(lastSync);\n }\n\n public getFilePath(): string {\n return this.filePersistence.getFilePath();\n }\n\n public getLogger(): Logger {\n return this.filePersistence.getLogger();\n }\n \n public createForPersistenceValidation(): Promise<KeychainPersistence> {\n const testCacheFileLocation = `${dirname(this.filePersistence.getFilePath())}/test.cache`;\n return KeychainPersistence.create(\n testCacheFileLocation, \n \"persistenceValidationServiceName\", \"persistencValidationAccountName\"\n );\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { setPassword, getPassword, deletePassword } from \"keytar\";\nimport { FilePersistence } from \"./FilePersistence\";\nimport { IPersistence } from \"./IPersistence\";\nimport { PersistenceError } from \"../error/PersistenceError\";\nimport { Logger, LoggerOptions } from \"@azure/msal-common\";\nimport { dirname } from \"path\";\nimport { BasePersistence } from \"./BasePersistence\";\n\n/**\n * Uses reads and writes passwords to Secret Service API/libsecret. Requires libsecret\n * to be installed.\n *\n * serviceName: Identifier used as key for whatever value is stored\n * accountName: Account under which password should be stored\n */\nexport class LibSecretPersistence extends BasePersistence implements IPersistence {\n\n protected readonly serviceName;\n protected readonly accountName;\n private filePersistence: FilePersistence;\n\n private constructor(serviceName: string, accountName: string) {\n super();\n this.serviceName = serviceName;\n this.accountName = accountName;\n }\n\n public static async create(\n fileLocation: string,\n serviceName: string,\n accountName: string,\n loggerOptions?: LoggerOptions): Promise<LibSecretPersistence> {\n\n const persistence = new LibSecretPersistence(serviceName, accountName);\n persistence.filePersistence = await FilePersistence.create(fileLocation, loggerOptions);\n return persistence;\n }\n\n public async save(contents: string): Promise<void> {\n try {\n await setPassword(this.serviceName, this.accountName, contents);\n } catch (err) {\n throw PersistenceError.createLibSecretError(err.message);\n }\n // Write dummy data to update file mtime\n await this.filePersistence.save(\"{}\");\n }\n\n public async load(): Promise<string | null> {\n try {\n return await getPassword(this.serviceName, this.accountName);\n } catch (err) {\n throw PersistenceError.createLibSecretError(err.message);\n }\n }\n\n public async delete(): Promise<boolean> {\n try {\n await this.filePersistence.delete();\n return await deletePassword(this.serviceName, this.accountName);\n } catch (err) {\n throw PersistenceError.createLibSecretError(err.message);\n }\n }\n\n public async reloadNecessary(lastSync: number): Promise<boolean> {\n return this.filePersistence.reloadNecessary(lastSync);\n }\n\n public getFilePath(): string {\n return this.filePersistence.getFilePath();\n }\n\n public getLogger(): Logger {\n return this.filePersistence.getLogger();\n }\n \n public createForPersistenceValidation(): Promise<LibSecretPersistence> {\n const testCacheFileLocation = `${dirname(this.filePersistence.getFilePath())}/test.cache`;\n return LibSecretPersistence.create(\n testCacheFileLocation, \n \"persistenceValidationServiceName\", \"persistencValidationAccountName\"\n );\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport path from \"path\";\nimport { Constants, Platform } from \"./Constants\";\nimport { PersistenceError } from \"../error/PersistenceError\";\nimport { StringUtils } from \"@azure/msal-common\";\n\nexport class Environment {\n static get homeEnvVar(): string {\n return this.getEnvironmentVariable(Constants.ENVIRONMENT.HOME);\n }\n \n static get lognameEnvVar(): string {\n return this.getEnvironmentVariable(Constants.ENVIRONMENT.LOGNAME);\n }\n\n static get userEnvVar(): string {\n return this.getEnvironmentVariable(Constants.ENVIRONMENT.USER);\n }\n\n static get lnameEnvVar(): string {\n return this.getEnvironmentVariable(Constants.ENVIRONMENT.LNAME);\n }\n\n static get usernameEnvVar(): string {\n return this.getEnvironmentVariable(Constants.ENVIRONMENT.USERNAME);\n }\n\n static getEnvironmentVariable(name: string): string {\n return process.env[name];\n }\n\n static getEnvironmentPlatform(): string {\n return process.platform;\n }\n\n static isWindowsPlatform(): boolean {\n return this.getEnvironmentPlatform() === Platform.WINDOWS;\n }\n\n static isLinuxPlatform(): boolean {\n return this.getEnvironmentPlatform() === Platform.LINUX;\n }\n\n static isMacPlatform(): boolean {\n return this.getEnvironmentPlatform() === Platform.MACOS;\n }\n\n static isLinuxRootUser(): boolean {\n return process.getuid() === Constants.LINUX_ROOT_USER_GUID;\n }\n\n static getUserRootDirectory(): string {\n return !this.isWindowsPlatform ?\n this.getUserHomeDirOnUnix() :\n this.getUserHomeDirOnWindows();\n }\n\n static getUserHomeDirOnWindows(): string {\n return this.getEnvironmentVariable(Constants.ENVIRONMENT.LOCAL_APPLICATION_DATA);\n }\n\n static getUserHomeDirOnUnix(): string | null {\n if (this.isWindowsPlatform()) {\n throw PersistenceError.createNotSupportedError(\n \"Getting the user home directory for unix is not supported in windows\");\n }\n\n if (!StringUtils.isEmpty(this.homeEnvVar)) {\n return this.homeEnvVar;\n }\n\n let username = null;\n if (!StringUtils.isEmpty(this.lognameEnvVar)) {\n username = this.lognameEnvVar;\n } else if (!StringUtils.isEmpty(this.userEnvVar)) {\n username = this.userEnvVar;\n } else if (!StringUtils.isEmpty(this.lnameEnvVar)) {\n username = this.lnameEnvVar;\n } else if (!StringUtils.isEmpty(this.usernameEnvVar)) {\n username = this.usernameEnvVar;\n }\n\n if (this.isMacPlatform()) {\n return !StringUtils.isEmpty(username) ? path.join(\"/Users\", username) : null;\n } else if (this.isLinuxPlatform()) {\n if (this.isLinuxRootUser()) {\n return \"/root\";\n } else {\n return !StringUtils.isEmpty(username) ? path.join(\"/home\", username) : null;\n }\n } else {\n throw PersistenceError.createNotSupportedError(\n \"Getting the user home directory for unix is not supported in windows\");\n }\n\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { FilePersistenceWithDataProtection } from \"./FilePersistenceWithDataProtection\";\nimport { LibSecretPersistence } from \"./LibSecretPersistence\";\nimport { KeychainPersistence } from \"./KeychainPersistence\";\nimport { DataProtectionScope } from \"./DataProtectionScope\";\nimport { Environment } from \"../utils/Environment\";\nimport { IPersistence } from \"./IPersistence\";\nimport { FilePersistence } from \"./FilePersistence\";\nimport { PersistenceError } from \"../error/PersistenceError\";\nimport { IPersistenceConfiguration } from \"./IPersistenceConfiguration\";\n\nexport class PersistenceCreator {\n static async createPersistence(config: IPersistenceConfiguration): Promise<IPersistence> {\n let peristence: IPersistence;\n\n // On Windows, uses a DPAPI encrypted file\n if (Environment.isWindowsPlatform()) {\n if (!config.cachePath || !config.dataProtectionScope) {\n throw PersistenceError.createPersistenceNotValidatedError(\n \"Cache path and/or data protection scope not provided for the FilePersistenceWithDataProtection cache plugin\");\n }\n\n peristence = await FilePersistenceWithDataProtection.create(config.cachePath, DataProtectionScope.CurrentUser, undefined, config.loggerOptions);\n }\n\n // On Mac, uses keychain.\n else if (Environment.isMacPlatform()) {\n if (!config.cachePath || !config.serviceName || !config.accountName) {\n throw PersistenceError.createPersistenceNotValidatedError(\n \"Cache path, service name and/or account name not provided for the KeychainPersistence cache plugin\");\n }\n\n peristence = await KeychainPersistence.create(config.cachePath, config.serviceName, config.accountName, config.loggerOptions);\n }\n\n // On Linux, uses libsecret to store to secret service. Libsecret has to be installed.\n else if (Environment.isLinuxPlatform()) {\n if (!config.cachePath || !config.serviceName || !config.accountName) {\n throw PersistenceError.createPersistenceNotValidatedError(\n \"Cache path, service name and/or account name not provided for the LibSecretPersistence cache plugin\");\n }\n\n peristence = await LibSecretPersistence.create(config.cachePath, config.serviceName, config.accountName, config.loggerOptions);\n }\n\n else {\n throw PersistenceError.createNotSupportedError(\n \"The current environment is not supported by msal-node-extensions yet.\");\n }\n\n // Initially suppress the error thrown during persistence verification to allow us to fallback to plain text\n const isPersistenceVerified = await peristence.verifyPersistence().catch(() => false);\n\n if (!isPersistenceVerified) {\n if (Environment.isLinuxPlatform() && config.usePlaintextFileOnLinux) {\n if (!config.cachePath) {\n throw PersistenceError.createPersistenceNotValidatedError(\n \"Cache path not provided for the FilePersistence cache plugin\");\n }\n\n peristence = await FilePersistence.create(config.cachePath, config.loggerOptions);\n\n const isFilePersistenceVerified = await peristence.verifyPersistence();\n if (isFilePersistenceVerified) {\n return peristence;\n }\n }\n\n throw PersistenceError.createPersistenceNotVerifiedError(\"Persistence could not be verified\");\n }\n\n return peristence;\n }\n}\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { AuthError } from \"@azure/msal-common\";\n\nexport class NativeAuthError extends AuthError {\n public statusCode: number;\n public tag: number;\n\n constructor(errorStatus: string, errorContext: string, errorCode: number, errorTag: number) {\n super(errorStatus, errorContext);\n this.name = \"NativeAuthError\";\n this.statusCode = errorCode;\n this.tag = errorTag;\n Object.setPrototypeOf(this, NativeAuthError.prototype);\n }\n}\n","/* eslint-disable header/header */\nexport const name = \"@azure/msal-node-extensions\";\nexport const version = \"1.0.0-alpha.31\";\n","/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { AccountInfo, AuthenticationResult, AuthenticationScheme, ClientAuthError, ClientConfigurationError, Constants, IdTokenClaims, INativeBrokerPlugin, InteractionRequiredAuthError, Logger, LoggerOptions, NativeRequest, NativeSignOutRequest, PromptValue, ServerError } from \"@azure/msal-common\";\nimport { msalNodeRuntime, Account, AuthParameters, AuthResult, ErrorStatus, MsalRuntimeError, ReadAccountResult, DiscoverAccountsResult, SignOutResult, LogLevel as MsalRuntimeLogLevel} from \"@azure/msal-node-runtime\";\nimport { ErrorCodes } from \"../utils/Constants\";\nimport { NativeAuthError } from \"../error/NativeAuthError\";\nimport { version, name } from \"../packageMetadata\";\n\nexport class NativeBrokerPlugin implements INativeBrokerPlugin {\n private logger: Logger;\n isBrokerAvailable: boolean;\n \n constructor() {\n const defaultLoggerOptions: LoggerOptions = {\n loggerCallback: (): void => {\n // Empty logger callback\n },\n piiLoggingEnabled: false\n };\n this.logger = new Logger(defaultLoggerOptions, name, version); // Default logger\n this.isBrokerAvailable = msalNodeRuntime.StartupError ? false : true;\n }\n\n setLogger(loggerOptions: LoggerOptions): void {\n this.logger = new Logger(loggerOptions, name, version);\n const logCallback = (message: string, logLevel: MsalRuntimeLogLevel, containsPii: boolean) => {\n switch(logLevel) {\n case MsalRuntimeLogLevel.Trace:\n if (containsPii) {\n this.logger.tracePii(message);\n } else {\n this.logger.trace(message);\n }\n break;\n case MsalRuntimeLogLevel.Debug: \n if (containsPii) {\n this.logger.tracePii(message);\n } else {\n this.logger.trace(message);\n }\n break;\n case MsalRuntimeLogLevel.Info:\n if (containsPii) {\n this.logger.infoPii(message);\n } else {\n this.logger.info(message);\n }\n break;\n case MsalRuntimeLogLevel.Warning:\n if (containsPii) {\n this.logger.warningPii(message);\n } else {\n this.logger.warning(message);\n }\n break;\n case MsalRuntimeLogLevel.Error:\n if (containsPii) {\n this.logger.errorPii(message);\n } else {\n this.logger.error(message);\n }\n break;\n case MsalRuntimeLogLevel.Fatal:\n if (containsPii) {\n this.logger.errorPii(message);\n } else {\n this.logger.error(message);\n }\n break;\n default:\n if (containsPii) {\n this.logger.infoPii(message);\n } else {\n this.logger.info(message);\n }\n break; \n }\n };\n try {\n msalNodeRuntime.RegisterLogger(logCallback, loggerOptions.piiLoggingEnabled);\n } catch (e) {\n const wrappedError = this.wrapError(e);\n if (wrappedError) {\n throw wrappedError;\n }\n }\n }\n\n async getAccountById(accountId: string, correlationId: string): Promise<AccountInfo> {\n this.logger.trace(\"NativeBrokerPlugin - getAccountById called\", correlationId);\n const readAccountResult = await this.readAccountById(accountId, correlationId);\n return this.generateAccountInfo(readAccountResult.account);\n }\n\n async getAllAccounts(clientId:string, correlationId: string): Promise<AccountInfo[]> {\n this.logger.trace(\"NativeBrokerPlugin - getAllAccounts called\", correlationId);\n return new Promise((resolve, reject) => {\n const resultCallback = (result: DiscoverAccountsResult) => {\n try {\n result.CheckError();\n } catch (e) {\n const wrappedError = this.wrapError(e);\n if (wrappedError) {\n reject(wrappedError);\n return;\n }\n }\n\n const accountInfoResult = [];\n result.accounts.forEach((account: Account) => {\n accountInfoResult.push(this.generateAccountInfo(account));\n });\n resolve(accountInfoResult);\n };\n\n try {\n msalNodeRuntime.DiscoverAccountsAsync(clientId, correlationId, resultCallback);\n } catch (e) {\n const wrappedError = this.wrapError(e);\n if (wrappedError) {\n reject(wrappedError);\n }\n }\n });\n }\n\n async acquireTokenSilent(request: NativeRequest): Promise<AuthenticationResult> {\n this.logger.trace(\"NativeBrokerPlugin - acquireTokenSilent called\", request.correlationId);\n const authParams = this.generateRequestParameters(request);\n const account = await this.getAccount(request);\n\n return new Promise((resolve: (value: AuthenticationResult) => void, reject) => {\n const resultCallback = (result: AuthResult) => {\n try {\n result.CheckError();\n } catch (e) {\n const wrappedError = this.wrapError(e);\n if (wrappedError) {\n reject(wrappedError);\n return;\n }\n }\n const authenticationResult = this.getAuthenticationResult(request, result);\n resolve(authenticationResult);\n };\n\n try {\n if (account) {\n msalNodeRuntime.AcquireTokenSilentlyAsync(authParams, request.correlationId, account, resultCallback);\n } else {\n msalNodeRuntime.SignInSilentlyAsync(authParams, request.correlationId, resultCallback);\n }\n } catch (e) {\n const wrappedError = this.wrapError(e);\n if (wrappedError) {\n reject(wrappedError);\n }\n }\n });\n }\n\n async acquireTokenInteractive(request: NativeRequest, providedWindowHandle?: Buffer): Promise<AuthenticationResult> {\n this.logger.trace(\"NativeBrokerPlugin - acquireTokenInteractive called\", request.correlationId);\n const authParams = this.generateRequestParameters(request);\n const account = await this.getAccount(request);\n const windowHandle = providedWindowHandle || Buffer.from([0]);\n\n return new Promise((resolve: (value: AuthenticationResult) => void, reject) => {\n const resultCallback = (result: AuthResult) => {\n try {\n result.CheckError();\n } catch (e) {\n const wrappedError = this.wrapError(e);\n if (wrappedError) {\n reject(wrappedError);\n return;\n }\n }\n const authenticationResult = this.getAuthenticationResult(request, result);\n resolve(authenticationResult);\n };\n\n try {\n switch (request.prompt) {\n case PromptValue.LOGIN:\n case PromptValue.SELECT_ACCOUNT:\n case PromptValue.CREATE:\n this.logger.info(\"Calling native interop SignInInteractively API\", request.correlationId);\n const loginHint = request.loginHint || Constants.EMPTY_STRING;\n msalNodeRuntime.SignInInteractivelyAsync(windowHandle, authParams, request.correlationId, loginHint, resultCallback);\n break;\n case PromptValue.NONE:\n if (account) {\n this.logger.info(\"Calling native interop AcquireTokenSilently API\", request.correlationId);\n msalNodeRuntime.AcquireTokenSilentlyAsync(authParams, request.correlationId, account, resultCallback);\n } else {\n this.logger.info(\"Calling native interop SignInSilently API\", request.correlationId);\n msalNodeRuntime.SignInSilentlyAsync(authParams, request.correlationId, resultCallback);\n }\n break;\n default:\n if (account) {\n this.logger.info(\"Calling native interop AcquireTokenInteractively API\", request.correlationId);\n msalNodeRuntime.AcquireTokenInteractivelyAsync(windowHandle, authParams, request.correlationId, account, resultCallback);\n } else {\n this.logger.info(\"Calling native interop SignIn API\", request.correlationId);\n const loginHint = request.loginHint || Constants.EMPTY_STRING;\n msalNodeRuntime.SignInAsync(windowHandle, authParams, request.correlationId, loginHint, resultCallback);\n }\n break;\n }\n } catch (e) {\n const wrappedError = this.wrapError(e);\n if (wrappedError) {\n reject(wrappedError);\n }\n }\n });\n }\n\n async signOut(request: NativeSignOutRequest): Promise<void> {\n this.logger.trace(\"NativeBrokerPlugin - signOut called\", request.correlationId);\n\n const account = await this.getAccount(request);\n if (!account) {\n throw ClientAuthError.createNoAccountFoundError();\n }\n\n return new Promise((resolve, reject) => {\n const resultCallback = (result: SignOutResult) => {\n try {\n result.CheckError();\n } catch (e) {\n const wrappedError = this.wrapError(e);\n if (wrappedError) {\n reject(wrappedError);\n return;\n }\n }\n resolve();\n };\n\n try {\n msalNodeRuntime.SignOutSilentlyAsync(request.clientId, request.correlationId, account, resultCallback);\n } catch (e) {\n const wrappedError = this.wrapError(e);\n if (wrappedError) {\n reject(wrappedError);\n }\n }\n });\n }\n\n private async getAccount(request: NativeRequest | NativeSignOutRequest): Promise<Account|null> {\n if (request.accountId) {\n const readAccountResult = await this.readAccountById(request.accountId, request.correlationId);\n return readAccountResult.account;\n }\n return null;\n }\n\n private async readAccountById(accountId: string, correlationId: string): Promise<ReadAccountResult> {\n this.logger.trace(\"NativeBrokerPlugin - readAccountById called\", correlationId);\n\n return new Promise((resolve, reject) => {\n const resultCallback = (result: ReadAccountResult) => {\n try {\n result.CheckError();\n } catch (e) {\n const wrappedError = this.wrapError(e);\n if (wrappedError) {\n reject(wrappedError);\n return;\n }\n }\n resolve(result);\n };\n\n try {\n msalNodeRuntime.ReadAccountByIdAsync(accountId, correlationId, resultCallback);\n } catch (e) {\n const wrappedError = this.wrapError(e);\n if (wrappedError) {\n reject(wrappedError);\n }\n }\n });\n }\n\n private generateRequestParameters(request: NativeRequest): AuthParameters {\n this.logger.trace(\"NativeBrokerPlugin - generateRequestParameters called\", request.correlationId);\n const authParams = new msalNodeRuntime.AuthParameters();\n\n try{\n authParams.CreateAuthParameters(request.clientId, request.authority);\n authParams.SetRedirectUri(request.redirectUri);\n authParams.SetRequestedScopes(request.scopes.join(\" \"));\n \n if (request.claims) {\n authParams.SetDecodedClaims(request.claims);\n }\n \n if (request.authenticationScheme === AuthenticationScheme.POP) {\n if (!request.resourceRequestMethod || !request.resourceRequestUri || !request.shrNonce) {\n throw new Error(\"Authentication Scheme set to POP but one or more of the following parameters are missing: resourceRequestMethod, resourceRequestUri, shrNonce\");\n }\n const resourceUrl = new URL(request.resourceRequestUri);\n authParams.SetPopParams(request.resourceRequestMethod, resourceUrl.host, resourceUrl.pathname, request.shrNonce);\n }\n \n if (request.extraParameters) {\n Object.keys(request.extraParameters).forEach((key) => {\n authParams.SetAdditionalParameter(key, request.extraParameters[key]);\n });\n }\n } catch (e) {\n const wrappedError = this.wrapError(e);\n if (wrappedError) {\n throw wrappedError;\n }\n }\n\n return authParams;\n }\n\n private getAuthenticationResult(request: NativeRequest, authResult: AuthResult): AuthenticationResult {\n this.logger.trace(\"NativeBrokerPlugin - getAuthenticationResult called\", request.correlationId);\n \n let fromCache: boolean;\n try {\n const telemetryJSON = JSON.parse(authResult.telemetryData);\n fromCache = !!telemetryJSON[\"is_cache\"];\n } catch (e) {\n this.logger.error(\"NativeBrokerPlugin: getAuthenticationResult - Error parsing telemetry data. Could not determine if response came from cache.\", request.correlationId);\n }\n\n let idTokenClaims: IdTokenClaims;\n try {\n idTokenClaims = JSON.parse(authResult.idToken);\n } catch (e) {\n throw new Error(\"Unable to parse idToken claims\");\n }\n\n const accountInfo = this.generateAccountInfo(authResult.account, idTokenClaims);\n\n const result: AuthenticationResult = {\n authority: request.authority,\n uniqueId: idTokenClaims.oid || idTokenClaims.sub || \"\",\n tenantId: idTokenClaims.tid || \"\",\n scopes: authResult.grantedScopes.split(\" \"),\n account: accountInfo,\n idToken: authResult.rawIdToken,\n idTokenClaims: idTokenClaims,\n accessToken: authResult.accessToken,\n fromCache: fromCache,\n expiresOn: new Date(authResult.expiresOn * 1000),\n tokenType: authResult.isPopAuthorization ? AuthenticationScheme.POP : AuthenticationScheme.BEARER,\n correlationId: request.correlationId,\n fromNativeBroker: true\n };\n return result;\n }\n\n private generateAccountInfo(account: Account, idTokenClaims?: IdTokenClaims): AccountInfo {\n this.logger.trace(\"NativeBrokerPlugin - generateAccountInfo called\");\n\n const accountInfo: AccountInfo = {\n homeAccountId: account.homeAccountId,\n environment: account.environment,\n tenantId: account.realm,\n username: account.username,\n localAccountId: account.localAccountId,\n name: account.displayName,\n idTokenClaims: idTokenClaims,\n nativeAccountId: account.accountId\n };\n return accountInfo;\n }\n\n private isMsalRuntimeError(result: Object): boolean {\n return result.hasOwnProperty(\"errorCode\") ||\n result.hasOwnProperty(\"errorStatus\") ||\n result.hasOwnProperty(\"errorContext\") ||\n result.hasOwnProperty(\"errorTag\");\n }\n\n private wrapError(error: Object): NativeAuthError | Object | null {\n if (this.isMsalRuntimeError(error)) {\n const { errorCode, errorStatus, errorContext, errorTag } = error as MsalRuntimeError;\n switch (errorStatus) {\n case ErrorStatus.InteractionRequired:\n case ErrorStatus.AccountUnusable:\n return new InteractionRequiredAuthError(ErrorCodes.INTERATION_REQUIRED_ERROR_CODE, errorContext);\n case ErrorStatus.NoNetwork:\n case ErrorStatus.NetworkTemporarilyUnavailable:\n return ClientAuthError.createNoNetworkConnectivityError();\n case ErrorStatus.ServerTemporarilyUnavailable:\n return new ServerError(ErrorCodes.SERVER_UNAVAILABLE, errorContext);\n case ErrorStatus.UserCanceled:\n return ClientAuthError.createUserCanceledError();\n case ErrorStatus.AuthorityUntrusted:\n return ClientConfigurationError.createUntrustedAuthorityError();\n case ErrorStatus.UserSwitched:\n // Not an error case, if there's customer demand we can surface this as a response property\n return null;\n case ErrorStatus.AccountNotFound:\n return ClientAuthError.createNoAccountFoundError();\n default:\n return new NativeAuthError(ErrorStatus[errorStatus], errorContext, errorCode, errorTag);\n }\n }\n\n return error;\n }\n}\n"],"names":["Constants","EEXIST_ERROR","ENOENT_ERROR","EPERM_ERROR","DEFAULT_SERVICE_NAME","PERSISTENCE_TEST_DATA","LINUX_ROOT_USER_GUID","ENVIRONMENT","HOME","LOGNAME","USER","LNAME","USERNAME","PLATFORM","LOCAL_APPLICATION_DATA","DEFAULT_CACHE_FILE_NAME","Platform","ErrorCodes","PersistenceError","Error","constructor","errorCode","errorMessage","errorString","Object","setPrototypeOf","prototype","name","createFileSystemError","createLibSecretError","createKeychainPersistenceError","createFilePersistenceWithDPAPIError","createCrossPlatformLockError","createCachePersistenceError","createNotSupportedError","createPersistenceNotVerifiedError","createPersistenceNotValidatedError","CrossPlatformLock","lockFilePath","logger","lockOptions","retryNumber","retryDelay","lock","tryCount","info","pid","lockFileHandle","fs","open","write","toString","err","code","sleep","error","message","unlock","unlink","close","warning","ms","Promise","resolve","setTimeout","PersistenceCachePlugin","persistence","getLogger","getFilePath","crossPlatformLock","lastSync","currentCache","beforeCacheAccess","cacheContext","reloadNecessary","cacheHasChanged","verbose","load","Date","getTime","tokenCache","deserialize","afterCacheAccess","serialize","save","BasePersistence","verifyPersistence","persistenceValidator","createForPersistenceValidation","retrievedDummyData","delete","e","FilePersistence","create","fileLocation","loggerOptions","filePersistence","filePath","Logger","createDefaultLoggerOptions","createCacheFile","contents","writeFile","saveBuffer","readFile","loadBuffer","timeLastModified","testCacheFileLocation","dirname","loggerCallback","piiLoggingEnabled","logLevel","LogLevel","Info","stats","stat","mtime","createFileDirectory","fileHandle","mkdir","recursive","Dpapi","require","DataProtectionScope","FilePersistenceWithDataProtection","scope","optionalEntropy","Buffer","from","encryptedContents","protectData","length","unprotectData","CurrentUser","KeychainPersistence","serviceName","accountName","setPassword","getPassword","deletePassword","LibSecretPersistence","Environment","homeEnvVar","getEnvironmentVariable","lognameEnvVar","userEnvVar","lnameEnvVar","usernameEnvVar","process","env","getEnvironmentPlatform","platform","isWindowsPlatform","WINDOWS","isLinuxPlatform","LINUX","isMacPlatform","MACOS","isLinuxRootUser","getuid","getUserRootDirectory","getUserHomeDirOnUnix","getUserHomeDirOnWindows","StringUtils","isEmpty","username","path","join","PersistenceCreator","createPersistence","config","peristence","cachePath","dataProtectionScope","undefined","isPersistenceVerified","catch","usePlaintextFileOnLinux","isFilePersistenceVerified","NativeAuthError","AuthError","errorStatus","errorContext","errorTag","statusCode","tag","version","NativeBrokerPlugin","defaultLoggerOptions","isBrokerAvailable","msalNodeRuntime","StartupError","setLogger","logCallback","containsPii","MsalRuntimeLogLevel","Trace","tracePii","trace","Debug","infoPii","Warning","warningPii","errorPii","Fatal","RegisterLogger","wrappedError","wrapError","getAccountById","accountId","correlationId","readAccountResult","readAccountById","generateAccountInfo","account","getAllAccounts","clientId","reject","resultCallback","result","CheckError","accountInfoResult","accounts","forEach","push","DiscoverAccountsAsync","acquireTokenSilent","request","authParams","generateRequestParameters","getAccount","authenticationResult","getAuthenticationResult","AcquireTokenSilentlyAsync","SignInSilentlyAsync","acquireTokenInteractive","providedWindowHandle","windowHandle","prompt","PromptValue","LOGIN","SELECT_ACCOUNT","CREATE","loginHint","EMPTY_STRING","SignInInteractivelyAsync","NONE","AcquireTokenInteractivelyAsync","SignInAsync","signOut","ClientAuthError","createNoAccountFoundError","SignOutSilentlyAsync","ReadAccountByIdAsync","AuthParameters","CreateAuthParameters","authority","SetRedirectUri","redirectUri","SetRequestedScopes","scopes","claims","SetDecodedClaims","authenticationScheme","AuthenticationScheme","POP","resourceRequestMethod","resourceRequestUri","shrNonce","resourceUrl","URL","SetPopParams","host","pathname","extraParameters","keys","key","SetAdditionalParameter","authResult","fromCache","telemetryJSON","JSON","parse","telemetryData","idTokenClaims","idToken","accountInfo","uniqueId","oid","sub","tenantId","tid","grantedScopes","split","rawIdToken","accessToken","expiresOn","tokenType","isPopAuthorization","BEARER","fromNativeBroker","homeAccountId","environment","realm","localAccountId","displayName","nativeAccountId","isMsalRuntimeError","hasOwnProperty","ErrorStatus","InteractionRequired","AccountUnusable","InteractionRequiredAuthError","INTERATION_REQUIRED_ERROR_CODE","NoNetwork","NetworkTemporarilyUnavailable","createNoNetworkConnectivityError","ServerTemporarilyUnavailable","ServerError","SERVER_UNAVAILABLE","UserCanceled","createUserCanceledError","AuthorityU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D,2BAAW,CAACE,eAAe;UAC5B,OAAO,IAAIC,uCAA4B,CAACvS,UAAU,CAACwS,8BAA8B,EAAEnI,YAAY,CAAC;QACpG,KAAK+H,2BAAW,CAACK,SAAS;QAC1B,KAAKL,2BAAW,CAACM,6BAA6B;UAC1C,OAAOjE,0BAAe,CAACkE,gCAAgC,EAAE;QAC7D,KAAKP,2BAAW,CAACQ,4BAA4B;UACzC,OAAO,IAAIC,sBAAW,CAAC7S,UAAU,CAAC8S,kBAAkB,EAAEzI,YAAY,CAAC;QACvE,KAAK+H,2BAAW,CAACW,YAAY;UACzB,OAAOtE,0BAAe,CAACuE,uBAAuB,EAAE;QACpD,KAAKZ,2BAAW,CAACa,kBAAkB;UAC/B,OAAOC,mCAAwB,CAACC,6BAA6B,EAAE;QACnE,KAAKf,2BAAW,CAACgB,YAAY;;UAEzB,OAAO,IAAI;QACf,KAAKhB,2BAAW,CAACiB,eAAe;UAC5B,OAAO5E,0BAAe,CAACC,yBAAyB,EAAE;QACtD;UACI,OAAO,IAAIxE,eAAe,CAACkI,2BAAW,CAAChI,WAAW,CAAC,EAAEC,YAAY,EAAEjK,SAAS,EAAEkK,QAAQ,CAAC;;;IAInG,OAAOhI,KAAK;;;;;;;;;;;;;"}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,t,r=require("fs"),i=require("process"),s=require("path"),a=(e=s)&&"object"==typeof e&&"default"in e?e.default:e,c=require("@azure/msal-common"),o=require("keytar");!function(e){e.WINDOWS="win32",e.LINUX="linux",e.MACOS="darwin"}(t||(t={}));class n extends Error{constructor(e,t){super(t?`${e}: ${t}`:e),Object.setPrototypeOf(this,n.prototype),this.errorCode=e,this.errorMessage=t,this.name="PersistenceError"}static createFileSystemError(e,t){return new n(e,t)}static createLibSecretError(e){return new n("GnomeKeyringError",e)}static createKeychainPersistenceError(e){return new n("KeychainError",e)}static createFilePersistenceWithDPAPIError(e){return new n("DPAPIEncryptedFileError",e)}static createCrossPlatformLockError(e){return new n("CrossPlatformLockError",e)}static createCachePersistenceError(e){return new n("CachePersistenceError",e)}static createNotSupportedError(e){return new n("NotSupportedError",e)}static createPersistenceNotVerifiedError(e){return new n("PersistenceNotVerifiedError",e)}static createPersistenceNotValidatedError(e){return new n("PersistenceNotValidatedError",e)}}class l{constructor(e,t,r){this.lockFilePath=e,this.retryNumber=r?r.retryNumber:500,this.retryDelay=r?r.retryDelay:100,this.logger=t}async lock(){for(let e=0;e<this.retryNumber;e++)try{return this.logger.info(`Pid ${i.pid} trying to acquire lock`),this.lockFileHandle=await r.promises.open(this.lockFilePath,"wx+"),this.logger.info(`Pid ${i.pid} acquired lock`),void await this.lockFileHandle.write(i.pid.toString())}catch(e){if("EEXIST"!==e.code&&"EPERM"!==e.code)throw this.logger.error(`${i.pid} was not able to acquire lock. Ran into error: ${e.message}`),n.createCrossPlatformLockError(e.message);this.logger.info(e),await this.sleep(this.retryDelay)}throw this.logger.error(i.pid+" was not able to acquire lock. Exceeded amount of retries set in the options"),n.createCrossPlatformLockError("Not able to acquire lock. Exceeded amount of retries set in options")}async unlock(){try{this.lockFileHandle?(await r.promises.unlink(this.lockFilePath),await this.lockFileHandle.close(),this.logger.info("lockfile deleted")):this.logger.warning("lockfile handle does not exist, so lockfile could not be deleted")}catch(e){if("ENOENT"!==e.code)throw this.logger.error(`${i.pid} was not able to release lock. Ran into error: ${e.message}`),n.createCrossPlatformLockError(e.message);this.logger.info("Tried to unlock but lockfile does not exist")}}sleep(e){return new Promise(t=>{setTimeout(t,e)})}}class h{async verifyPersistence(){const e=await this.createForPersistenceValidation();try{await e.save("Dummy data to verify underlying persistence mechanism");const t=await e.load();if(!t)throw n.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.");if("Dummy data to verify underlying persistence mechanism"!==t)throw n.createCachePersistenceError("Persistence check failed. Data written Dummy data to verify underlying persistence mechanism is different from data read "+t);return await e.delete(),!0}catch(e){throw n.createCachePersistenceError("Verifing persistence failed with the error: "+e)}}}class d extends h{static async create(e,t){const r=new d;return r.filePath=e,r.logger=new c.Logger(t||d.createDefaultLoggerOptions()),await r.createCacheFile(),r}async save(e){try{await r.promises.writeFile(this.getFilePath(),e,"utf-8")}catch(e){throw n.createFileSystemError(e.code,e.message)}}async saveBuffer(e){try{await r.promises.writeFile(this.getFilePath(),e)}catch(e){throw n.createFileSystemError(e.code,e.message)}}async load(){try{return await r.promises.readFile(this.getFilePath(),"utf-8")}catch(e){throw n.createFileSystemError(e.code,e.message)}}async loadBuffer(){try{return await r.promises.readFile(this.getFilePath())}catch(e){throw n.createFileSystemError(e.code,e.message)}}async delete(){try{return await r.promises.unlink(this.getFilePath()),!0}catch(e){if("ENOENT"===e.code)return this.logger.warning("Cache file does not exist, so it could not be deleted"),!1;throw n.createFileSystemError(e.code,e.message)}}getFilePath(){return this.filePath}async reloadNecessary(e){return e<await this.timeLastModified()}getLogger(){return this.logger}createForPersistenceValidation(){const e=s.dirname(this.filePath)+"/test.cache";return d.create(e)}static createDefaultLoggerOptions(){return{loggerCallback:()=>{},piiLoggingEnabled:!1,logLevel:c.LogLevel.Info}}async timeLastModified(){try{return(await r.promises.stat(this.filePath)).mtime.getTime()}catch(e){if("ENOENT"===e.code)return this.logger.verbose("Cache file does not exist"),0;throw n.createFileSystemError(e.code,e.message)}}async createCacheFile(){await this.createFileDirectory();const e=await r.promises.open(this.filePath,"a");await e.close(),this.logger.info("File created at "+this.filePath)}async createFileDirectory(){try{await r.promises.mkdir(s.dirname(this.filePath),{recursive:!0})}catch(e){if("EEXIST"!==e.code)throw n.createFileSystemError(e.code,e.message);this.logger.info(`Directory ${s.dirname(this.filePath)} already exists`)}}}var g,u=require("../build/Release/dpapi.node");(g=exports.DataProtectionScope||(exports.DataProtectionScope={})).CurrentUser="CurrentUser",g.LocalMachine="LocalMachine";class m extends h{constructor(e,t){super(),this.scope=e,this.optionalEntropy=t?Buffer.from(t,"utf-8"):null}static async create(e,t,r,i){const s=new m(t,r);return s.filePersistence=await d.create(e,i),s}async save(e){try{const t=u.protectData(Buffer.from(e,"utf-8"),this.optionalEntropy,this.scope.toString());await this.filePersistence.saveBuffer(t)}catch(e){throw n.createFilePersistenceWithDPAPIError(e.message)}}async load(){try{const e=await this.filePersistence.loadBuffer();return void 0!==e&&e&&0!==e.length?u.unprotectData(e,this.optionalEntropy,this.scope.toString()).toString():(this.filePersistence.getLogger().info("Encrypted contents loaded from file were null or empty"),null)}catch(e){throw n.createFilePersistenceWithDPAPIError(e.message)}}async delete(){return this.filePersistence.delete()}async reloadNecessary(e){return this.filePersistence.reloadNecessary(e)}getFilePath(){return this.filePersistence.getFilePath()}getLogger(){return this.filePersistence.getLogger()}createForPersistenceValidation(){const e=s.dirname(this.filePersistence.getFilePath())+"/test.cache";return m.create(e,exports.DataProtectionScope.CurrentUser)}}class f extends h{constructor(e,t){super(),this.serviceName=e,this.accountName=t}static async create(e,t,r,i){const s=new f(t,r);return s.filePersistence=await d.create(e,i),s}async save(e){try{await o.setPassword(this.serviceName,this.accountName,e)}catch(e){throw n.createKeychainPersistenceError(e.message)}await this.filePersistence.save("{}")}async load(){try{return await o.getPassword(this.serviceName,this.accountName)}catch(e){throw n.createKeychainPersistenceError(e.message)}}async delete(){try{return await this.filePersistence.delete(),await o.deletePassword(this.serviceName,this.accountName)}catch(e){throw n.createKeychainPersistenceError(e.message)}}async reloadNecessary(e){return this.filePersistence.reloadNecessary(e)}getFilePath(){return this.filePersistence.getFilePath()}getLogger(){return this.filePersistence.getLogger()}createForPersistenceValidation(){const e=s.dirname(this.filePersistence.getFilePath())+"/test.cache";return f.create(e,"persistenceValidationServiceName","persistencValidationAccountName")}}class P extends h{constructor(e,t){super(),this.serviceName=e,this.accountName=t}static async create(e,t,r,i){const s=new P(t,r);return s.filePersistence=await d.create(e,i),s}async save(e){try{await o.setPassword(this.serviceName,this.accountName,e)}catch(e){throw n.createLibSecretError(e.message)}await this.filePersistence.save("{}")}async load(){try{return await o.getPassword(this.serviceName,this.accountName)}catch(e){throw n.createLibSecretError(e.message)}}async delete(){try{return await this.filePersistence.delete(),await o.deletePassword(this.serviceName,this.accountName)}catch(e){throw n.createLibSecretError(e.message)}}async reloadNecessary(e){return this.filePersistence.reloadNecessary(e)}getFilePath(){return this.filePersistence.getFilePath()}getLogger(){return this.filePersistence.getLogger()}createForPersistenceValidation(){const e=s.dirname(this.filePersistence.getFilePath())+"/test.cache";return P.create(e,"persistenceValidationServiceName","persistencValidationAccountName")}}class y{static get homeEnvVar(){return this.getEnvironmentVariable("HOME")}static get lognameEnvVar(){return this.getEnvironmentVariable("LOGNAME")}static get userEnvVar(){return this.getEnvironmentVariable("USER")}static get lnameEnvVar(){return this.getEnvironmentVariable("LNAME")}static get usernameEnvVar(){return this.getEnvironmentVariable("USERNAME")}static getEnvironmentVariable(e){return process.env[e]}static getEnvironmentPlatform(){return process.platform}static isWindowsPlatform(){return this.getEnvironmentPlatform()===t.WINDOWS}static isLinuxPlatform(){return this.getEnvironmentPlatform()===t.LINUX}static isMacPlatform(){return this.getEnvironmentPlatform()===t.MACOS}static isLinuxRootUser(){return 0===process.getuid()}static getUserRootDirectory(){return this.isWindowsPlatform?this.getUserHomeDirOnWindows():this.getUserHomeDirOnUnix()}static getUserHomeDirOnWindows(){return this.getEnvironmentVariable("LOCALAPPDATA")}static getUserHomeDirOnUnix(){if(this.isWindowsPlatform())throw n.createNotSupportedError("Getting the user home directory for unix is not supported in windows");if(!c.StringUtils.isEmpty(this.homeEnvVar))return this.homeEnvVar;let e=null;if(c.StringUtils.isEmpty(this.lognameEnvVar)?c.StringUtils.isEmpty(this.userEnvVar)?c.StringUtils.isEmpty(this.lnameEnvVar)?c.StringUtils.isEmpty(this.usernameEnvVar)||(e=this.usernameEnvVar):e=this.lnameEnvVar:e=this.userEnvVar:e=this.lognameEnvVar,this.isMacPlatform())return c.StringUtils.isEmpty(e)?null:a.join("/Users",e);if(this.isLinuxPlatform())return this.isLinuxRootUser()?"/root":c.StringUtils.isEmpty(e)?null:a.join("/home",e);throw n.createNotSupportedError("Getting the user home directory for unix is not supported in windows")}}exports.Environment=y,exports.FilePersistence=d,exports.FilePersistenceWithDataProtection=m,exports.KeychainPersistence=f,exports.LibSecretPersistence=P,exports.PersistenceCachePlugin=class{constructor(e,t){this.persistence=e,this.logger=e.getLogger(),this.lockFilePath=this.persistence.getFilePath()+".lockfile",this.crossPlatformLock=new l(this.lockFilePath,this.logger,t),this.lastSync=0,this.currentCache=null}async beforeCacheAccess(e){if(this.logger.info("Executing before cache access"),await this.persistence.reloadNecessary(this.lastSync)||null===this.currentCache)try{this.logger.info("Reload necessary. Last sync time: "+this.lastSync),await this.crossPlatformLock.lock(),this.currentCache=await this.persistence.load(),this.lastSync=(new Date).getTime(),e.tokenCache.deserialize(this.currentCache),this.logger.info("Last sync time updated to: "+this.lastSync)}finally{e.cacheHasChanged?this.logger.info(`Pid ${i.pid} beforeCacheAccess did not release lock`):(await this.crossPlatformLock.unlock(),this.logger.info(`Pid ${i.pid} released lock`))}else e.cacheHasChanged&&(this.logger.verbose("Cache context has changed"),await this.crossPlatformLock.lock())}async afterCacheAccess(e){this.logger.info("Executing after cache access");try{e.cacheHasChanged?(this.logger.info("Msal in-memory cache has changed. Writing changes to persistence"),this.currentCache=e.tokenCache.serialize(),await this.persistence.save(this.currentCache)):this.logger.info("Msal in-memory cache has not changed. Did not write to persistence")}finally{await this.crossPlatformLock.unlock(),this.logger.info(`Pid ${i.pid} afterCacheAccess released lock`)}}},exports.PersistenceCreator=class{static async createPersistence(e){let t;if(y.isWindowsPlatform()){if(!e.cachePath||!e.dataProtectionScope)throw n.createPersistenceNotValidatedError("Cache path and/or data protection scope not provided for the FilePersistenceWithDataProtection cache plugin");t=await m.create(e.cachePath,exports.DataProtectionScope.CurrentUser,void 0,e.loggerOptions)}else if(y.isMacPlatform()){if(!e.cachePath||!e.serviceName||!e.accountName)throw n.createPersistenceNotValidatedError("Cache path, service name and/or account name not provided for the KeychainPersistence cache plugin");t=await f.create(e.cachePath,e.serviceName,e.accountName,e.loggerOptions)}else{if(!y.isLinuxPlatform())throw n.createNotSupportedError("The current environment is not supported by msal-node-extensions yet.");if(!e.cachePath||!e.serviceName||!e.accountName)throw n.createPersistenceNotValidatedError("Cache path, service name and/or account name not provided for the LibSecretPersistence cache plugin");t=await P.create(e.cachePath,e.serviceName,e.accountName,e.loggerOptions)}if(!await t.verifyPersistence().catch(()=>!1)){if(y.isLinuxPlatform()&&e.usePlaintextFileOnLinux){if(!e.cachePath)throw n.createPersistenceNotValidatedError("Cache path not provided for the FilePersistence cache plugin");if(t=await d.create(e.cachePath,e.loggerOptions),await t.verifyPersistence())return t}throw n.createPersistenceNotVerifiedError("Persistence could not be verified")}return t}};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,t,r,i=require("fs"),a=require("process"),s=require("path"),o=(e=s)&&"object"==typeof e&&"default"in e?e.default:e,n=require("@azure/msal-common"),c=require("keytar"),l=require("@azure/msal-node-runtime");!function(e){e.WINDOWS="win32",e.LINUX="linux",e.MACOS="darwin"}(t||(t={})),function(e){e.INTERATION_REQUIRED_ERROR_CODE="interaction_required",e.SERVER_UNAVAILABLE="server_unavailable"}(r||(r={}));class h extends Error{constructor(e,t){super(t?`${e}: ${t}`:e),Object.setPrototypeOf(this,h.prototype),this.errorCode=e,this.errorMessage=t,this.name="PersistenceError"}static createFileSystemError(e,t){return new h(e,t)}static createLibSecretError(e){return new h("GnomeKeyringError",e)}static createKeychainPersistenceError(e){return new h("KeychainError",e)}static createFilePersistenceWithDPAPIError(e){return new h("DPAPIEncryptedFileError",e)}static createCrossPlatformLockError(e){return new h("CrossPlatformLockError",e)}static createCachePersistenceError(e){return new h("CachePersistenceError",e)}static createNotSupportedError(e){return new h("NotSupportedError",e)}static createPersistenceNotVerifiedError(e){return new h("PersistenceNotVerifiedError",e)}static createPersistenceNotValidatedError(e){return new h("PersistenceNotValidatedError",e)}}class u{constructor(e,t,r){this.lockFilePath=e,this.retryNumber=r?r.retryNumber:500,this.retryDelay=r?r.retryDelay:100,this.logger=t}async lock(){for(let e=0;e<this.retryNumber;e++)try{return this.logger.info(`Pid ${a.pid} trying to acquire lock`),this.lockFileHandle=await i.promises.open(this.lockFilePath,"wx+"),this.logger.info(`Pid ${a.pid} acquired lock`),void await this.lockFileHandle.write(a.pid.toString())}catch(e){if("EEXIST"!==e.code&&"EPERM"!==e.code)throw this.logger.error(`${a.pid} was not able to acquire lock. Ran into error: ${e.message}`),h.createCrossPlatformLockError(e.message);this.logger.info(e),await this.sleep(this.retryDelay)}throw this.logger.error(a.pid+" was not able to acquire lock. Exceeded amount of retries set in the options"),h.createCrossPlatformLockError("Not able to acquire lock. Exceeded amount of retries set in options")}async unlock(){try{this.lockFileHandle?(await i.promises.unlink(this.lockFilePath),await this.lockFileHandle.close(),this.logger.info("lockfile deleted")):this.logger.warning("lockfile handle does not exist, so lockfile could not be deleted")}catch(e){if("ENOENT"!==e.code)throw this.logger.error(`${a.pid} was not able to release lock. Ran into error: ${e.message}`),h.createCrossPlatformLockError(e.message);this.logger.info("Tried to unlock but lockfile does not exist")}}sleep(e){return new Promise(t=>{setTimeout(t,e)})}}class g{async verifyPersistence(){const e=await this.createForPersistenceValidation();try{await e.save("Dummy data to verify underlying persistence mechanism");const t=await e.load();if(!t)throw h.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.");if("Dummy data to verify underlying persistence mechanism"!==t)throw h.createCachePersistenceError("Persistence check failed. Data written Dummy data to verify underlying persistence mechanism is different from data read "+t);return await e.delete(),!0}catch(e){throw h.createCachePersistenceError("Verifing persistence failed with the error: "+e)}}}class d extends g{static async create(e,t){const r=new d;return r.filePath=e,r.logger=new n.Logger(t||d.createDefaultLoggerOptions()),await r.createCacheFile(),r}async save(e){try{await i.promises.writeFile(this.getFilePath(),e,"utf-8")}catch(e){throw h.createFileSystemError(e.code,e.message)}}async saveBuffer(e){try{await i.promises.writeFile(this.getFilePath(),e)}catch(e){throw h.createFileSystemError(e.code,e.message)}}async load(){try{return await i.promises.readFile(this.getFilePath(),"utf-8")}catch(e){throw h.createFileSystemError(e.code,e.message)}}async loadBuffer(){try{return await i.promises.readFile(this.getFilePath())}catch(e){throw h.createFileSystemError(e.code,e.message)}}async delete(){try{return await i.promises.unlink(this.getFilePath()),!0}catch(e){if("ENOENT"===e.code)return this.logger.warning("Cache file does not exist, so it could not be deleted"),!1;throw h.createFileSystemError(e.code,e.message)}}getFilePath(){return this.filePath}async reloadNecessary(e){return e<await this.timeLastModified()}getLogger(){return this.logger}createForPersistenceValidation(){const e=s.dirname(this.filePath)+"/test.cache";return d.create(e)}static createDefaultLoggerOptions(){return{loggerCallback:()=>{},piiLoggingEnabled:!1,logLevel:n.LogLevel.Info}}async timeLastModified(){try{return(await i.promises.stat(this.filePath)).mtime.getTime()}catch(e){if("ENOENT"===e.code)return this.logger.verbose("Cache file does not exist"),0;throw h.createFileSystemError(e.code,e.message)}}async createCacheFile(){await this.createFileDirectory();const e=await i.promises.open(this.filePath,"a");await e.close(),this.logger.info("File created at "+this.filePath)}async createFileDirectory(){try{await i.promises.mkdir(s.dirname(this.filePath),{recursive:!0})}catch(e){if("EEXIST"!==e.code)throw h.createFileSystemError(e.code,e.message);this.logger.info(`Directory ${s.dirname(this.filePath)} already exists`)}}}var m,P=require("../build/Release/dpapi.node");(m=exports.DataProtectionScope||(exports.DataProtectionScope={})).CurrentUser="CurrentUser",m.LocalMachine="LocalMachine";class f extends g{constructor(e,t){super(),this.scope=e,this.optionalEntropy=t?Buffer.from(t,"utf-8"):null}static async create(e,t,r,i){const a=new f(t,r);return a.filePersistence=await d.create(e,i),a}async save(e){try{const t=P.protectData(Buffer.from(e,"utf-8"),this.optionalEntropy,this.scope.toString());await this.filePersistence.saveBuffer(t)}catch(e){throw h.createFilePersistenceWithDPAPIError(e.message)}}async load(){try{const e=await this.filePersistence.loadBuffer();return void 0!==e&&e&&0!==e.length?P.unprotectData(e,this.optionalEntropy,this.scope.toString()).toString():(this.filePersistence.getLogger().info("Encrypted contents loaded from file were null or empty"),null)}catch(e){throw h.createFilePersistenceWithDPAPIError(e.message)}}async delete(){return this.filePersistence.delete()}async reloadNecessary(e){return this.filePersistence.reloadNecessary(e)}getFilePath(){return this.filePersistence.getFilePath()}getLogger(){return this.filePersistence.getLogger()}createForPersistenceValidation(){const e=s.dirname(this.filePersistence.getFilePath())+"/test.cache";return f.create(e,exports.DataProtectionScope.CurrentUser)}}class y extends g{constructor(e,t){super(),this.serviceName=e,this.accountName=t}static async create(e,t,r,i){const a=new y(t,r);return a.filePersistence=await d.create(e,i),a}async save(e){try{await c.setPassword(this.serviceName,this.accountName,e)}catch(e){throw h.createKeychainPersistenceError(e.message)}await this.filePersistence.save("{}")}async load(){try{return await c.getPassword(this.serviceName,this.accountName)}catch(e){throw h.createKeychainPersistenceError(e.message)}}async delete(){try{return await this.filePersistence.delete(),await c.deletePassword(this.serviceName,this.accountName)}catch(e){throw h.createKeychainPersistenceError(e.message)}}async reloadNecessary(e){return this.filePersistence.reloadNecessary(e)}getFilePath(){return this.filePersistence.getFilePath()}getLogger(){return this.filePersistence.getLogger()}createForPersistenceValidation(){const e=s.dirname(this.filePersistence.getFilePath())+"/test.cache";return y.create(e,"persistenceValidationServiceName","persistencValidationAccountName")}}class p extends g{constructor(e,t){super(),this.serviceName=e,this.accountName=t}static async create(e,t,r,i){const a=new p(t,r);return a.filePersistence=await d.create(e,i),a}async save(e){try{await c.setPassword(this.serviceName,this.accountName,e)}catch(e){throw h.createLibSecretError(e.message)}await this.filePersistence.save("{}")}async load(){try{return await c.getPassword(this.serviceName,this.accountName)}catch(e){throw h.createLibSecretError(e.message)}}async delete(){try{return await this.filePersistence.delete(),await c.deletePassword(this.serviceName,this.accountName)}catch(e){throw h.createLibSecretError(e.message)}}async reloadNecessary(e){return this.filePersistence.reloadNecessary(e)}getFilePath(){return this.filePersistence.getFilePath()}getLogger(){return this.filePersistence.getLogger()}createForPersistenceValidation(){const e=s.dirname(this.filePersistence.getFilePath())+"/test.cache";return p.create(e,"persistenceValidationServiceName","persistencValidationAccountName")}}class E{static get homeEnvVar(){return this.getEnvironmentVariable("HOME")}static get lognameEnvVar(){return this.getEnvironmentVariable("LOGNAME")}static get userEnvVar(){return this.getEnvironmentVariable("USER")}static get lnameEnvVar(){return this.getEnvironmentVariable("LNAME")}static get usernameEnvVar(){return this.getEnvironmentVariable("USERNAME")}static getEnvironmentVariable(e){return process.env[e]}static getEnvironmentPlatform(){return process.platform}static isWindowsPlatform(){return this.getEnvironmentPlatform()===t.WINDOWS}static isLinuxPlatform(){return this.getEnvironmentPlatform()===t.LINUX}static isMacPlatform(){return this.getEnvironmentPlatform()===t.MACOS}static isLinuxRootUser(){return 0===process.getuid()}static getUserRootDirectory(){return this.isWindowsPlatform?this.getUserHomeDirOnWindows():this.getUserHomeDirOnUnix()}static getUserHomeDirOnWindows(){return this.getEnvironmentVariable("LOCALAPPDATA")}static getUserHomeDirOnUnix(){if(this.isWindowsPlatform())throw h.createNotSupportedError("Getting the user home directory for unix is not supported in windows");if(!n.StringUtils.isEmpty(this.homeEnvVar))return this.homeEnvVar;let e=null;if(n.StringUtils.isEmpty(this.lognameEnvVar)?n.StringUtils.isEmpty(this.userEnvVar)?n.StringUtils.isEmpty(this.lnameEnvVar)?n.StringUtils.isEmpty(this.usernameEnvVar)||(e=this.usernameEnvVar):e=this.lnameEnvVar:e=this.userEnvVar:e=this.lognameEnvVar,this.isMacPlatform())return n.StringUtils.isEmpty(e)?null:o.join("/Users",e);if(this.isLinuxPlatform())return this.isLinuxRootUser()?"/root":n.StringUtils.isEmpty(e)?null:o.join("/home",e);throw h.createNotSupportedError("Getting the user home directory for unix is not supported in windows")}}class w extends n.AuthError{constructor(e,t,r,i){super(e,t),this.name="NativeAuthError",this.statusCode=r,this.tag=i,Object.setPrototypeOf(this,w.prototype)}}const v="@azure/msal-node-extensions";exports.Environment=E,exports.FilePersistence=d,exports.FilePersistenceWithDataProtection=f,exports.KeychainPersistence=y,exports.LibSecretPersistence=p,exports.NativeBrokerPlugin=class{constructor(){this.logger=new n.Logger({loggerCallback:()=>{},piiLoggingEnabled:!1},v,"1.0.0-alpha.31"),this.isBrokerAvailable=!l.msalNodeRuntime.StartupError}setLogger(e){this.logger=new n.Logger(e,v,"1.0.0-alpha.31");const t=(e,t,r)=>{switch(t){case l.LogLevel.Trace:case l.LogLevel.Debug:r?this.logger.tracePii(e):this.logger.trace(e);break;case l.LogLevel.Info:r?this.logger.infoPii(e):this.logger.info(e);break;case l.LogLevel.Warning:r?this.logger.warningPii(e):this.logger.warning(e);break;case l.LogLevel.Error:case l.LogLevel.Fatal:r?this.logger.errorPii(e):this.logger.error(e);break;default:r?this.logger.infoPii(e):this.logger.info(e)}};try{l.msalNodeRuntime.RegisterLogger(t,e.piiLoggingEnabled)}catch(e){const t=this.wrapError(e);if(t)throw t}}async getAccountById(e,t){this.logger.trace("NativeBrokerPlugin - getAccountById called",t);const r=await this.readAccountById(e,t);return this.generateAccountInfo(r.account)}async getAllAccounts(e,t){return this.logger.trace("NativeBrokerPlugin - getAllAccounts called",t),new Promise((r,i)=>{const a=e=>{try{e.CheckError()}catch(e){const t=this.wrapError(e);if(t)return void i(t)}const t=[];e.accounts.forEach(e=>{t.push(this.generateAccountInfo(e))}),r(t)};try{l.msalNodeRuntime.DiscoverAccountsAsync(e,t,a)}catch(e){const t=this.wrapError(e);t&&i(t)}})}async acquireTokenSilent(e){this.logger.trace("NativeBrokerPlugin - acquireTokenSilent called",e.correlationId);const t=this.generateRequestParameters(e),r=await this.getAccount(e);return new Promise((i,a)=>{const s=t=>{try{t.CheckError()}catch(e){const t=this.wrapError(e);if(t)return void a(t)}const r=this.getAuthenticationResult(e,t);i(r)};try{r?l.msalNodeRuntime.AcquireTokenSilentlyAsync(t,e.correlationId,r,s):l.msalNodeRuntime.SignInSilentlyAsync(t,e.correlationId,s)}catch(e){const t=this.wrapError(e);t&&a(t)}})}async acquireTokenInteractive(e,t){this.logger.trace("NativeBrokerPlugin - acquireTokenInteractive called",e.correlationId);const r=this.generateRequestParameters(e),i=await this.getAccount(e),a=t||Buffer.from([0]);return new Promise((t,s)=>{const o=r=>{try{r.CheckError()}catch(e){const t=this.wrapError(e);if(t)return void s(t)}const i=this.getAuthenticationResult(e,r);t(i)};try{switch(e.prompt){case n.PromptValue.LOGIN:case n.PromptValue.SELECT_ACCOUNT:case n.PromptValue.CREATE:this.logger.info("Calling native interop SignInInteractively API",e.correlationId),l.msalNodeRuntime.SignInInteractivelyAsync(a,r,e.correlationId,e.loginHint||n.Constants.EMPTY_STRING,o);break;case n.PromptValue.NONE:i?(this.logger.info("Calling native interop AcquireTokenSilently API",e.correlationId),l.msalNodeRuntime.AcquireTokenSilentlyAsync(r,e.correlationId,i,o)):(this.logger.info("Calling native interop SignInSilently API",e.correlationId),l.msalNodeRuntime.SignInSilentlyAsync(r,e.correlationId,o));break;default:i?(this.logger.info("Calling native interop AcquireTokenInteractively API",e.correlationId),l.msalNodeRuntime.AcquireTokenInteractivelyAsync(a,r,e.correlationId,i,o)):(this.logger.info("Calling native interop SignIn API",e.correlationId),l.msalNodeRuntime.SignInAsync(a,r,e.correlationId,e.loginHint||n.Constants.EMPTY_STRING,o))}}catch(e){const t=this.wrapError(e);t&&s(t)}})}async signOut(e){this.logger.trace("NativeBrokerPlugin - signOut called",e.correlationId);const t=await this.getAccount(e);if(!t)throw n.ClientAuthError.createNoAccountFoundError();return new Promise((r,i)=>{const a=e=>{try{e.CheckError()}catch(e){const t=this.wrapError(e);if(t)return void i(t)}r()};try{l.msalNodeRuntime.SignOutSilentlyAsync(e.clientId,e.correlationId,t,a)}catch(e){const t=this.wrapError(e);t&&i(t)}})}async getAccount(e){return e.accountId?(await this.readAccountById(e.accountId,e.correlationId)).account:null}async readAccountById(e,t){return this.logger.trace("NativeBrokerPlugin - readAccountById called",t),new Promise((r,i)=>{const a=e=>{try{e.CheckError()}catch(e){const t=this.wrapError(e);if(t)return void i(t)}r(e)};try{l.msalNodeRuntime.ReadAccountByIdAsync(e,t,a)}catch(e){const t=this.wrapError(e);t&&i(t)}})}generateRequestParameters(e){this.logger.trace("NativeBrokerPlugin - generateRequestParameters called",e.correlationId);const t=new l.msalNodeRuntime.AuthParameters;try{if(t.CreateAuthParameters(e.clientId,e.authority),t.SetRedirectUri(e.redirectUri),t.SetRequestedScopes(e.scopes.join(" ")),e.claims&&t.SetDecodedClaims(e.claims),e.authenticationScheme===n.AuthenticationScheme.POP){if(!e.resourceRequestMethod||!e.resourceRequestUri||!e.shrNonce)throw new Error("Authentication Scheme set to POP but one or more of the following parameters are missing: resourceRequestMethod, resourceRequestUri, shrNonce");const r=new URL(e.resourceRequestUri);t.SetPopParams(e.resourceRequestMethod,r.host,r.pathname,e.shrNonce)}e.extraParameters&&Object.keys(e.extraParameters).forEach(r=>{t.SetAdditionalParameter(r,e.extraParameters[r])})}catch(e){const t=this.wrapError(e);if(t)throw t}return t}getAuthenticationResult(e,t){let r,i;this.logger.trace("NativeBrokerPlugin - getAuthenticationResult called",e.correlationId);try{r=!!JSON.parse(t.telemetryData).is_cache}catch(t){this.logger.error("NativeBrokerPlugin: getAuthenticationResult - Error parsing telemetry data. Could not determine if response came from cache.",e.correlationId)}try{i=JSON.parse(t.idToken)}catch(e){throw new Error("Unable to parse idToken claims")}const a=this.generateAccountInfo(t.account,i);return{authority:e.authority,uniqueId:i.oid||i.sub||"",tenantId:i.tid||"",scopes:t.grantedScopes.split(" "),account:a,idToken:t.rawIdToken,idTokenClaims:i,accessToken:t.accessToken,fromCache:r,expiresOn:new Date(1e3*t.expiresOn),tokenType:t.isPopAuthorization?n.AuthenticationScheme.POP:n.AuthenticationScheme.BEARER,correlationId:e.correlationId,fromNativeBroker:!0}}generateAccountInfo(e,t){return this.logger.trace("NativeBrokerPlugin - generateAccountInfo called"),{homeAccountId:e.homeAccountId,environment:e.environment,tenantId:e.realm,username:e.username,localAccountId:e.localAccountId,name:e.displayName,idTokenClaims:t,nativeAccountId:e.accountId}}isMsalRuntimeError(e){return e.hasOwnProperty("errorCode")||e.hasOwnProperty("errorStatus")||e.hasOwnProperty("errorContext")||e.hasOwnProperty("errorTag")}wrapError(e){if(this.isMsalRuntimeError(e)){const{errorCode:t,errorStatus:i,errorContext:a,errorTag:s}=e;switch(i){case l.ErrorStatus.InteractionRequired:case l.ErrorStatus.AccountUnusable:return new n.InteractionRequiredAuthError(r.INTERATION_REQUIRED_ERROR_CODE,a);case l.ErrorStatus.NoNetwork:case l.ErrorStatus.NetworkTemporarilyUnavailable:return n.ClientAuthError.createNoNetworkConnectivityError();case l.ErrorStatus.ServerTemporarilyUnavailable:return new n.ServerError(r.SERVER_UNAVAILABLE,a);case l.ErrorStatus.UserCanceled:return n.ClientAuthError.createUserCanceledError();case l.ErrorStatus.AuthorityUntrusted:return n.ClientConfigurationError.createUntrustedAuthorityError();case l.ErrorStatus.UserSwitched:return null;case l.ErrorStatus.AccountNotFound:return n.ClientAuthError.createNoAccountFoundError();default:return new w(l.ErrorStatus[i],a,t,s)}}return e}},exports.PersistenceCachePlugin=class{constructor(e,t){this.persistence=e,this.logger=e.getLogger(),this.lockFilePath=this.persistence.getFilePath()+".lockfile",this.crossPlatformLock=new u(this.lockFilePath,this.logger,t),this.lastSync=0,this.currentCache=null}async beforeCacheAccess(e){if(this.logger.info("Executing before cache access"),await this.persistence.reloadNecessary(this.lastSync)||null===this.currentCache)try{this.logger.info("Reload necessary. Last sync time: "+this.lastSync),await this.crossPlatformLock.lock(),this.currentCache=await this.persistence.load(),this.lastSync=(new Date).getTime(),e.tokenCache.deserialize(this.currentCache),this.logger.info("Last sync time updated to: "+this.lastSync)}finally{e.cacheHasChanged?this.logger.info(`Pid ${a.pid} beforeCacheAccess did not release lock`):(await this.crossPlatformLock.unlock(),this.logger.info(`Pid ${a.pid} released lock`))}else e.cacheHasChanged&&(this.logger.verbose("Cache context has changed"),await this.crossPlatformLock.lock())}async afterCacheAccess(e){this.logger.info("Executing after cache access");try{e.cacheHasChanged?(this.logger.info("Msal in-memory cache has changed. Writing changes to persistence"),this.currentCache=e.tokenCache.serialize(),await this.persistence.save(this.currentCache)):this.logger.info("Msal in-memory cache has not changed. Did not write to persistence")}finally{await this.crossPlatformLock.unlock(),this.logger.info(`Pid ${a.pid} afterCacheAccess released lock`)}}},exports.PersistenceCreator=class{static async createPersistence(e){let t;if(E.isWindowsPlatform()){if(!e.cachePath||!e.dataProtectionScope)throw h.createPersistenceNotValidatedError("Cache path and/or data protection scope not provided for the FilePersistenceWithDataProtection cache plugin");t=await f.create(e.cachePath,exports.DataProtectionScope.CurrentUser,void 0,e.loggerOptions)}else if(E.isMacPlatform()){if(!e.cachePath||!e.serviceName||!e.accountName)throw h.createPersistenceNotValidatedError("Cache path, service name and/or account name not provided for the KeychainPersistence cache plugin");t=await y.create(e.cachePath,e.serviceName,e.accountName,e.loggerOptions)}else{if(!E.isLinuxPlatform())throw h.createNotSupportedError("The current environment is not supported by msal-node-extensions yet.");if(!e.cachePath||!e.serviceName||!e.accountName)throw h.createPersistenceNotValidatedError("Cache path, service name and/or account name not provided for the LibSecretPersistence cache plugin");t=await p.create(e.cachePath,e.serviceName,e.accountName,e.loggerOptions)}if(!await t.verifyPersistence().catch(()=>!1)){if(E.isLinuxPlatform()&&e.usePlaintextFileOnLinux){if(!e.cachePath)throw h.createPersistenceNotValidatedError("Cache path not provided for the FilePersistence cache plugin");if(t=await d.create(e.cachePath,e.loggerOptions),await t.verifyPersistence())return t}throw h.createPersistenceNotVerifiedError("Persistence could not be verified")}return t}};
2
2
  //# sourceMappingURL=msal-node-extensions.cjs.production.min.js.map