@forge/cli-shared
9.10.0-next.19.10.0-next.1-experimental-65945d2
out/auth/personal/credential-store.js~
out/auth/personal/credential-store.jsModified+238−1
Index: package/out/auth/personal/credential-store.js
===================================================================
--- package/out/auth/personal/credential-store.js
+++ package/out/auth/personal/credential-store.js
@@ -1,10 +1,15 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
-exports.CredentialStoreImpl = exports.KeytarAccessError = exports.NoKeytarError = exports.NoTokenInStoreError = exports.personalApiCredentialsValidatedShape = exports.personalApiCredentialsShape = exports.API_TOKEN_KEY = exports.EMAIL_KEY = void 0;
+exports.CredentialStoreImpl = exports.FileCredentialStore = exports.CredentialStoreSecurityError = exports.KeytarAccessError = exports.NoKeytarError = exports.NoTokenInStoreError = exports.personalApiCredentialsValidatedShape = exports.personalApiCredentialsShape = exports.FILE_CREDENTIAL_STORE_FLAG = exports.API_TOKEN_KEY = exports.EMAIL_KEY = void 0;
+exports.getCredentialsFilePath = getCredentialsFilePath;
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");
@@ -12,10 +17,19 @@
const shared_1 = require("../../shared");
const ui_1 = require("../../ui");
exports.EMAIL_KEY = 'FORGE_EMAIL';
exports.API_TOKEN_KEY = 'FORGE_API_TOKEN';
+exports.FILE_CREDENTIAL_STORE_FLAG = 'FORGE_CLI_ENABLE_FILE_CREDENTIAL_STORE';
const KEYTAR_SERVICE = 'Atlassian';
const CACHE_CREDENTIALS_KEY = 'forge-credentials';
+const CREDENTIALS_FILE_NAME = 'credentials.json';
+const CONFIG_DIRECTORY_SUFFIX = 'nodejs';
+const CREDENTIALS_DIRECTORY_MODE = 0o700;
+const CREDENTIALS_FILE_MODE = 0o600;
+const PERMISSION_BITS_MASK = 0o777;
+const GROUP_OR_OTHER_WRITE_BITS_MASK = 0o022;
+const WINDOWS_SYSTEM_SID = 'S-1-5-18';
+const WINDOWS_ADMINISTRATORS_SID = 'S-1-5-32-544';
var KeytarAccount;
(function (KeytarAccount) {
KeytarAccount["DEV"] = "Ecosystem-staging";
KeytarAccount["STG"] = "Ecosystem-staging";
@@ -54,8 +68,227 @@
exports.NoKeytarError = NoKeytarError;
class KeytarAccessError extends shared_1.UserError {
}
exports.KeytarAccessError = KeytarAccessError;
+class CredentialStoreSecurityError extends shared_1.UserError {
+ constructor() {
+ super(ui_1.Text.error.credentialsFilePermissions);
+ }
+}
+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';
+}
+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', 'Preferences', `${cache_1.CONFIG_PROJECT_NAME}-${CONFIG_DIRECTORY_SUFFIX}`);
+ break;
+ case 'win32':
+ credentialsDirectory = platformPath.join(environment.LOCALAPPDATA || platformPath.join(userHome, 'AppData', 'Local'), 'Atlassian', 'Forge');
+ break;
+ default:
+ credentialsDirectory = platformPath.join(environment.XDG_CONFIG_HOME || platformPath.join(userHome, '.config'), `${cache_1.CONFIG_PROJECT_NAME}-${CONFIG_DIRECTORY_SUFFIX}`);
+ }
+ return platformPath.join(credentialsDirectory, CREDENTIALS_FILE_NAME);
+}
+class FileCredentialStore {
+ userRepository;
+ account;
+ credentialsFilePath;
+ currentPlatform;
+ commandRunner;
+ windowsUserSid;
+ constructor(userRepository, account, credentialsFilePath = getCredentialsFilePath(), currentPlatform = (0, os_1.platform)(), commandRunner = runCredentialStoreCommand) {
+ this.userRepository = userRepository;
+ this.account = account;
+ this.credentialsFilePath = credentialsFilePath;
+ this.currentPlatform = currentPlatform;
+ this.commandRunner = commandRunner;
+ }
+ 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;
+ }
+ 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;
+ try {
+ await fs_1.promises.access(this.credentialsFilePath);
+ }
+ catch (error) {
+ if (!isFileNotFoundError(error)) {
+ throw error;
+ }
+ fileExists = false;
+ }
+ if (!fileExists && !createFile) {
+ return;
+ }
+ 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);
+ }
+ async securePosixStorage(createFile) {
+ let fileExists = true;
+ try {
+ await fs_1.promises.access(this.credentialsFilePath);
+ }
+ catch (error) {
+ if (!isFileNotFoundError(error)) {
+ throw error;
+ }
+ fileExists = false;
+ }
+ if (!fileExists && !createFile) {
+ return;
+ }
+ const credentialsDirectory = path_1.default.dirname(this.credentialsFilePath);
+ const createdDirectory = await fs_1.promises.mkdir(credentialsDirectory, {
+ recursive: true,
+ mode: CREDENTIALS_DIRECTORY_MODE
+ });
+ if (createdDirectory !== undefined) {
+ 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 & GROUP_OR_OTHER_WRITE_BITS_MASK) !== 0) {
+ throw new Error('The credentials directory is not owned exclusively by the current user');
+ }
+ 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');
+ }
+ }
+ async secureStorage(createFile) {
+ try {
+ if (this.currentPlatform === 'win32') {
+ await this.secureWindowsStorage(createFile);
+ }
+ else {
+ await this.securePosixStorage(createFile);
+ }
+ }
+ 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 };
+ }
+ const credentials = (await this.readCredentialsFile())[this.account];
+ if (!credentials) {
+ throw new NoTokenInStoreError();
+ }
+ return credentials;
+ }
+ async setCredentials(credentials) {
+ let credentialsByAccount;
+ try {
+ credentialsByAccount = await this.readCredentialsFile();
+ }
+ catch (error) {
+ if (!(error instanceof NoTokenInStoreError)) {
+ throw error;
+ }
+ credentialsByAccount = {};
+ }
+ 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);
+ }
+ async deleteCredentials() {
+ const credentialsByAccount = await this.readCredentialsFile();
+ delete credentialsByAccount[this.account];
+ if (Object.keys(credentialsByAccount).length === 0) {
+ try {
+ await fs_1.promises.unlink(this.credentialsFilePath);
+ }
+ catch (error) {
+ if (!isFileNotFoundError(error)) {
+ throw error;
+ }
+ }
+ return;
+ }
+ await fs_1.promises.writeFile(this.credentialsFilePath, `${JSON.stringify(credentialsByAccount, null, 2)}\n`, 'utf8');
+ await this.secureStorage(false);
+ }
+}
+exports.FileCredentialStore = FileCredentialStore;
class CredentialStoreImpl {
logger;
instructionsURL;
keytar;
@@ -183,8 +416,12 @@
}
}
exports.CredentialStoreImpl = CredentialStoreImpl;
function getCredentialStore(logger, userRepository) {
+ const credentialAccount = (0, graphql_1.getEnvironmentConfig)(KeytarAccount);
+ if (process.env[exports.FILE_CREDENTIAL_STORE_FLAG] === 'true') {
+ return new FileCredentialStore(userRepository, credentialAccount);
+ }
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);