@forge/cli-shared
9.10.0-next.1-experimental-1e956969.10.0-next.5
out/auth/personal/credential-store.js~
out/auth/personal/credential-store.jsModified+120−196
Index: package/out/auth/personal/credential-store.js
===================================================================
--- package/out/auth/personal/credential-store.js
+++ package/out/auth/personal/credential-store.js
@@ -1,36 +1,37 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
-exports.FileCredentialStore = exports.CredentialStoreSecurityError = exports.NoTokenInStoreError = exports.personalApiCredentialsValidatedShape = exports.personalApiCredentialsShape = exports.API_TOKEN_KEY = exports.EMAIL_KEY = void 0;
-exports.getCredentialsFilePath = getCredentialsFilePath;
+exports.CredentialStoreImpl = exports.KeytarAccessError = exports.NoKeytarError = exports.NoTokenInStoreError = exports.personalApiCredentialsValidatedShape = exports.personalApiCredentialsShape = exports.API_TOKEN_KEY = exports.EMAIL_KEY = void 0;
exports.getCredentialStore = getCredentialStore;
const tslib_1 = require("tslib");
-const child_process_1 = require("child_process");
-const fs_1 = require("fs");
const os_1 = require("os");
-const path_1 = tslib_1.__importDefault(require("path"));
-const util_1 = require("util");
const Either_1 = require("fp-ts/lib/Either");
const t = tslib_1.__importStar(require("io-ts"));
+const cache_1 = require("../../cache");
+const instruction_1 = require("../instruction");
const graphql_1 = require("../../graphql");
const shared_1 = require("../../shared");
const ui_1 = require("../../ui");
exports.EMAIL_KEY = 'FORGE_EMAIL';
exports.API_TOKEN_KEY = 'FORGE_API_TOKEN';
-const CREDENTIALS_FILE_NAME = 'credentials.json';
-const CREDENTIALS_DIRECTORY_MODE = 0o700;
-const CREDENTIALS_FILE_MODE = 0o600;
-const PERMISSION_BITS_MASK = 0o777;
-const WINDOWS_SYSTEM_SID = 'S-1-5-18';
-const WINDOWS_ADMINISTRATORS_SID = 'S-1-5-32-544';
-var CredentialAccount;
-(function (CredentialAccount) {
- CredentialAccount["DEV"] = "Ecosystem-staging";
- CredentialAccount["STG"] = "Ecosystem-staging";
- CredentialAccount["PROD"] = "Ecosystem";
- CredentialAccount["FEDRAMP_MODERATE_STAGING"] = "Ecosystem-fedm-staging";
- CredentialAccount["FEDRAMP_MODERATE_PROD"] = "Ecosystem-fedm-prod";
-})(CredentialAccount || (CredentialAccount = {}));
+const KEYTAR_SERVICE = 'Atlassian';
+const CACHE_CREDENTIALS_KEY = 'forge-credentials';
+var KeytarAccount;
+(function (KeytarAccount) {
+ KeytarAccount["DEV"] = "Ecosystem-staging";
+ KeytarAccount["STG"] = "Ecosystem-staging";
+ KeytarAccount["PROD"] = "Ecosystem";
+ KeytarAccount["FEDRAMP_MODERATE_STAGING"] = "Ecosystem-fedm-staging";
+ KeytarAccount["FEDRAMP_MODERATE_PROD"] = "Ecosystem-fedm-prod";
+})(KeytarAccount || (KeytarAccount = {}));
+function getKeytar() {
+ try {
+ return require('keytar');
+ }
+ catch {
+ return null;
+ }
+}
exports.personalApiCredentialsShape = t.type({
email: t.string,
token: t.string
});
@@ -44,224 +45,147 @@
super(ui_1.Text.error.noTokenStored);
}
}
exports.NoTokenInStoreError = NoTokenInStoreError;
-class CredentialStoreSecurityError extends shared_1.UserError {
+class NoKeytarError extends shared_1.UserError {
constructor() {
- super(ui_1.Text.error.credentialsFilePermissions);
+ super(ui_1.Text.error.noKeytar);
}
}
-exports.CredentialStoreSecurityError = CredentialStoreSecurityError;
-const execFileAsync = (0, util_1.promisify)(child_process_1.execFile);
-const runCredentialStoreCommand = async (command, args) => {
- const { stdout } = await execFileAsync(command, [...args], { encoding: 'utf8', windowsHide: true });
- return stdout;
-};
-const credentialsByAccountShape = t.record(t.string, exports.personalApiCredentialsValidatedShape);
-function isFileNotFoundError(error) {
- return typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT';
+exports.NoKeytarError = NoKeytarError;
+class KeytarAccessError extends shared_1.UserError {
}
-function getCredentialsFilePath(currentPlatform = (0, os_1.platform)(), environment = process.env, userHome = (0, os_1.homedir)()) {
- const platformPath = currentPlatform === 'win32' ? path_1.default.win32 : path_1.default.posix;
- let credentialsDirectory;
- switch (currentPlatform) {
- case 'darwin':
- credentialsDirectory = platformPath.join(userHome, 'Library', 'Application Support', 'Atlassian', 'Forge');
- break;
- case 'win32':
- credentialsDirectory = platformPath.join(environment.LOCALAPPDATA || platformPath.join(userHome, 'AppData', 'Local'), 'Atlassian', 'Forge');
- break;
- default:
- credentialsDirectory = platformPath.join(environment.XDG_DATA_HOME || platformPath.join(userHome, '.local', 'share'), 'Atlassian', 'Forge');
- }
- return platformPath.join(credentialsDirectory, CREDENTIALS_FILE_NAME);
-}
-class FileCredentialStore {
+exports.KeytarAccessError = KeytarAccessError;
+class CredentialStoreImpl {
+ logger;
+ instructionsURL;
+ keytar;
+ cachedConfig;
userRepository;
- account;
- credentialsFilePath;
- currentPlatform;
- commandRunner;
- windowsUserSid;
- constructor(userRepository, account, credentialsFilePath = getCredentialsFilePath(), currentPlatform = (0, os_1.platform)(), commandRunner = runCredentialStoreCommand) {
+ keytarAccount;
+ constructor(logger, instructionsURL, keytar, cachedConfig, userRepository) {
+ this.logger = logger;
+ this.instructionsURL = instructionsURL;
+ this.keytar = keytar;
+ this.cachedConfig = cachedConfig;
this.userRepository = userRepository;
- this.account = account;
- this.credentialsFilePath = credentialsFilePath;
- this.currentPlatform = currentPlatform;
- this.commandRunner = commandRunner;
+ this.keytarAccount = (0, graphql_1.getEnvironmentConfig)(KeytarAccount);
}
- async getWindowsUserSid() {
- this.windowsUserSid ??= this.commandRunner('whoami.exe', ['/user', '/fo', 'csv', '/nh']).then((output) => {
- const sid = output.trim().match(/"?(S-\d(?:-\d+)+)"?$/)?.[1];
- if (!sid) {
- throw new Error('Could not determine the current Windows user SID');
- }
- return sid;
- });
- return this.windowsUserSid;
+ wrapKeytarError(e) {
+ const message = (0, shared_1.wrapError)(e).message;
+ let error;
+ const currentPlatform = (0, os_1.platform)();
+ switch (currentPlatform) {
+ case 'darwin':
+ error = ui_1.Text.error.keytarAccessError.mac(message);
+ break;
+ case 'linux':
+ error = ui_1.Text.error.keytarAccessError.linux(message);
+ break;
+ case 'win32':
+ error = ui_1.Text.error.keytarAccessError.windows(message);
+ break;
+ default:
+ error = ui_1.Text.error.keytarAccessError.other(message);
+ }
+ throw new KeytarAccessError(error);
}
- async applyWindowsAcl(targetPath, directory) {
- const userSid = await this.getWindowsUserSid();
- const permission = directory ? '(OI)(CI)F' : 'F';
- await this.commandRunner('icacls.exe', [
- targetPath,
- '/inheritance:r',
- '/grant:r',
- `*${userSid}:${permission}`,
- `*${WINDOWS_SYSTEM_SID}:${permission}`,
- `*${WINDOWS_ADMINISTRATORS_SID}:${permission}`
- ]);
- }
- async secureWindowsStorage(createFile) {
- let fileExists = true;
+ decodeCredentials(credentialsString) {
+ if (!credentialsString) {
+ throw new NoTokenInStoreError();
+ }
+ let credentials;
try {
- await fs_1.promises.access(this.credentialsFilePath);
+ credentials = JSON.parse(credentialsString);
}
- catch (error) {
- if (!isFileNotFoundError(error)) {
- throw error;
- }
- fileExists = false;
+ catch {
+ throw new NoTokenInStoreError();
}
- if (!fileExists && !createFile) {
- return;
+ const decodeResult = exports.personalApiCredentialsValidatedShape.decode(credentials);
+ if ((0, Either_1.isLeft)(decodeResult)) {
+ throw new NoTokenInStoreError();
}
- const credentialsDirectory = path_1.default.dirname(this.credentialsFilePath);
- await fs_1.promises.mkdir(credentialsDirectory, { recursive: true });
- await this.applyWindowsAcl(credentialsDirectory, true);
- if (!fileExists) {
- await fs_1.promises.writeFile(this.credentialsFilePath, '', { flag: 'wx' });
- }
- await this.applyWindowsAcl(this.credentialsFilePath, false);
+ return decodeResult.right;
}
- async securePosixStorage(createFile) {
- let fileExists = true;
+ async getCredentialsKeytar(keytar) {
+ let stringifiedPersonalApiCredentials;
try {
- await fs_1.promises.access(this.credentialsFilePath);
+ stringifiedPersonalApiCredentials = await keytar.getPassword(KEYTAR_SERVICE, this.keytarAccount);
}
- catch (error) {
- if (!isFileNotFoundError(error)) {
- throw error;
- }
- fileExists = false;
+ catch (e) {
+ this.wrapKeytarError(e);
}
- if (!fileExists && !createFile) {
- return;
+ if (!stringifiedPersonalApiCredentials) {
+ return undefined;
}
- const credentialsDirectory = path_1.default.dirname(this.credentialsFilePath);
- await fs_1.promises.mkdir(credentialsDirectory, {
- recursive: true,
- mode: CREDENTIALS_DIRECTORY_MODE
- });
- await fs_1.promises.chmod(credentialsDirectory, CREDENTIALS_DIRECTORY_MODE);
- const directoryStat = await fs_1.promises.stat(credentialsDirectory);
- const currentUserId = process.getuid?.();
- if (currentUserId === undefined ||
- !directoryStat.isDirectory() ||
- directoryStat.uid !== currentUserId ||
- (directoryStat.mode & PERMISSION_BITS_MASK) !== CREDENTIALS_DIRECTORY_MODE) {
- throw new Error('The credentials directory is not owned exclusively by the current user');
+ return this.decodeCredentials(stringifiedPersonalApiCredentials);
+ }
+ popInsecurePlaintextCredentials() {
+ const result = this.cachedConfig.get(CACHE_CREDENTIALS_KEY);
+ if (result) {
+ this.logger.warn(ui_1.Text.warning.plaintextCredentialsFound(this.instructionsURL));
+ this.deleteInsecurePlaintextCredentials();
}
- if (!fileExists) {
- const file = await fs_1.promises.open(this.credentialsFilePath, 'wx', CREDENTIALS_FILE_MODE);
- await file.close();
- }
- await fs_1.promises.chmod(this.credentialsFilePath, CREDENTIALS_FILE_MODE);
- const fileStat = await fs_1.promises.stat(this.credentialsFilePath);
- if (!fileStat.isFile() ||
- fileStat.uid !== currentUserId ||
- (fileStat.mode & PERMISSION_BITS_MASK) !== CREDENTIALS_FILE_MODE) {
- throw new Error('Could not restrict access to the credentials file');
- }
+ return result;
}
- async secureStorage(createFile) {
- try {
- if (this.currentPlatform === 'win32') {
- await this.secureWindowsStorage(createFile);
+ deleteInsecurePlaintextCredentials() {
+ this.cachedConfig.delete(CACHE_CREDENTIALS_KEY);
+ }
+ async getCredentials() {
+ let result;
+ const plaintextCredentials = this.popInsecurePlaintextCredentials();
+ if (plaintextCredentials) {
+ if (this.keytar) {
+ await this.setCredentials(plaintextCredentials);
+ this.logger.warn(ui_1.Text.warning.plaintextCredentialsMigrated);
}
else {
- await this.securePosixStorage(createFile);
+ this.logger.warn(ui_1.Text.warning.plaintextCredentialsNotMigrated);
}
}
- catch {
- await fs_1.promises.rm(this.credentialsFilePath, { force: true }).catch(() => undefined);
- throw new CredentialStoreSecurityError();
- }
- }
- async readCredentialsFile() {
- let contents;
- try {
- await this.secureStorage(false);
- contents = await fs_1.promises.readFile(this.credentialsFilePath, 'utf8');
- }
- catch (error) {
- if (isFileNotFoundError(error)) {
- return {};
- }
- throw error;
- }
- let parsed;
- try {
- parsed = JSON.parse(contents);
- }
- catch {
- throw new NoTokenInStoreError();
- }
- const decodeResult = credentialsByAccountShape.decode(parsed);
- if ((0, Either_1.isLeft)(decodeResult)) {
- throw new NoTokenInStoreError();
- }
- return decodeResult.right;
- }
- async getCredentials() {
if (process.env[exports.API_TOKEN_KEY] && process.env[exports.EMAIL_KEY]) {
const credentials = {
email: process.env[exports.EMAIL_KEY],
token: process.env[exports.API_TOKEN_KEY]
};
const { accountId } = await this.userRepository.getUser(credentials);
- return { ...credentials, accountId };
+ result = { ...credentials, accountId };
}
- const credentials = (await this.readCredentialsFile())[this.account];
- if (!credentials) {
- throw new NoTokenInStoreError();
+ else if (this.keytar) {
+ result = await this.getCredentialsKeytar(this.keytar);
}
- return credentials;
+ if (result) {
+ return result;
+ }
+ throw new NoTokenInStoreError();
}
async setCredentials(credentials) {
- let credentialsByAccount;
- try {
- credentialsByAccount = await this.readCredentialsFile();
- }
- catch (error) {
- if (!(error instanceof NoTokenInStoreError)) {
- throw error;
+ if (this.keytar) {
+ try {
+ await this.keytar.setPassword(KEYTAR_SERVICE, this.keytarAccount, JSON.stringify(credentials));
}
- credentialsByAccount = {};
+ catch (e) {
+ throw new NoKeytarError();
+ }
}
- credentialsByAccount[this.account] = credentials;
- await this.secureStorage(true);
- await fs_1.promises.writeFile(this.credentialsFilePath, `${JSON.stringify(credentialsByAccount, null, 2)}\n`, 'utf8');
- await this.secureStorage(false);
+ else {
+ throw new NoKeytarError();
+ }
}
async deleteCredentials() {
- const credentialsByAccount = await this.readCredentialsFile();
- delete credentialsByAccount[this.account];
- if (Object.keys(credentialsByAccount).length === 0) {
+ if (this.keytar) {
try {
- await fs_1.promises.unlink(this.credentialsFilePath);
+ await this.keytar.deletePassword(KEYTAR_SERVICE, this.keytarAccount);
}
- catch (error) {
- if (!isFileNotFoundError(error)) {
- throw error;
- }
+ catch (e) {
}
- return;
}
- await fs_1.promises.writeFile(this.credentialsFilePath, `${JSON.stringify(credentialsByAccount, null, 2)}\n`, 'utf8');
- await this.secureStorage(false);
+ this.deleteInsecurePlaintextCredentials();
}
}
-exports.FileCredentialStore = FileCredentialStore;
-function getCredentialStore(userRepository) {
- return new FileCredentialStore(userRepository, (0, graphql_1.getEnvironmentConfig)(CredentialAccount));
+exports.CredentialStoreImpl = CredentialStoreImpl;
+function getCredentialStore(logger, userRepository) {
+ const keytar = getKeytar();
+ const cachedConfig = cache_1.CachedConf.getCache(cache_1.CONFIG_PROJECT_NAME);
+ const instructionsUrl = (0, instruction_1.getInstructionsUrl)();
+ return new CredentialStoreImpl(logger, instructionsUrl, keytar, cachedConfig, userRepository);
}