'use strict'; const originalEmitWarning = process.emitWarning; process.emitWarning = (warning, ...args) => { const message = typeof warning === 'string' ? warning : warning?.message || ''; if (message.includes('DEPRECATION WARNING')) { return; } // If not the BoxClient deprecation warning, call the original emitWarning function originalEmitWarning.call(process, warning, ...args); }; const { Command, Flags } = require('@oclif/core'); const chalk = require('chalk'); const { promisify } = require('node:util'); const _ = require('lodash'); const fs = require('node:fs'); const { mkdirp } = require('mkdirp'); const os = require('node:os'); const path = require('node:path'); const yaml = require('js-yaml'); const csv = require('csv'); const csvParse = promisify(csv.parse); const csvStringify = promisify(csv.stringify); const dateTime = require('date-fns'); const BoxSDK = require('box-node-sdk').default; const BoxTSSDK = require('box-node-sdk/sdk-gen'); const BoxTsErrors = require('box-node-sdk/sdk-gen/box/errors'); const BoxCLIError = require('./cli-error'); const CLITokenCache = require('./token-cache'); const PaginationUtilities = require('./pagination-utils'); const utils = require('./util'); const pkg = require('../package.json'); const inquirer = require('./inquirer'); const { stringifyStream } = require('@discoveryjs/json-ext'); const progress = require('cli-progress'); const secureStorage = require('./secure-storage'); const DEBUG = require('./debug'); const stream = require('node:stream'); const pipeline = promisify(stream.pipeline); const { Transform } = require('node:stream'); const KEY_MAPPINGS = { url: 'URL', id: 'ID', etag: 'ETag', sha1: 'SHA1', templateKey: 'Template Key', displayName: 'Display Name', tos: 'ToS', statusCode: 'Status Code', boxReportsFolderPath: 'Box Reports Folder Path', boxReportsFolderName: 'Box Reports Folder Name (Deprecated)', boxReportsFileFormat: 'Box Reports File Format', boxDownloadsFolderPath: 'Box Downloads Folder Path', boxDownloadsFolderName: 'Box Downloads Folder Name (Deprecated)', outputJson: 'Output JSON', clientId: 'Client ID', enterpriseId: 'Enterprise ID', boxConfigFilePath: 'Box Config File Path', hasInLinePrivateKey: 'Has Inline Private Key', privateKeyPath: 'Private Key Path', defaultAsUserId: 'Default As-User ID', useDefaultAsUser: 'Use Default As-User', cacheTokens: 'Cache Tokens', ip: 'IP', operationParams: 'Operation Params', copyInstanceOnItemCopy: 'Copy Instance On Item Copy', }; const REQUIRED_FIELDS = ['type', 'id']; const SDK_CONFIG = Object.freeze({ iterators: true, analyticsClient: { version: pkg.version, }, request: { headers: { 'User-Agent': `Box CLI v${pkg.version}`, }, }, }); const CONFIG_FOLDER_PATH = path.join(os.homedir(), '.box'); const SETTINGS_FILE_PATH = path.join(CONFIG_FOLDER_PATH, 'settings.json'); const ENVIRONMENTS_FILE_PATH = path.join( CONFIG_FOLDER_PATH, 'box_environments.json' ); const ENVIRONMENTS_KEYCHAIN_SERVICE = 'boxcli'; const ENVIRONMENTS_KEYCHAIN_ACCOUNT = 'Box'; const DEFAULT_ANALYTICS_CLIENT_NAME = 'box-cli'; /** * Convert error objects to a stable debug-safe shape. * * @param {unknown} error A caught error object * @returns {Object} A reduced object for DEBUG logging */ function getDebugErrorDetails(error) { if (!error || typeof error !== 'object') { return { message: String(error) }; } return { name: error.name || 'Error', code: error.code, message: error.message || String(error), stack: error.stack, }; } /** * Parse a string value from CSV into the correct boolean value * @param {string|boolean} value The value to parse * @returns {boolean} The parsed value * @private */ function getBooleanFlagValue(value) { let trueValues = ['yes', 'y', 'true', '1', 't', 'on']; let falseValues = ['no', 'n', 'false', '0', 'f', 'off']; if (typeof value === 'boolean') { return value; } else if (trueValues.includes(value.toLowerCase())) { return true; } else if (falseValues.includes(value.toLowerCase())) { return false; } let possibleValues = [...trueValues, ...falseValues].join(', '); throw new Error( `Incorrect boolean value "${value}" passed. Possible values are ${possibleValues}` ); } /** * Removes all the undefined values from the object * * @param {Object} obj The object to format for display * @returns {Object} The formatted object output */ function removeUndefinedValues(obj) { if (typeof obj !== 'object' || obj === null) { return obj; } if (Array.isArray(obj)) { return obj.map((item) => removeUndefinedValues(item)); } for (const key of Object.keys(obj)) { if (obj[key] === undefined) { delete obj[key]; } else { obj[key] = removeUndefinedValues(obj[key]); } } return obj; } /** * Add or subtract a given offset from a date * * @param {Date} date The date to offset * @param {int} timeLength The number of time units to offset by * @param {string} timeUnit The unit of time to offset by, in single-character shorthand * @returns {Date} The date with offset applied */ function offsetDate(date, timeLength, timeUnit) { switch (timeUnit) { case 's': { return dateTime.addSeconds(date, timeLength); } case 'm': { return dateTime.addMinutes(date, timeLength); } case 'h': { return dateTime.addHours(date, timeLength); } case 'd': { return dateTime.addDays(date, timeLength); } case 'w': { return dateTime.addWeeks(date, timeLength); } case 'M': { return dateTime.addMonths(date, timeLength); } case 'y': { return dateTime.addYears(date, timeLength); } default: { throw new Error(`Invalid time unit: ${timeUnit}`); } } } /** * Formats an API key (e.g. field name) for human-readable display * * @param {string} key The key to format * @returns {string} The formatted key * @private */ function formatKey(key) { // Converting camel case to snake case and then to title case return key .replaceAll(/[A-Z]/gu, (letter) => `_${letter.toLowerCase()}`) .split('_') .map((s) => KEY_MAPPINGS[s] || _.capitalize(s)) .join(' '); } /** * Formats an object's keys for human-readable output * @param {*} obj The thing to format * @returns {*} The formatted thing * @private */ function formatObjectKeys(obj) { // No need to process primitive values if (typeof obj !== 'object' || obj === null) { return obj; } // If type is Date, convert to ISO string if (obj instanceof Date) { return obj.toISOString(); } // Don't format metadata objects to avoid mangling keys if (obj.$type) { return obj; } if (Array.isArray(obj)) { return obj.map((el) => formatObjectKeys(el)); } let formattedObj = Object.create(null); for (const key of Object.keys(obj)) { let formattedKey = formatKey(key); formattedObj[formattedKey] = formatObjectKeys(obj[key]); } return formattedObj; } /** * Formats an object for output by prettifying its keys * and rendering it in a more human-readable form (i.e. YAML) * * @param {Object} obj The object to format for display * @returns {string} The formatted object output * @private */ function formatObject(obj) { let outputData = formatObjectKeys(obj); // Other objects are formatted as YAML for human-readable output let yamlString = yaml.dump(outputData, { indent: 4, noRefs: true, }); // The YAML library puts a trailing newline at the end of the string, which is // redundant with the automatic newline added by oclif when writing to stdout return yamlString .replace(/\r?\n$/u, '') .replaceAll(/^([^:]+:)/gmu, (match, key) => chalk.cyan(key)); } /** * Formats the object header, used to separate multiple objects in a collection * * @param {Object} obj The object to generate a header for * @returns {string} The header string * @private */ function formatObjectHeader(obj) { if (!obj.type || !obj.id) { return chalk`{dim ----------}`; } return chalk`{dim ----- ${formatKey(obj.type)} ${obj.id} -----}`; } /** * Base class for all Box CLI commands */ class BoxCommand extends Command { // @TODO(2018-08-15): Move all fs methods used here to be async /** * Initialize before the command is run * @returns {void} */ async init() { DEBUG.init('Initializing Box CLI'); let originalArgs, originalFlags; if ( this.argv.some((arg) => arg.startsWith('--bulk-file-path')) && Object.keys(this.constructor.flags).includes('bulk-file-path') ) { // Set up the command for bulk run DEBUG.init('Preparing for bulk input'); this.isBulk = true; // eslint-disable-next-line unicorn/prefer-structured-clone originalArgs = _.cloneDeep(this.constructor.args); // eslint-disable-next-line unicorn/prefer-structured-clone originalFlags = _.cloneDeep(this.constructor.flags); this.disableRequiredArgsAndFlags(); } this.supportsSecureStorage = secureStorage.available; let { flags, args } = await this.parse(this.constructor); this.flags = flags; this.args = args; this.settings = await this._loadSettings(); this.client = await this.getClient(); this.tsClient = await this.getTsClient(); if (this.isBulk) { this.constructor.args = originalArgs; this.constructor.flags = originalFlags; this.bulkOutputList = []; this.bulkErrors = []; this._singleRun = this.run; this.run = this.bulkOutputRun; } DEBUG.execute( 'Starting execution command: %s argv: %O', this.id, this.argv ); } /** * Read in the input file and run the command once for each set of inputs * @returns {void} */ async bulkOutputRun() { const allPossibleArgs = Object.keys(this.constructor.args || {}); const allPossibleFlags = Object.keys(this.constructor.flags || {}); // Map from matchKey (arg/flag name in all lower-case characters) => {type, fieldKey} let fieldMapping = Object.assign( {}, ...allPossibleArgs.map((arg) => ({ [arg.toLowerCase()]: { type: 'arg', fieldKey: arg }, })), ...allPossibleFlags.map((flag) => ({ [flag.replaceAll('-', '')]: { type: 'flag', fieldKey: flag }, })) ); let bulkCalls = await this._parseBulkFile( this.flags['bulk-file-path'], fieldMapping ); let bulkEntryIndex = 0; let progressBar = new progress.Bar({ format: '[{bar}] {percentage}% | {value}/{total}', stopOnComplete: true, }); progressBar.start(bulkCalls.length, 0); for (let bulkData of bulkCalls) { this.argv = []; bulkEntryIndex += 1; this._getArgsForBulkInput(allPossibleArgs, bulkData); this._setFlagsForBulkInput(bulkData); await this._handleAsUserSettings(bulkData); DEBUG.execute('Executing in bulk mode argv: %O', this.argv); // @TODO(2018-08-29): Convert this to a promise queue to improve performance try { await this._singleRun(); } catch (error) { // In bulk mode, we don't want to write directly to console and kill the command // Instead, we should buffer the error output so subsequent commands might be able to succeed DEBUG.execute( 'Caught error from bulk input entry %d', bulkEntryIndex ); this.bulkErrors.push({ index: bulkEntryIndex, data: bulkData, error: this.wrapError(error), }); } progressBar.update(bulkEntryIndex); } this.isBulk = false; DEBUG.execute('Leaving bulk mode and writing final output'); await this.output(this.bulkOutputList); this._handleBulkErrors(); } /** * Logs bulk processing errors if any occured. * @returns {void} * @private */ _handleBulkErrors() { const numErrors = this.bulkErrors.length; if (numErrors === 0) { this.info( chalk`{green All bulk input entries processed successfully.}` ); return; } this.info( chalk`{redBright ${numErrors} entr${numErrors > 1 ? 'ies' : 'y'} failed!}` ); for (const errorInfo of this.bulkErrors) { this.info(chalk`{dim ----------}`); let entryData = errorInfo.data .map((o) => ` ${o.fieldKey}=${o.value}`) .join(os.EOL); this.info( chalk`{redBright Entry ${errorInfo.index} (${ os.EOL + entryData + os.EOL }) failed with error:}` ); let err = errorInfo.error; let contextInfo; if ( err.response && err.response.body && err.response.body.context_info ) { contextInfo = formatObject(err.response.body.context_info); // Remove color codes from context info // eslint-disable-next-line no-control-regex contextInfo = contextInfo.replaceAll(/\u001B\[\d+m/gu, ''); // Remove \n with os.EOL contextInfo = contextInfo.replaceAll('\n', os.EOL); } let errMsg = chalk`{redBright ${ this.flags && this.flags.verbose ? err.stack : err.message }${os.EOL}${contextInfo ? contextInfo + os.EOL : ''}}`; this.info(errMsg); } } /** * Set as-user header from the bulk file or use the default one. * @param {Array} bulkData Bulk data * @returns {Promise} Returns nothing * @private */ async _handleAsUserSettings(bulkData) { let asUser = bulkData.find((o) => o.fieldKey === 'as-user') || {}; if (!_.isEmpty(asUser)) { if (_.isNil(asUser.value)) { let environmentsObj = await this.getEnvironments(); if (environmentsObj.default) { let environment = environmentsObj.environments[environmentsObj.default]; DEBUG.init( 'Using environment %s %O', environmentsObj.default, environment ); if (environment.useDefaultAsUser) { this.client.asUser(environment.defaultAsUserId); DEBUG.init( 'Impersonating default user ID %s', environment.defaultAsUserId ); } else { this.client.asSelf(); } } else { this.client.asSelf(); } } else { this.client.asUser(asUser.value); DEBUG.init('Impersonating user ID %s', asUser.value); } } } /** * Include flag values from command line first, * they'll automatically be overwritten/combined with later values by the oclif parser. * @param {Array} bulkData Bulk data * @returns {void} * @private */ _setFlagsForBulkInput(bulkData) { const bulkDataFlags = new Set( bulkData .filter((o) => o.type === 'flag' && !_.isNil(o.value)) .map((o) => o.fieldKey) ); for (const flag of Object.keys(this.flags) .filter((flag) => flag !== 'bulk-file-path') // Remove the bulk file path flag so we don't recurse! .filter((flag) => !bulkDataFlags.has(flag))) { // Some flags can be specified multiple times in a single command. For these flags, their value is an array of user inputted values. // For these flags, we iterate through their values and add each one as a separate flag to comply with oclif if (Array.isArray(this.flags[flag])) { for (const value of this.flags[flag]) { this._addFlagToArgv(flag, value); } } else { this._addFlagToArgv(flag, this.flags[flag]); } } // Include all flag values from bulk input, which will override earlier ones // from the command line for (const o of bulkData // Remove the bulk file path flag so we don't recurse! .filter( (o) => o.type === 'flag' && o.fieldKey !== 'bulk-file-path' )) this._addFlagToArgv(o.fieldKey, o.value); } /** * For each possible arg, find the correct value between bulk input and values given on the command line. * @param {Array} allPossibleArgs All possible args * @param {Array} bulkData Bulk data * @returns {void} * @private */ _getArgsForBulkInput(allPossibleArgs, bulkData) { for (let arg of allPossibleArgs) { let bulkArg = bulkData.find((o) => o.fieldKey === arg) || {}; if (!_.isNil(bulkArg.value)) { // Use value from bulk input file when available this.argv.push(bulkArg.value); } else if (this.args[arg]) { // Fall back to value from command line this.argv.push(this.args[arg]); } } } /** * Parses file wilk bulk commands * @param {String} filePath Path to file with bulk commands * @param {Array} fieldMapping Data to parse * @returns {Promise<*>} Returns parsed data * @private */ async _parseBulkFile(filePath, fieldMapping) { const fileExtension = path.extname(filePath); const fileContents = this._readBulkFile(filePath); let bulkCalls; if (fileExtension === '.json') { bulkCalls = this._handleJsonFile(fileContents, fieldMapping); } else if (fileExtension === '.csv') { bulkCalls = await this._handleCsvFile(fileContents, fieldMapping); } else { throw new Error( `Input file had extension "${fileExtension}", but only .json and .csv are supported` ); } // Filter out any undefined values, which can arise when the input file contains extraneous keys bulkCalls = bulkCalls.map((args) => args.filter((o) => o !== undefined) ); DEBUG.execute( 'Read %d entries from bulk file %s', bulkCalls.length, this.flags['bulk-file-path'] ); return bulkCalls; } /** * Parses CSV file * @param {Object} fileContents File content to parse * @param {Array} fieldMapping Field mapings * @returns {Promise} Returns parsed data * @private */ async _handleCsvFile(fileContents, fieldMapping) { let parsedData = await csvParse(fileContents, { bom: true, delimiter: ',', cast(value, context) { if (value.length === 0) { // Regard unquoted empty values as null return context.quoting ? '' : null; } return value; }, }); if (parsedData.length < 2) { throw new Error( 'CSV input file should contain the headers row and at least on data row' ); } // @NOTE: We don't parse the CSV into an aray of Objects // and instead mainatain a separate array of headers, in // order to ensure that ordering is maintained in the keys let headers = parsedData.shift().map((key) => { let keyParts = key.match(/(.*)_\d+$/u); let someKey = keyParts ? keyParts[1] : key; return someKey.toLowerCase().replaceAll(/[-_]/gu, ''); }); return parsedData.map((values) => values.map((value, index) => { let key = headers[index]; let field = fieldMapping[key]; return field ? { ...field, value } : undefined; }) ); } /** * Parses JSON file * @param {Object} fileContents File content to parse * @param {Array} fieldMapping Field mapings * @returns {*} Returns parsed data * @private */ _handleJsonFile(fileContents, fieldMapping) { let parsedData; try { let jsonFile = JSON.parse(fileContents); parsedData = Object.hasOwn(jsonFile, 'entries') ? jsonFile.entries : jsonFile; } catch (error) { throw new BoxCLIError( `Could not parse JSON input file ${this.flags['bulk-file-path']}`, error ); } if (!Array.isArray(parsedData)) { throw new TypeError( 'Expected input file to contain an array of input objects, but none found' ); } // Translate each row object to an array of {type, fieldKey, value}, to be handled below return parsedData.map(function flattenObjectToArgs(obj) { // One top-level object key can map to multiple args/flags, so we need to deeply flatten after mapping return _.flatMapDeep(obj, (value, key) => { let matchKey = key.toLowerCase().replaceAll(/[-_]/gu, ''); let field = fieldMapping[matchKey]; if (_.isPlainObject(value)) { // Map e.g. { item: { id: 12345, type: folder } } => { item: 12345, itemtype: folder } // @NOTE: For now, we only support nesting keys this way one level deep return Object.keys(value).map((nestedKey) => { let nestedMatchKey = matchKey + nestedKey.toLowerCase().replaceAll(/[-_]/gu, ''); let nestedField = fieldMapping[nestedMatchKey]; return nestedField ? { ...nestedField, value: value[nestedKey] } : undefined; }); } else if (Array.isArray(value)) { // Arrays can be one of two things: an array of values for a single key, // or an array of grouped flags/args as objects // First, check if everything in the array is either all object or all non-object let types = value.map((t) => typeof t); if ( types.some((t) => t !== 'object') && types.includes('object') ) { throw new BoxCLIError( 'Mixed types in bulk input JSON array; use strings or Objects' ); } // If everything in the array is objects, handle each one as a group of flags and args // by recursively parsing that object into args if (types[0] === 'object') { return value.map((o) => flattenObjectToArgs(o)); } // If the array is of values for this field, just return those return field ? value.map((v) => ({ ...field, value: v })) : []; } return field ? { ...field, value } : undefined; }); }); } /** * Returns bulk file contents * @param {String} filePath Path to bulk file * @returns {Buffer} Bulk file contents * @private */ _readBulkFile(filePath) { try { const fileContents = fs.readFileSync(filePath); DEBUG.execute('Read bulk input file at %s', filePath); return fileContents; } catch (error) { throw new BoxCLIError( `Could not open input file ${filePath}`, error ); } } /** * Writes a given flag value to the command's argv array * * @param {string} flag The flag name * @param {*} flagValue The flag value * @returns {void} * @private */ _addFlagToArgv(flag, flagValue) { if (_.isNil(flagValue)) { return; } if (this.constructor.flags[flag].type === 'boolean') { if (getBooleanFlagValue(flagValue)) { this.argv.push(`--${flag}`); } else { this.argv.push(`--no-${flag}`); } } else { this.argv.push(`--${flag}=${flagValue}`); } } /** * Ensure that all args and flags for the command are not marked as required, * to avoid issues when filling in required values from the input file. * @returns {void} */ disableRequiredArgsAndFlags() { if (this.constructor.args !== undefined) { for (const key of Object.keys(this.constructor.args)) { this.constructor.args[key].required = false; } } if (this.constructor.flags !== undefined) { for (const key of Object.keys(this.constructor.flags)) { this.constructor.flags[key].required = false; } } } /** * Instantiate the SDK client for making API calls * * @returns {BoxClient} The client for making API calls in the command */ async getClient() { // Allow some commands (e.g. configure:environments:add, login) to skip client setup so they can run if (this.constructor.noClient) { return null; } let environmentsObj = await this.getEnvironments(); const environment = environmentsObj.environments[environmentsObj.default] || {}; const { authMethod } = environment; let client; if (this.flags.token) { DEBUG.init('Using passed in token %s', this.flags.token); let sdk = new BoxSDK({ clientID: '', clientSecret: '', ...SDK_CONFIG, }); this._configureSdk(sdk, { ...SDK_CONFIG }); this.sdk = sdk; client = sdk.getBasicClient(this.flags.token); } else if (authMethod === 'ccg') { DEBUG.init('Using Client Credentials Grant Authentication'); const { clientId, clientSecret, ccgUser } = environment; if (!clientId || !clientSecret) { throw new BoxCLIError( 'You need to have a default environment with clientId and clientSecret in order to use CCG' ); } let configObj; try { configObj = JSON.parse( fs.readFileSync(environment.boxConfigFilePath) ); } catch (error) { throw new BoxCLIError( 'Could not read environments config file', error ); } const { enterpriseID } = configObj; const sdk = new BoxSDK({ clientID: clientId, clientSecret, enterpriseID, ...SDK_CONFIG, }); this._configureSdk(sdk, { ...SDK_CONFIG }); this.sdk = sdk; client = ccgUser ? sdk.getCCGClientForUser(ccgUser) : sdk.getAnonymousClient(); } else if ( environmentsObj.default && environmentsObj.environments[environmentsObj.default].authMethod === 'oauth20' ) { try { DEBUG.init( 'Using environment %s %O', environmentsObj.default, environment ); let tokenCache = new CLITokenCache(environmentsObj.default); let sdk = new BoxSDK({ clientID: environment.clientId, clientSecret: environment.clientSecret, ...SDK_CONFIG, }); this._configureSdk(sdk, { ...SDK_CONFIG }); this.sdk = sdk; let tokenInfo = await new Promise((resolve, reject) => { tokenCache.read((error, localTokenInfo) => { if (error) { reject(error); } else { resolve(localTokenInfo); } }); }); client = sdk.getPersistentClient(tokenInfo, tokenCache); } catch { throw new BoxCLIError( `Can't load the default OAuth environment "${environmentsObj.default}". Please reauthorize selected environment, login again or provide a token.` ); } } else if (environmentsObj.default) { DEBUG.init( 'Using environment %s %O', environmentsObj.default, environment ); let tokenCache = environment.cacheTokens === false ? null : new CLITokenCache(environmentsObj.default); let configObj; try { configObj = JSON.parse( fs.readFileSync(environment.boxConfigFilePath) ); } catch (error) { throw new BoxCLIError( 'Could not read environments config file', error ); } if (!environment.hasInLinePrivateKey) { try { configObj.boxAppSettings.appAuth.privateKey = fs.readFileSync(environment.privateKeyPath, 'utf8'); DEBUG.init( 'Loaded JWT private key from %s', environment.privateKeyPath ); } catch (error) { throw new BoxCLIError( `Could not read private key file ${environment.privateKeyPath}`, error ); } } this.sdk = BoxSDK.getPreconfiguredInstance(configObj); this._configureSdk(this.sdk, { ...SDK_CONFIG }); client = this.sdk.getAppAuthClient( 'enterprise', environment.enterpriseId, tokenCache ); DEBUG.init('Initialized client from environment config'); } else { // No environments set up yet! throw new BoxCLIError( `No default environment found. It looks like you haven't configured the Box CLI yet. See this command for help adding an environment: box configure:environments:add --help Or, supply a token with your command with --token.`.replaceAll(/^\s+/gmu, '') ); } // Using the as-user flag should have precedence over the environment setting if (this.flags['as-user']) { client.asUser(this.flags['as-user']); DEBUG.init( 'Impersonating user ID %s using the ID provided via the --as-user flag', this.flags['as-user'] ); } else if (!this.flags.token && environment.useDefaultAsUser) { // We don't want to use any environment settings if a token is passed in the command client.asUser(environment.defaultAsUserId); DEBUG.init( 'Impersonating default user ID %s using environment configuration', environment.defaultAsUserId ); } return client; } /** * Instantiate the TypeScript SDK client for making API calls * * @returns {BoxTSSDK.BoxClient} The TypeScript SDK client for making API calls in the command */ async getTsClient() { // Allow some commands (e.g. configure:environments:add, login) to skip client setup so they can run if (this.constructor.noClient) { return null; } let environmentsObj = await this.getEnvironments(); const environment = environmentsObj.environments[environmentsObj.default] || {}; const { authMethod } = environment; let client; if (this.flags.token) { DEBUG.init('Using passed in token %s', this.flags.token); let tsSdkAuth = new BoxTSSDK.BoxDeveloperTokenAuth({ token: this.flags.token, }); client = new BoxTSSDK.BoxClient({ auth: tsSdkAuth, }); client = this._configureTsSdk(client, SDK_CONFIG); } else if (authMethod === 'ccg') { DEBUG.init('Using Client Credentials Grant Authentication'); const { clientId, clientSecret, ccgUser } = environment; if (!clientId || !clientSecret) { throw new BoxCLIError( 'You need to have a default environment with clientId and clientSecret in order to use CCG' ); } let configObj; try { configObj = JSON.parse( fs.readFileSync(environment.boxConfigFilePath) ); } catch (error) { throw new BoxCLIError( 'Could not read environments config file', error ); } const { enterpriseID } = configObj; const tokenCache = environment.cacheTokens === false ? null : new CLITokenCache(environmentsObj.default); let ccgConfig = new BoxTSSDK.CcgConfig( ccgUser ? { clientId, clientSecret, userId: ccgUser, tokenStorage: tokenCache, } : { clientId, clientSecret, enterpriseId: enterpriseID, tokenStorage: tokenCache, } ); let ccgAuth = new BoxTSSDK.BoxCcgAuth({ config: ccgConfig }); client = new BoxTSSDK.BoxClient({ auth: ccgAuth, }); client = this._configureTsSdk(client, SDK_CONFIG); } else if ( environmentsObj.default && environmentsObj.environments[environmentsObj.default].authMethod === 'oauth20' ) { try { DEBUG.init( 'Using environment %s %O', environmentsObj.default, environment ); const tokenCache = new CLITokenCache(environmentsObj.default); const oauthConfig = new BoxTSSDK.OAuthConfig({ clientId: environment.clientId, clientSecret: environment.clientSecret, tokenStorage: tokenCache, }); const oauthAuth = new BoxTSSDK.BoxOAuth({ config: oauthConfig, }); client = new BoxTSSDK.BoxClient({ auth: oauthAuth }); client = this._configureTsSdk(client, SDK_CONFIG); } catch { throw new BoxCLIError( `Can't load the default OAuth environment "${environmentsObj.default}". Please reauthorize selected environment, login again or provide a token.` ); } } else if (environmentsObj.default) { DEBUG.init( 'Using environment %s %O', environmentsObj.default, environment ); let tokenCache = environment.cacheTokens === false ? null : new CLITokenCache(environmentsObj.default); let configObj; try { configObj = JSON.parse( fs.readFileSync(environment.boxConfigFilePath) ); } catch (error) { throw new BoxCLIError( 'Could not read environments config file', error ); } if (!environment.hasInLinePrivateKey) { try { configObj.boxAppSettings.appAuth.privateKey = fs.readFileSync(environment.privateKeyPath, 'utf8'); DEBUG.init( 'Loaded JWT private key from %s', environment.privateKeyPath ); } catch (error) { throw new BoxCLIError( `Could not read private key file ${environment.privateKeyPath}`, error ); } } const jwtConfig = new BoxTSSDK.JwtConfig({ clientId: configObj.boxAppSettings.clientID, clientSecret: configObj.boxAppSettings.clientSecret, jwtKeyId: configObj.boxAppSettings.appAuth.publicKeyID, privateKey: configObj.boxAppSettings.appAuth.privateKey, privateKeyPassphrase: configObj.boxAppSettings.appAuth.passphrase, enterpriseId: environment.enterpriseId, tokenStorage: tokenCache, }); let jwtAuth = new BoxTSSDK.BoxJwtAuth({ config: jwtConfig }); client = new BoxTSSDK.BoxClient({ auth: jwtAuth }); DEBUG.init('Initialized client from environment config'); if (environment.useDefaultAsUser) { client = client.withAsUserHeader(environment.defaultAsUserId); DEBUG.init( 'Impersonating default user ID %s', environment.defaultAsUserId ); } client = this._configureTsSdk(client, SDK_CONFIG); } else { // No environments set up yet! throw new BoxCLIError( `No default environment found. It looks like you haven't configured the Box CLI yet. See this command for help adding an environment: box configure:environments:add --help Or, supply a token with your command with --token.`.replaceAll(/^\s+/gmu, '') ); } if (this.flags['as-user']) { client = client.withAsUserHeader(this.flags['as-user']); DEBUG.init('Impersonating user ID %s', this.flags['as-user']); } return client; } /** * Configures SDK by using values from settings.json file * @param {*} sdk to configure * @param {*} config Additional options to use while building configuration * @returns {void} */ _configureSdk(sdk, config = {}) { const clientSettings = { ...config }; if (this.settings.enableProxy) { clientSettings.proxy = this.settings.proxy; } if (this.settings.apiRootURL) { clientSettings.apiRootURL = this.settings.apiRootURL; } if (this.settings.uploadAPIRootURL) { clientSettings.uploadAPIRootURL = this.settings.uploadAPIRootURL; } if (this.settings.authorizeRootURL) { clientSettings.authorizeRootURL = this.settings.authorizeRootURL; } if (this.settings.numMaxRetries) { clientSettings.numMaxRetries = this.settings.numMaxRetries; } if (this.settings.retryIntervalMS) { clientSettings.retryIntervalMS = this.settings.retryIntervalMS; } if (this.settings.uploadRequestTimeoutMS) { clientSettings.uploadRequestTimeoutMS = this.settings.uploadRequestTimeoutMS; } clientSettings.analyticsClient.name = this.settings.enableAnalyticsClient && this.settings.analyticsClient.name ? `${DEFAULT_ANALYTICS_CLIENT_NAME} ${this.settings.analyticsClient.name}` : DEFAULT_ANALYTICS_CLIENT_NAME; if (Object.keys(clientSettings).length > 0) { DEBUG.init('SDK client settings %s', clientSettings); sdk.configure(clientSettings); } } /** * Configures TS SDK by using values from settings.json file * * @param {BoxTSSDK.BoxClient} client to configure * @param {Object} config Additional options to use while building configuration * @returns {BoxTSSDK.BoxClient} The configured client */ _configureTsSdk(client, config) { let additionalHeaders = config.request.headers; let customBaseURL = { baseUrl: 'https://api.box.com', uploadUrl: 'https://upload.box.com/api', oauth2Url: 'https://account.box.com/api/oauth2', }; if (this.settings.enableProxy) { client = client.withProxy(this.settings.proxy); } if (this.settings.apiRootURL) { customBaseURL.baseUrl = this.settings.apiRootURL; } if (this.settings.uploadAPIRootURL) { customBaseURL.uploadUrl = this.settings.uploadAPIRootURL; } if (this.settings.authorizeRootURL) { customBaseURL.oauth2Url = this.settings.authorizeRootURL; } client = client.withCustomBaseUrls(customBaseURL); if (this.settings.numMaxRetries) { // Not supported in TS SDK } if (this.settings.retryIntervalMS) { // Not supported in TS SDK } if (this.settings.uploadRequestTimeoutMS) { // Not supported in TS SDK } additionalHeaders['X-Box-UA'] = this.settings.enableAnalyticsClient && this.settings.analyticsClient.name ? `${DEFAULT_ANALYTICS_CLIENT_NAME} ${this.settings.analyticsClient.name}` : DEFAULT_ANALYTICS_CLIENT_NAME; client = client.withExtraHeaders(additionalHeaders); DEBUG.init('TS SDK configured with settings from settings.json'); return client; } /** * Returns true when raw API JSON output was requested. * * @returns {boolean} True if raw JSON output should be used * @private */ _wantsRawJsonOutput() { return Boolean(this.flags && this.flags['raw-json']); } /** * Preserves default output behavior while adding raw JSON support. * * The generated TypeScript client can expose response objects with normalized * field names that do not match the original API schema. That behavior was * introduced as newer commands moved to `tsClient`. To fix the JSON output * shape without a breaking change, commands that support `--raw-json` use this * wrapper on the top-level response object before calling `output()`. * * @param {*} content The content to potentially replace with rawData * @returns {*} The content to send to output formatting */ getOutputContentWithRawJsonSupport(content) { if (typeof content === 'object' && content !== null) { if (this._wantsRawJsonOutput()) { return content.rawData ?? content; } if (Object.hasOwn(content, 'rawData')) { const output = { ...content }; delete output.rawData; return output; } } return content; } /** * Format data for output to stdout * @param {*} content The content to output * @returns {Promise} A promise resolving when output is handled */ async output(content) { if (this.isBulk) { this.bulkOutputList.push(content); DEBUG.output( 'Added command output to bulk list total: %d', this.bulkOutputList.length ); return; } let formattedOutputData; if (Array.isArray(content)) { // Format each object individually and then flatten in case this an array of arrays, // which happens when a command that outputs a collection gets run in bulk const formattedOutputResults = await Promise.all( content.map((o) => this._formatOutputObject(o)) ); formattedOutputData = formattedOutputResults.flat(); DEBUG.output( 'Formatted %d output entries for display', content.length ); } else { formattedOutputData = await this._formatOutputObject(content); DEBUG.output('Formatted output content for display'); } let outputFormat = this._getOutputFormat(); DEBUG.output('Using %s output format', outputFormat); DEBUG.output(formattedOutputData); let writeFunc; let logFunc; let stringifiedOutput; // remove all the undefined values from the object formattedOutputData = removeUndefinedValues(formattedOutputData); if (outputFormat === 'json') { stringifiedOutput = stringifyStream(formattedOutputData, null, 4); let appendNewLineTransform = new Transform({ transform(chunk, encoding, callback) { callback(null, chunk); }, flush(callback) { this.push(os.EOL); callback(); }, }); writeFunc = async (savePath) => { await pipeline( stringifiedOutput, appendNewLineTransform, fs.createWriteStream(savePath, { encoding: 'utf8' }) ); }; logFunc = async () => { await this.logStream(stringifiedOutput); }; } else { stringifiedOutput = await this._stringifyOutput(formattedOutputData); writeFunc = async (savePath) => { await utils.writeFileAsync( savePath, stringifiedOutput + os.EOL, { encoding: 'utf8', } ); }; logFunc = () => this.log(stringifiedOutput); } return this._writeOutput(writeFunc, logFunc); } /** * Check if max-items has been reached. * * @param {number} maxItems Total number of items to return * @param {number} itemsCount Current number of items * @returns {boolean} True if limit has been reached, otherwise false * @private */ maxItemsReached(maxItems, itemsCount) { return maxItems && itemsCount >= maxItems; } /** * Fetch all marker-based pages from a TypeScript SDK endpoint. * * @param {Function} fetchPage Callback that receives query params and returns a paged response * @param {Object} queryParams Base query params for each request * @param {number} [maxItemsOverride] Optional max items override for advanced use * @returns {Promise} Aggregated marker-based response entries */ async markerPagination(fetchPage, queryParams, maxItemsOverride) { const normalizedQueryParams = queryParams || {}; const paginationFlags = { 'max-items': maxItemsOverride === undefined ? this.flags['max-items'] : maxItemsOverride, }; const paginationOptions = PaginationUtilities.handlePagination(paginationFlags); const maxItems = paginationFlags['max-items'] === undefined ? paginationOptions.limit : paginationFlags['max-items']; let remaining = maxItems; const entries = []; const pageLimit = paginationOptions.limit; let marker; while (remaining > 0) { const pageQueryParams = { ...normalizedQueryParams, limit: Math.min(pageLimit, remaining), }; if (marker) { pageQueryParams.marker = marker; } const page = await fetchPage(pageQueryParams); const rawPage = typeof page?.rawData === 'object' && page.rawData !== null ? page.rawData : page; const pageEntries = rawPage.entries || page.entries || []; entries.push(...pageEntries); remaining -= pageEntries.length; marker = page.nextMarker || page.next_marker; if (!marker || pageEntries.length === 0) { break; } } return entries; } /** * Prepare the output data by: * 1) Unrolling an iterator into an array * 2) Filtering out unwanted object fields * * @param {*} obj The raw object containing output data * @returns {*} The formatted output data * @private */ async _formatOutputObject(obj) { let output = obj; // Pass primitive content types through if (typeof output !== 'object' || output === null) { return output; } // Unroll iterator into array if (typeof obj.next === 'function') { output = []; let entry = await obj.next(); while (!entry.done) { output.push(entry.value); if ( this.maxItemsReached(this.flags['max-items'], output.length) ) { break; } entry = await obj.next(); } DEBUG.output('Unrolled iterable into %d entries', output.length); } if (this.flags['id-only']) { output = Array.isArray(output) ? this.filterOutput(output, 'id') : output.id; } else { output = this.filterOutput(output, this.flags.fields); } return output; } /** * Get the output format (and file extension) based on the settings and flags set * * @returns {string} The file extension/format to use for output * @private */ _getOutputFormat() { if (this.flags.json) { return 'json'; } // Raw API payloads are only intended for JSON output, so `--raw-json` // implicitly promotes the format to JSON without changing default behavior. if (this._wantsRawJsonOutput()) { return 'json'; } if (this.flags.csv) { return 'csv'; } if (this.flags.save || this.flags['save-to-file-path']) { return this.settings.boxReportsFileFormat || 'txt'; } if (this.settings.outputJson) { return 'json'; } return 'txt'; } /** * Converts output data to a string based on the type of content and flags the user * has specified regarding output format * * @param {*} outputData The data to output * @returns {string} Promise resolving to the output data as a string * @private */ async _stringifyOutput(outputData) { let outputFormat = this._getOutputFormat(); if (typeof outputData !== 'object') { DEBUG.output('Primitive output cast to string'); return String(outputData); } else if (outputFormat === 'csv') { let csvString = await csvStringify( this.formatForTableAndCSVOutput(outputData) ); // The CSV library puts a trailing newline at the end of the string, which is // redundant with the automatic newline added by oclif when writing to stdout DEBUG.output('Processed output as CSV'); return csvString.replace(/\r?\n$/u, ''); } else if (Array.isArray(outputData)) { let str = outputData .map( (o) => `${formatObjectHeader(o)}${os.EOL}${formatObject(o)}` ) .join(os.EOL.repeat(2)); DEBUG.output('Processed collection into human-readable output'); return str; } let str = formatObject(outputData); DEBUG.output('Processed human-readable output'); return str; } /** * Generate an appropriate default filename for writing * the output of this command to disk. * * @returns {string} The output file name * @private */ _getOutputFileName() { let extension = this._getOutputFormat(); return `${this.id.replaceAll(':', '-')}-${dateTime.format( new Date(), 'YYYY-MM-DD_HH_mm_ss_SSS' )}.${extension}`; } /** * Write output to its final destination, either a file or stdout * @param {Function} writeFunc Function used to save output to a file * @param {Function} logFunc Function used to print output to stdout * @returns {Promise} A promise resolving when output is written * @private */ async _writeOutput(writeFunc, logFunc) { if (this.flags.save) { DEBUG.output('Writing output to default location on disk'); let filePath = path.join( this.settings.boxReportsFolderPath, this._getOutputFileName() ); try { await writeFunc(filePath); } catch (error) { throw new BoxCLIError( `Could not write output to file at ${filePath}`, error ); } this.info(chalk`{green Output written to ${filePath}}`); } else if (this.flags['save-to-file-path']) { let savePath = this.flags['save-to-file-path']; if (fs.existsSync(savePath)) { if (fs.statSync(savePath).isDirectory()) { // Append default file name and write into the provided directory savePath = path.join(savePath, this._getOutputFileName()); DEBUG.output( 'Output path is a directory, will write to %s', savePath ); } else { DEBUG.output('File already exists at %s', savePath); // Ask if the user want to overwrite the file let shouldOverwrite = await this.confirm( `File ${savePath} already exists — overwrite?` ); if (!shouldOverwrite) { return; } } } try { DEBUG.output( 'Writing output to specified location on disk: %s', savePath ); await writeFunc(savePath); } catch (error) { throw new BoxCLIError( `Could not write output to file at ${savePath}`, error ); } this.info(chalk`{green Output written to ${savePath}}`); } else { DEBUG.output('Writing output to terminal'); await logFunc(); } DEBUG.output('Finished writing output'); } /** * Ask a user to confirm something, respecting the default --yes flag * * @param {string} promptText The text of the prompt to the user * @param {boolean} defaultValue The default value of the prompt * @returns {Promise} A promise resolving to a boolean that is true iff the user confirmed */ async confirm(promptText, defaultValue = false) { if (this.flags.yes) { return true; } let answers = await inquirer.prompt([ { name: 'confirmation', message: promptText, type: 'confirm', default: defaultValue, }, ]); return answers.confirmation; } /** * Writes output to stderr — this should be used for informational output. For example, a message * stating that an item has been deleted. * * @param {string} content The message to output * @returns {void} */ info(content) { if (!this.flags.quiet) { process.stderr.write(`${content}${os.EOL}`); } } /** * Writes output to stderr — this should be used for informational output. For example, a message * stating that an item has been deleted. * * @param {string} content The message to output * @returns {void} */ log(content) { if (!this.flags.quiet) { process.stdout.write(`${content}${os.EOL}`); } } /** * Writes stream output to stderr — this should be used for informational output. For example, a message * stating that an item has been deleted. * * @param {ReadableStream} content The message to output * @returns {void} */ async logStream(content) { if (!this.flags.quiet) { // For Node 12 when process.stdout is in pipeline it's not emitting end event correctly and it freezes. // See - https://github.com/nodejs/node/issues/34059 // Using promise for now. content.pipe(process.stdout); await new Promise((resolve, reject) => { content .on('end', () => { process.stdout.write(os.EOL); resolve(); }) .on('error', (err) => { reject(err); }); }); } } /** * Wraps filtered error in an error with a user-friendly description * * @param {Error} err The thrown error * @returns {Error} Error wrapped in an error with user friendly description */ wrapError(err) { let messageMap = { 'invalid_grant - Refresh token has expired': 'Your refresh token has expired. \nPlease run this command "box login --name --reauthorize" to reauthorize selected environment and then run your command again.', 'Expired Auth: Auth code or refresh token has expired': 'Authentication failed: token is invalid or expired. OAuth: run "box login --reauthorize". JWT/CCG: tokens are refreshed automatically, so this usually means app credentials or environment configuration must be fixed. You can also provide a fresh token with --token.', }; for (const key in messageMap) { if (err.message.includes(key)) { return new BoxCLIError(messageMap[key], err); } } return err; } /** * Handles an error thrown within a command * * @param {Error} err The thrown error * @returns {void} */ async catch(err) { const AUTH_FAILED_HINT = 'Authentication failed: token is invalid or expired. OAuth: run "box login --reauthorize". JWT/CCG: tokens are refreshed automatically, so a 401 usually means app credentials or environment configuration must be fixed. You can also provide a fresh token with --token.'; if ( err instanceof BoxTsErrors.BoxApiError && err.responseInfo && err.responseInfo.body ) { const responseInfo = err.responseInfo; let errorMessage = `Unexpected API Response [${responseInfo.body.status} ${responseInfo.body.message} | ${responseInfo.body.request_id}] ${responseInfo.body.code} - ${responseInfo.body.message}`; if (responseInfo.body.status === 401) { errorMessage += `\n${AUTH_FAILED_HINT}`; } err = new BoxCLIError(errorMessage, err); } if (err instanceof BoxTsErrors.BoxSdkError) { try { let errorObj = JSON.parse(err.message); if (errorObj.message) { err = new BoxCLIError(errorObj.message, err); } } catch (error) { DEBUG.execute('Error parsing BoxSdkError message: %s', error); } } try { // Let the oclif default handler run first, since it handles the help and version flags there /* eslint-disable promise/no-promise-in-callback */ DEBUG.execute('Running framework error handler'); await super.catch(this.wrapError(err)); } catch (error) { // The oclif default catch handler rethrows most errors; handle those here DEBUG.execute('Handling re-thrown error in base command handler'); if (error.code === 'EEXIT') { // oclif throws this when it handled the error itself and wants to exit, so just let it do that DEBUG.execute('Got EEXIT code, exiting immediately'); return; } let contextInfo; if ( error.response && error.response.body && error.response.body.context_info ) { contextInfo = formatObject(error.response.body.context_info); // Remove color codes from context info // eslint-disable-next-line no-control-regex contextInfo = contextInfo.replaceAll(/\u001B\[\d+m/gu, ''); // Remove \n with os.EOL contextInfo = contextInfo.replaceAll('\n', os.EOL); } let statusHint = ''; const statusCode = error.statusCode || error.response?.statusCode; if (statusCode === 401) { statusHint = AUTH_FAILED_HINT; } let errorMsg = chalk`{redBright ${ this.flags && this.flags.verbose ? error.stack : error.message }${os.EOL}${contextInfo ? contextInfo + os.EOL : ''}${statusHint ? statusHint + os.EOL : ''}}`; // Write the error message but let the process exit gracefully with error code so stderr gets written out // @NOTE: Exiting the process in the callback enables tests to mock out stderr and run to completion! process.stderr.write(errorMsg, () => { process.exitCode = 2; }); } } /** * Final hook that executes for all commands, regardless of if an error occurred * @param {Error} [err] An error, if one occurred * @returns {void} */ async finally(/* err */) { // called after run and catch regardless of whether or not the command errored } /** * Filter out unwanted fields from the output object(s) * * @param {Object|Object[]} output The output object(s) * @param {string} [fields] Comma-separated list of fields to include * @returns {Object|Object[]} The filtered object(s) for output */ filterOutput(output, fields) { if (!fields) { return output; } fields = [ ...REQUIRED_FIELDS, ...fields.split(',').filter((f) => !REQUIRED_FIELDS.includes(f)), ]; DEBUG.output('Filtering output with fields: %O', fields); if (Array.isArray(output)) { output = output.map((o) => typeof o === 'object' ? _.pick(o, fields) : o ); } else if (typeof output === 'object') { output = _.pick(output, fields); } return output; } /** * Flatten nested objects for output to a table/CSV * * @param {Object[]} objectArray The objects that will be output * @returns {Array[]} The formatted output */ formatForTableAndCSVOutput(objectArray) { let formattedData = []; if (!Array.isArray(objectArray)) { objectArray = [objectArray]; DEBUG.output('Creating tabular output from single object'); } let keyPaths = []; for (let object of objectArray) { keyPaths = _.union(keyPaths, this.getNestedKeys(object)); } DEBUG.output('Found %d keys for tabular output', keyPaths.length); formattedData.push(keyPaths); for (let object of objectArray) { let row = []; if (typeof object === 'object') { for (let keyPath of keyPaths) { let value = _.get(object, keyPath); if (value === null || value === undefined) { row.push(''); } else { row.push(value); } } } else { row.push(object); } DEBUG.output('Processed row with %d values', row.length); formattedData.push(row); } DEBUG.output( 'Processed %d rows of tabular output', formattedData.length - 1 ); return formattedData; } /** * Extracts all keys from an object and flattens them * * @param {Object} object The object to extract flattened keys from * @returns {string[]} The array of flattened keys */ getNestedKeys(object) { let keys = []; if (typeof object === 'object') { for (let key in object) { if ( typeof object[key] === 'object' && !Array.isArray(object[key]) ) { let subKeys = this.getNestedKeys(object[key]); subKeys = subKeys.map((x) => `${key}.${x}`); keys = [...keys, ...subKeys]; } else { keys.push(key); } } } return keys; } /** * Converts time interval shorthand like 5w, -3d, etc to timestamps. It also ensures any timestamp * passed in is properly formatted for API calls. * * @param {string} time The command lint input string for the datetime * @returns {string} The full RFC3339-formatted datetime string in UTC */ static normalizeDateString(time) { // Attempt to parse date as timestamp or string let newDate = /^\d+$/u.test(time) ? dateTime.parse(Number.parseInt(time, 10) * 1000) : dateTime.parse(time); if (!dateTime.isValid(newDate)) { let parsedOffset = time.match(/^(-?)((?:\d+[smhdwMy])+)$/u); if (parsedOffset) { let sign = parsedOffset[1] === '-' ? -1 : 1, offset = parsedOffset[2]; // Transform a string like "-1d2h3m" into an array of arg arrays, e.g.: // [ [-1, "d"], [-2, "h"], [-3, "m"] ] let argPairs = _.chunk(offset.split(/(\d+)/u).slice(1), 2).map( (pair) => [sign * Number.parseInt(pair[0], 10), pair[1]] ); // Successively apply the offsets to the current time newDate = new Date(); for (const args of argPairs) { newDate = offsetDate(newDate, ...args); } } else if (time === 'now') { newDate = new Date(); } else { throw new BoxCLIError(`Cannot parse date format "${time}"`); } } // Format the timezone to RFC3339 format for the Box API // Also always use UTC timezone for consistency in tests return newDate.toISOString().replace(/\.\d{3}Z$/u, '+00:00'); } /** * Writes updated settings to disk * * @param {Object} updatedSettings The settings object to write * @returns {void} */ updateSettings(updatedSettings) { this.settings = Object.assign(this.settings, updatedSettings); try { fs.writeFileSync( SETTINGS_FILE_PATH, JSON.stringify(this.settings, null, 4), 'utf8' ); } catch (error) { throw new BoxCLIError( `Could not write settings file ${SETTINGS_FILE_PATH}`, error ); } return this.settings; } /** * Read the current set of environments from disk * * @returns {Object} The parsed environment information */ async getEnvironments() { if (this.supportsSecureStorage) { DEBUG.init( 'Attempting secure storage read via %s service="%s" account="%s"', secureStorage.backend, ENVIRONMENTS_KEYCHAIN_SERVICE, ENVIRONMENTS_KEYCHAIN_ACCOUNT ); try { const password = await secureStorage.getPassword( ENVIRONMENTS_KEYCHAIN_SERVICE, ENVIRONMENTS_KEYCHAIN_ACCOUNT ); if (password) { DEBUG.init( 'Successfully loaded environments from secure storage (%s)', secureStorage.backend ); return JSON.parse(password); } DEBUG.init( 'Secure storage returned empty result for service="%s" account="%s"', ENVIRONMENTS_KEYCHAIN_SERVICE, ENVIRONMENTS_KEYCHAIN_ACCOUNT ); } catch (error) { DEBUG.init( 'Failed to read from secure storage (%s), falling back to file: %O', secureStorage.backend, getDebugErrorDetails(error) ); } } else { DEBUG.init( 'Skipping secure storage read: platform=%s available=%s', process.platform, secureStorage.available ); } // Try to read from file (fallback or no secure storage) try { if (fs.existsSync(ENVIRONMENTS_FILE_PATH)) { DEBUG.init( 'Attempting environments fallback file read at %s', ENVIRONMENTS_FILE_PATH ); return JSON.parse(fs.readFileSync(ENVIRONMENTS_FILE_PATH)); } DEBUG.init( 'Environments fallback file does not exist at %s', ENVIRONMENTS_FILE_PATH ); } catch (error) { DEBUG.init( 'Failed to read environments from file: %O', getDebugErrorDetails(error) ); } // No environments found in either location throw new BoxCLIError( `Could not read environments. No environments found in secure storage or file ${ENVIRONMENTS_FILE_PATH}` ); } /** * Writes updated environment information to disk * * @param {Object} updatedEnvironments The environment information to write * @param {Object} environments use to override current environment * @returns {void} */ async updateEnvironments(updatedEnvironments, environments) { if (environments === undefined) { environments = await this.getEnvironments(); } Object.assign(environments, updatedEnvironments); let storedInSecureStorage = false; if (this.supportsSecureStorage) { DEBUG.init( 'Attempting secure storage write via %s service="%s" account="%s"', secureStorage.backend, ENVIRONMENTS_KEYCHAIN_SERVICE, ENVIRONMENTS_KEYCHAIN_ACCOUNT ); try { await secureStorage.setPassword( ENVIRONMENTS_KEYCHAIN_SERVICE, ENVIRONMENTS_KEYCHAIN_ACCOUNT, JSON.stringify(environments) ); storedInSecureStorage = true; DEBUG.init( 'Stored environment configuration in secure storage (%s)', secureStorage.backend ); if (fs.existsSync(ENVIRONMENTS_FILE_PATH)) { fs.unlinkSync(ENVIRONMENTS_FILE_PATH); DEBUG.init( 'Removed environment configuration file after migrating to secure storage' ); } } catch (error) { DEBUG.init( 'Could not store credentials in secure storage (%s), falling back to file: %O', secureStorage.backend, getDebugErrorDetails(error) ); } } else { DEBUG.init( 'Skipping secure storage write: platform=%s available=%s', process.platform, secureStorage.available ); } // Write to file if secure storage failed or not available if (!storedInSecureStorage) { try { let fileContents = JSON.stringify(environments, null, 4); fs.writeFileSync(ENVIRONMENTS_FILE_PATH, fileContents, 'utf8'); if ( process.platform === 'linux' && this.supportsSecureStorage ) { this.info( 'Could not store credentials in secure storage, falling back to file.' + ' To enable secure storage on Linux, install libsecret-1-dev package.' ); } } catch (error) { throw new BoxCLIError( `Could not write environments config file ${ENVIRONMENTS_FILE_PATH}`, error ); } } return environments; } /** * Initialize the CLI by creating the necessary configuration files on disk * in the users' home directory, then read and parse the CLI settings file. * * @returns {Object} The parsed settings * @private */ async _loadSettings() { try { if (!fs.existsSync(CONFIG_FOLDER_PATH)) { mkdirp.sync(CONFIG_FOLDER_PATH); DEBUG.init('Created config folder at %s', CONFIG_FOLDER_PATH); } // Check if environments exist (in secure storage or file) let environmentsExist = false; try { const environments = await this.getEnvironments(); // Check if there are any environments configured if ( environments && environments.environments && Object.keys(environments.environments).length > 0 ) { environmentsExist = true; DEBUG.init('Found existing environments in storage'); } } catch (error) { // No environments found, need to create defaults DEBUG.init('No existing environments found: %s', error.message); } if (!environmentsExist) { // Create default environments (will be stored in secure storage if available) await this.updateEnvironments( {}, this._getDefaultEnvironments() ); DEBUG.init('Created default environments configuration'); } if (!fs.existsSync(SETTINGS_FILE_PATH)) { let settingsJSON = JSON.stringify( this._getDefaultSettings(), null, 4 ); fs.writeFileSync(SETTINGS_FILE_PATH, settingsJSON, 'utf8'); DEBUG.init( 'Created settings file at %s %O', SETTINGS_FILE_PATH, settingsJSON ); } } catch (error) { throw new BoxCLIError( 'Could not initialize CLI home directory', error ); } let settings; try { settings = JSON.parse(fs.readFileSync(SETTINGS_FILE_PATH)); settings = Object.assign(this._getDefaultSettings(), settings); DEBUG.init('Loaded settings %O', settings); } catch (error) { throw new BoxCLIError( `Could not read CLI settings file at ${SETTINGS_FILE_PATH}`, error ); } try { if (!fs.existsSync(settings.boxReportsFolderPath)) { mkdirp.sync(settings.boxReportsFolderPath); DEBUG.init( 'Created reports folder at %s', settings.boxReportsFolderPath ); } if (!fs.existsSync(settings.boxDownloadsFolderPath)) { mkdirp.sync(settings.boxDownloadsFolderPath); DEBUG.init( 'Created downloads folder at %s', settings.boxDownloadsFolderPath ); } } catch (error) { throw new BoxCLIError( 'Failed creating CLI working directory', error ); } return settings; } /** * Get the default settings object * * @returns {Object} The default settings object * @private */ _getDefaultSettings() { return { boxReportsFolderPath: path.join( os.homedir(), 'Documents/Box-Reports' ), boxReportsFileFormat: 'txt', boxDownloadsFolderPath: path.join( os.homedir(), 'Downloads/Box-Downloads' ), outputJson: false, enableProxy: false, proxy: { url: null, username: null, password: null, }, enableAnalyticsClient: false, analyticsClient: { name: null, }, }; } /** * Get the default environments object * * @returns {Object} The default environments object * @private */ _getDefaultEnvironments() { return { default: null, environments: {}, }; } } BoxCommand.flags = { token: Flags.string({ char: 't', description: 'Provide a token to perform this call', }), 'as-user': Flags.string({ description: 'Provide an ID for a user' }), // @NOTE: This flag is not read anywhere directly; the chalk library automatically turns off color when it's passed 'no-color': Flags.boolean({ description: 'Turn off colors for logging', }), json: Flags.boolean({ description: 'Output formatted JSON', exclusive: ['csv'], }), csv: Flags.boolean({ description: 'Output formatted CSV', exclusive: ['json'], }), save: Flags.boolean({ char: 's', description: 'Save report to default reports folder on disk', exclusive: ['save-to-file-path'], }), 'save-to-file-path': Flags.string({ description: 'Override default file path to save report', exclusive: ['save'], parse: utils.parsePath, }), fields: Flags.string({ description: 'Comma separated list of fields to show', }), 'bulk-file-path': Flags.string({ description: 'File path to bulk .csv or .json objects', parse: utils.parsePath, }), help: Flags.help({ char: 'h', description: 'Show CLI help', }), verbose: Flags.boolean({ char: 'v', description: 'Show verbose output, which can be helpful for debugging', }), yes: Flags.boolean({ char: 'y', description: 'Automatically respond yes to all confirmation prompts', }), quiet: Flags.boolean({ char: 'q', description: 'Suppress any non-error output to stderr', }), }; BoxCommand.rawJsonFlags = Object.freeze({ 'raw-json': Flags.boolean({ description: 'Output the raw API JSON response instead of the tsClient-normalized object fields. Added as a non-breaking compatibility flag for users who need JSON field names to match the API schema exactly. Implies --json.', exclusive: ['csv'], }), }); BoxCommand.minFlags = _.pick(BoxCommand.flags, [ 'no-color', 'help', 'verbose', 'quiet', ]); module.exports = BoxCommand;