[ACS-5987] improved security for shell scripts (#8889)

* improved security for node process functions

* improved security for node process functions

* remove unused file from demo shell

* restore regex

* fix regex

* update escaping

* lint fixes

* fix typo

* fix export

* fix exports

* fix lint

* fix lint
This commit is contained in:
Denys Vuika
2023-09-27 10:52:33 +01:00
committed by GitHub
parent 6d8c513180
commit 8f684a9f6a
20 changed files with 233 additions and 311 deletions

View File

@@ -44,6 +44,7 @@
"docx", "docx",
"dropdownrestprocess", "dropdownrestprocess",
"Droppable", "Droppable",
"dryrun",
"ECMBPM", "ECMBPM",
"ECMHOST", "ECMHOST",
"Examinate", "Examinate",
@@ -125,6 +126,7 @@
"typeahed", "typeahed",
"uncheck", "uncheck",
"Unclaim", "Unclaim",
"Undeployed",
"unfavorite", "unfavorite",
"unlisten", "unlisten",
"unshare", "unshare",
@@ -139,8 +141,7 @@
"webscript", "webscript",
"Whitespaces", "Whitespaces",
"xdescribe", "xdescribe",
"xsrf", "xsrf"
"Undeployed"
], ],
"dictionaries": [ "dictionaries": [
"html", "html",

View File

@@ -1,77 +0,0 @@
var port = process.env.PORT || 3000,
http = require('http'),
fs = require('fs'),
url = require('url'),
mime = require('mime'),
html = fs.readFileSync('index.html');
var log = function(entry) {
fs.appendFileSync('/tmp/sample-app.log', new Date().toISOString() + ' - ' + entry + '\n');
};
var server = http.createServer(function (req, res) {
// Parse the request containing file name
var pathname = url.parse(req.url).pathname;
// Print the name of the file for which request is made.
console.log("Request for " + pathname + " received.");
if (req.method === 'POST') {
var body = '';
req.on('data', function(chunk) {
body += chunk;
});
req.on('end', function() {
if (req.url === '/') {
log('Received message: ' + body);
} else if (req.url === '/scheduled') {
log('Received task ' + req.headers['x-aws-sqsd-taskname'] + ' scheduled at ' + req.headers['x-aws-sqsd-scheduled-at']);
}
res.writeHead(200, 'OK', {'Content-Type': 'text/plain'});
res.end();
});
} else {
var filename = pathname.substr(1);
if(filename === '' || filename.indexOf('.') === -1){
filename = 'index.html';
}
// Read the requested file content from file system
fs.readFile(filename, function (err, data) {
if (err) {
console.log(err, filename);
// HTTP Status: 404 : NOT FOUND
// Content Type: text/plain
res.writeHead(404, {'Content-Type': 'text/html'});
}else{
//Page found
// HTTP Status: 200 : OK
// Content Type: text/plain
var type = mime.lookup(filename);
console.log('type',type);
if (!res.getHeader('content-type')) {
var charset = mime.charsets.lookup(type);
res.setHeader('Content-Type', type + (charset ? '; charset=' + charset : ''));
}
if(type.indexOf('image') > -1 || type.indexOf('font') > -1){
var img = fs.readFileSync(pathname.substr(1));
res.end(img, 'binary');
}else{
res.write(data.toString());
}
// Write the content of the file to response body
}
// Send the response body
res.end();
});
}
});
// Listen on port 3000, IP defaults to 127.0.0.1
server.listen(port);
// Put a friendly message on the terminal
console.log('Server running at http://127.0.0.1:' + port + '/');

View File

@@ -1,44 +1,45 @@
#!/usr/bin/env node #!/usr/bin/env node
const minimist = require('minimist'); const minimist = require('minimist');
const path = require('path'); const { resolve, join } = require('node:path');
const fs = require('fs'); const { readFileSync, existsSync } = require('node:fs');
const { argv, exit, env, cwd } = require('node:process');
function printHelp() { function printHelp() {
const pkgData = fs.readFileSync(path.resolve(__dirname, '..', 'package.json')); const pkgData = readFileSync(resolve(__dirname, '..', 'package.json')).toString();
const { name, version } = JSON.parse(pkgData); const { name, version } = JSON.parse(pkgData);
console.log(`${name} v${version}`); console.log(`${name} v${version}`);
} }
const args = minimist(process.argv.slice(2), { const args = minimist(argv.slice(2), {
boolean: ['verbose'] boolean: ['verbose']
}); });
if (args._.length === 0) { if (args._.length === 0) {
printHelp(); printHelp();
process.exit(1); exit(1);
} }
const scriptName = args._.shift(); const scriptName = args._.shift();
const scriptPath = process.env.DEVELOP const scriptPath = env.DEVELOP
? path.resolve(path.join(__dirname, '../dist/scripts', scriptName)) ? resolve(join(__dirname, '../dist/scripts', scriptName))
: path.resolve(path.join(__dirname, '../scripts', scriptName)); : resolve(join(__dirname, '../scripts', scriptName));
if (!fs.existsSync(`${scriptPath}.js`)) { if (!existsSync(`${scriptPath}.js`)) {
console.error(`Error: command ${scriptName} not found.`); console.error(`Error: command ${scriptName} not found.`);
process.exit(1); exit(1);
} }
const cwd = process.cwd(); const workingDir = cwd();
try { try {
Promise.resolve() Promise.resolve()
.then(() => require(scriptPath).default(args, cwd)) .then(() => require(scriptPath).default(args, workingDir))
.then(exitCode => process.exit(exitCode || 0)) .then(exitCode => exit(exitCode || 0))
.catch(err => { .catch(err => {
console.error(err && err.stack); console.error(err && err.stack);
process.exit(99); exit(99);
}); });
} catch (err) { } catch (err) {
console.error(err.stack); console.error(err.stack);
process.exit(99); exit(99);
} }

View File

@@ -17,6 +17,7 @@
* limitations under the License. * limitations under the License.
*/ */
import { argv, exit } from 'node:process';
import { exec } from './exec'; import { exec } from './exec';
import { logger } from './logger'; import { logger } from './logger';
import program from 'commander'; import program from 'commander';
@@ -38,25 +39,20 @@ function zipArtifact(output: string) {
logger.info(response); logger.info(response);
} }
export default function() { export default function main() {
main();
}
function main() {
program program
.version('0.1.0') .version('0.1.0')
.requiredOption('-a, --artifact [type]', ' path to the s3 artifact (tar.bz2) to download and extract') .requiredOption('-a, --artifact [type]', ' path to the s3 artifact (tar.bz2) to download and extract')
.requiredOption('-o, --output [type]', 'directory to extract the archive to') .requiredOption('-o, --output [type]', 'directory to extract the archive to')
.parse(process.argv); .parse(argv);
if (process.argv.includes('-h') || process.argv.includes('--help')) { if (argv.includes('-h') || argv.includes('--help')) {
program.outputHelp(); program.outputHelp();
return; return;
} }
if (!program.artifact || program.artifact === '' || !program.output || program.output === '') { if (!program.artifact || program.artifact === '' || !program.output || program.output === '') {
process.exit(1); exit(1);
} else if (program.artifact !== '' || program.output !== '') { } else if (program.artifact !== '' || program.output !== '') {
zipArtifact(program.artifact); zipArtifact(program.artifact);
awsCp(program.output); awsCp(program.output);

View File

@@ -17,6 +17,7 @@
* limitations under the License. * limitations under the License.
*/ */
import { argv, exit } from 'node:process';
import { exec } from './exec'; import { exec } from './exec';
import { logger } from './logger'; import { logger } from './logger';
import program from 'commander'; import program from 'commander';
@@ -24,7 +25,7 @@ import program from 'commander';
function zipArtifact(artifact: string) { function zipArtifact(artifact: string) {
logger.info(`Perform zip artifact ${artifact}`); logger.info(`Perform zip artifact ${artifact}`);
const response = exec(`tar cvfj ./s3-artifact.tmp -C ${program.artifact} ls ${program.artifact}`, [] , {}); const response = exec(`tar cvfj ./s3-artifact.tmp -C ${program.artifact} ls ${program.artifact}`, [], {});
logger.info(response); logger.info(response);
} }
@@ -34,25 +35,21 @@ function awsCp(output: string) {
logger.info(response); logger.info(response);
} }
export default function() {
main();
}
function main() {
export default function main() {
program program
.version('0.1.0') .version('0.1.0')
.option('-a, --artifact [type]', ' path to the artifact to archieve (tar.bz2) and upload (like ./dist)') .option('-a, --artifact [type]', ' path to the artifact to archieve (tar.bz2) and upload (like ./dist)')
.option('-o, --output [type]', ' the S3 object to copy it to, like: s3://bucket-name/folder/whatever.tar.bz2') .option('-o, --output [type]', ' the S3 object to copy it to, like: s3://bucket-name/folder/whatever.tar.bz2')
.parse(process.argv); .parse(argv);
if (process.argv.includes('-h') || process.argv.includes('--help')) { if (argv.includes('-h') || argv.includes('--help')) {
program.outputHelp(); program.outputHelp();
return; return;
} }
if (!program.artifact || program.artifact === '' || !program.output || program.output === '') { if (!program.artifact || program.artifact === '' || !program.output || program.output === '') {
process.exit(1); exit(1);
} else if (program.artifact !== '' || program.output !== '') { } else if (program.artifact !== '' || program.output !== '') {
zipArtifact(program.artifact); zipArtifact(program.artifact);
awsCp(program.output); awsCp(program.output);

View File

@@ -21,6 +21,7 @@ import * as shell from 'shelljs';
import * as ejs from 'ejs'; import * as ejs from 'ejs';
import * as path from 'path'; import * as path from 'path';
import * as fs from 'fs'; import * as fs from 'fs';
import { argv, exit } from 'node:process';
import program from 'commander'; import program from 'commander';
export default function main(_args: string[], workingDir: string) { export default function main(_args: string[], workingDir: string) {
@@ -29,9 +30,9 @@ export default function main(_args: string[], workingDir: string) {
.usage('audit [options]') .usage('audit [options]')
.option('-p, --package <path>', 'Path to package file (default: package.json in working directory)') .option('-p, --package <path>', 'Path to package file (default: package.json in working directory)')
.option('-d, --outDir <dir>', 'Ouput directory (default: working directory)') .option('-d, --outDir <dir>', 'Ouput directory (default: working directory)')
.parse(process.argv); .parse(argv);
if (process.argv.includes('-h') || process.argv.includes('--help')) { if (argv.includes('-h') || argv.includes('--help')) {
program.outputHelp(); program.outputHelp();
return; return;
} }
@@ -44,13 +45,13 @@ export default function main(_args: string[], workingDir: string) {
if (!fs.existsSync(packagePath)) { if (!fs.existsSync(packagePath)) {
console.error('The package.json file was not found'); console.error('The package.json file was not found');
process.exit(1); exit(1);
} }
const templatePath = path.resolve(__dirname, '../templates/auditPage.ejs'); const templatePath = path.resolve(__dirname, '../templates/auditPage.ejs');
if (!fs.existsSync(templatePath)) { if (!fs.existsSync(templatePath)) {
console.error(`Cannot find the report template: ${templatePath}`); console.error(`Cannot find the report template: ${templatePath}`);
process.exit(1); exit(1);
} }
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@@ -61,24 +62,29 @@ export default function main(_args: string[], workingDir: string) {
const cmd = 'npm audit --json --prod'; const cmd = 'npm audit --json --prod';
const jsonAudit = JSON.parse(shell.exec(cmd, { silent: true })); const jsonAudit = JSON.parse(shell.exec(cmd, { silent: true }));
ejs.renderFile(templatePath, { ejs.renderFile(
jsonAudit, templatePath,
projVersion: packageJson.version, {
projName: packageJson.name jsonAudit,
}, {}, (err: any, mdText: string) => { projVersion: packageJson.version,
if (err) { projName: packageJson.name
console.error(err); },
reject(1); {},
} else { (err: any, mdText: string) => {
const outputPath = path.resolve(program.outDir || workingDir); if (err) {
const outputFile = path.join(outputPath, `audit-info-${packageJson.version}.md`); console.error(err);
reject(err);
} else {
const outputPath = path.resolve(program.outDir || workingDir);
const outputFile = path.join(outputPath, `audit-info-${packageJson.version}.md`);
fs.writeFileSync(outputFile, mdText); fs.writeFileSync(outputFile, mdText);
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
console.log(`Report saved as ${outputFile}`); console.log(`Report saved as ${outputFile}`);
resolve(0); resolve(0);
}
} }
}); );
}); });
} }

View File

@@ -19,6 +19,7 @@
/* eslint-disable @typescript-eslint/naming-convention */ /* eslint-disable @typescript-eslint/naming-convention */
import { argv, exit } from 'node:process';
import * as shell from 'shelljs'; import * as shell from 'shelljs';
import * as path from 'path'; import * as path from 'path';
import program from 'commander'; import program from 'commander';
@@ -78,14 +79,13 @@ function getRemote(workingDir: string): string {
function getCommits(options: DiffOptions): Array<Commit> { function getCommits(options: DiffOptions): Array<Commit> {
let authorFilter = (options.exclude || '') let authorFilter = (options.exclude || '')
.split(',') .split(',')
.map(str => str.trim().replace(/\\/g, '')) .map((str) => str.trim().replace(/\\/g, ''))
.join('|'); .join('|');
if (!authorFilter) { if (!authorFilter) {
authorFilter = `bot|Alfresco Build User`; authorFilter = `bot|Alfresco Build User`;
} }
const args = [ const args = [
`git`, `git`,
`log`, `log`,
@@ -114,7 +114,10 @@ function getCommits(options: DiffOptions): Array<Commit> {
log = log.substring(0, log.length - 1); log = log.substring(0, log.length - 1);
} }
return log.split('\\n').map(str => JSON.parse(str) as Commit).filter(commit => commitAuthorAllowed(commit, authorFilter)); return log
.split('\\n')
.map((str: string) => JSON.parse(str) as Commit)
.filter((commit: Commit) => commitAuthorAllowed(commit, authorFilter));
} }
function commitAuthorAllowed(commit: Commit, authorFilter: string): boolean { function commitAuthorAllowed(commit: Commit, authorFilter: string): boolean {
@@ -134,9 +137,9 @@ export default function main(_args: string[], workingDir: string) {
.option('--skip <number>', 'Skip number commits before starting to show the commit output') .option('--skip <number>', 'Skip number commits before starting to show the commit output')
.option('-f, --format <format>', 'Output format (md, html)', 'md') .option('-f, --format <format>', 'Output format (md, html)', 'md')
.option('-e --exclude <string>', 'Exclude authors from the output, comma-delimited list') .option('-e --exclude <string>', 'Exclude authors from the output, comma-delimited list')
.parse(process.argv); .parse(argv);
if (process.argv.includes('-h') || process.argv.includes('--help')) { if (argv.includes('-h') || argv.includes('--help')) {
program.outputHelp(); program.outputHelp();
return; return;
} }
@@ -162,40 +165,45 @@ export default function main(_args: string[], workingDir: string) {
const packagePath = path.resolve(dir, 'package.json'); const packagePath = path.resolve(dir, 'package.json');
if (!fs.existsSync(packagePath)) { if (!fs.existsSync(packagePath)) {
console.error('The package.json file was not found'); console.error('The package.json file was not found');
process.exit(1); exit(1);
} }
const templatePath = path.resolve(__dirname, `../templates/changelog-${format}.ejs`); const templatePath = path.resolve(__dirname, `../templates/changelog-${format}.ejs`);
if (!fs.existsSync(templatePath)) { if (!fs.existsSync(templatePath)) {
console.error(`Cannot find the report template: ${templatePath}`); console.error(`Cannot find the report template: ${templatePath}`);
process.exit(1); exit(1);
} }
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const packageJson = JSON.parse(fs.readFileSync(packagePath).toString()); const packageJson = JSON.parse(fs.readFileSync(packagePath).toString());
ejs.renderFile(templatePath, { ejs.renderFile(
remote, templatePath,
repo_url, {
commits, remote,
projVersion: packageJson.version, repo_url,
projName: packageJson.name commits,
}, {}, (err: any, text: string) => { projVersion: packageJson.version,
if (err) { projName: packageJson.name
console.error(err); },
reject(1); {},
} else { (err: any, text: string) => {
if (output) { if (err) {
const outputDir = path.resolve(output); console.error(err);
const outputFile = path.join(outputDir, `changelog-${packageJson.version}.${format}`); reject(err);
console.log('Writing changelog to', outputFile);
fs.writeFileSync(outputFile, text);
} else { } else {
console.log(text); if (output) {
const outputDir = path.resolve(output);
const outputFile = path.join(outputDir, `changelog-${packageJson.version}.${format}`);
console.log('Writing changelog to', outputFile);
fs.writeFileSync(outputFile, text);
} else {
console.log(text);
}
resolve(0);
} }
resolve(0);
} }
}); );
}); });
} }

View File

@@ -25,7 +25,7 @@ const TIMEOUT = 20000;
let counter = 0; let counter = 0;
let alfrescoJsApi: AlfrescoApi; let alfrescoJsApi: AlfrescoApi;
export default async function main(_args: string[]) { export default async function main() {
program program
.version('0.1.0') .version('0.1.0')
.description('Check Content service is up ') .description('Check Content service is up ')

View File

@@ -15,6 +15,7 @@
* limitations under the License. * limitations under the License.
*/ */
import { argv } from 'node:process';
import { PluginTarget } from './plugins/plugin-model'; import { PluginTarget } from './plugins/plugin-model';
import { CheckEnv } from './plugins/check-env'; import { CheckEnv } from './plugins/check-env';
import program = require('commander'); import program = require('commander');
@@ -22,7 +23,7 @@ import { ProcessServiceCheckPlugin } from './plugins/process-service-check-plugi
import { ProcessAutomationCheckPlugin } from './plugins/process-automation-check-plugin'; import { ProcessAutomationCheckPlugin } from './plugins/process-automation-check-plugin';
import { GovernanceCheckPlugin } from './plugins/governance-check-plugin'; import { GovernanceCheckPlugin } from './plugins/governance-check-plugin';
let pluginEnv; let pluginEnv: CheckEnv;
export default async function main(_args: string[]) { export default async function main(_args: string[]) {
program program
@@ -34,7 +35,7 @@ export default async function main(_args: string[]) {
.option('-p, --password [type]', 'password ') .option('-p, --password [type]', 'password ')
.option('-u, --username [type]', 'username ') .option('-u, --username [type]', 'username ')
.option('--ui, --uiName [type]', 'uiName', 'Deployed app UI type on activiti-cloud') .option('--ui, --uiName [type]', 'uiName', 'Deployed app UI type on activiti-cloud')
.parse(process.argv); .parse(argv);
pluginEnv = new CheckEnv(program.host, program.username, program.password, program.clientId); pluginEnv = new CheckEnv(program.host, program.username, program.password, program.clientId);
await pluginEnv.checkEnv(); await pluginEnv.checkEnv();

View File

@@ -23,7 +23,7 @@ const MAX_RETRY = 10;
const TIMEOUT = 60000; const TIMEOUT = 60000;
let counter = 0; let counter = 0;
export default async function main(_args: string[]) { export default async function main() {
program program
.version('0.1.0') .version('0.1.0')
.description('Check Process service is up ') .description('Check Process service is up ')

View File

@@ -17,6 +17,7 @@
* limitations under the License. * limitations under the License.
*/ */
import { argv, exit } from 'node:process';
import { exec } from './exec'; import { exec } from './exec';
import program from 'commander'; import program from 'commander';
import { logger } from './logger'; import { logger } from './logger';
@@ -42,6 +43,7 @@ export interface PublishArgs {
dockerTags?: string; dockerTags?: string;
pathProject: string; pathProject: string;
fileName: string; fileName: string;
sourceTag?: string;
} }
function loginPerform(args: PublishArgs) { function loginPerform(args: PublishArgs) {
@@ -97,15 +99,13 @@ function cleanImagePerform(args: PublishArgs, tag: string) {
logger.info(response); logger.info(response);
} }
export default function(args: PublishArgs) { export default function main(args: PublishArgs) {
main(args);
}
function main(args) {
program program
.version('0.1.0') .version('0.1.0')
.description('Move in the folder where you have your Dockerfile and run the command:\n\n' + .description(
'adf-cli docker-publish --dockerRepo "${docker_repository}" --dockerTags "${TAGS}"') 'Move in the folder where you have your Dockerfile and run the command:\n\n' +
'adf-cli docker-publish --dockerRepo "${docker_repository}" --dockerTags "${TAGS}"'
)
.option('--loginRepo [type]', 'URL registry') .option('--loginRepo [type]', 'URL registry')
.option('--loginPassword [type]', ' password') .option('--loginPassword [type]', ' password')
.option('--loginUsername [type]', ' username') .option('--loginUsername [type]', ' username')
@@ -119,26 +119,26 @@ function main(args) {
.option('--target [type]', 'target: publish or link', TARGETS.publish) .option('--target [type]', 'target: publish or link', TARGETS.publish)
.requiredOption('--dockerRepo [type]', 'docker repo') .requiredOption('--dockerRepo [type]', 'docker repo')
.requiredOption('--dockerTags [type]', ' tags') .requiredOption('--dockerTags [type]', ' tags')
.parse(process.argv); .parse(argv);
if (process.argv.includes('-h') || process.argv.includes('--help')) { if (argv.includes('-h') || argv.includes('--help')) {
program.outputHelp(); program.outputHelp();
return; return;
} }
if (!Object.values(TARGETS).includes(program.opts().target)) { if (!Object.values(TARGETS).includes(program.opts().target)) {
logger.error(`error: invalid --target value. It can be ${Object.values(TARGETS)}`); logger.error(`error: invalid --target value. It can be ${Object.values(TARGETS)}`);
process.exit(1); exit(1);
} }
if (program.opts().target === TARGETS.publish && args.buildArgs === undefined) { if (program.opts().target === TARGETS.publish && args.buildArgs === undefined) {
logger.error(`error: required option --buildArgs [type] in case the target is ${TARGETS.publish}`); logger.error(`error: required option --buildArgs [type] in case the target is ${TARGETS.publish}`);
process.exit(1); exit(1);
} }
if (program.opts().target === TARGETS.link && args.sourceTag === undefined) { if (program.opts().target === TARGETS.link && args.sourceTag === undefined) {
logger.error(`error: required option --sourceTag [type] in case the target is ${TARGETS.link}`); logger.error(`error: required option --sourceTag [type] in case the target is ${TARGETS.link}`);
process.exit(1); exit(1);
} }
if (args.pathProject === undefined) { if (args.pathProject === undefined) {
@@ -153,7 +153,7 @@ function main(args) {
loginPerform(args); loginPerform(args);
} }
let mainTag; let mainTag: string;
if (args.dockerTags !== '') { if (args.dockerTags !== '') {
args.dockerTags.split(',').forEach((tag, index) => { args.dockerTags.split(',').forEach((tag, index) => {
if (tag) { if (tag) {

View File

@@ -199,7 +199,7 @@ async function getApplicationsByName(args: ConfigArgs, apiService: AlfrescoApi,
return apps ? apps.list.entries : []; return apps ? apps.list.entries : [];
} catch (error) { } catch (error) {
logger.error(`Not possible to get the applications with name ${name} ` + JSON.stringify(error)); logger.error(`Not possible to get the applications with name ${name} ` + JSON.stringify(error));
process.exit(1); exit(1);
} }
} }

View File

@@ -17,14 +17,10 @@
* limitations under the License. * limitations under the License.
*/ */
import { argv } from 'node:process';
import program from 'commander'; import program from 'commander';
import * as kube from './kube-utils'; import * as kube from './kube-utils';
// eslint-disable-next-line prefer-arrow/prefer-arrow-functions
export default function(args: kube.KubeArgs) {
main(args);
}
const main = (args: kube.KubeArgs) => { const main = (args: kube.KubeArgs) => {
program program
.version('0.1.0') .version('0.1.0')
@@ -34,9 +30,9 @@ const main = (args: kube.KubeArgs) => {
.option('--clusterEnv [type]', 'cluster Env') .option('--clusterEnv [type]', 'cluster Env')
.option('--clusterUrl [type]', 'cluster Url') .option('--clusterUrl [type]', 'cluster Url')
.option('--label [type]', 'label cluster') .option('--label [type]', 'label cluster')
.parse(process.argv); .parse(argv);
if (process.argv.includes('-h') || process.argv.includes('--help')) { if (argv.includes('-h') || argv.includes('--help')) {
program.outputHelp(); program.outputHelp();
return; return;
} }
@@ -49,3 +45,5 @@ const main = (args: kube.KubeArgs) => {
kube.deletePod(args); kube.deletePod(args);
} }
}; };
export default main;

View File

@@ -17,6 +17,7 @@
* limitations under the License. * limitations under the License.
*/ */
import { argv } from 'node:process';
import { exec } from './exec'; import { exec } from './exec';
import program from 'commander'; import program from 'commander';
import { logger } from './logger'; import { logger } from './logger';
@@ -29,16 +30,14 @@ const installPerform = () => {
exec('curl', [`LO`, `${k8sRelease}`], {}); exec('curl', [`LO`, `${k8sRelease}`], {});
}; };
// eslint-disable-next-line prefer-arrow/prefer-arrow-functions
export default function(args: kube.KubeArgs) {
main(args);
}
const main = (args: kube.KubeArgs) => { const main = (args: kube.KubeArgs) => {
program program
.version('0.1.0') .version('0.1.0')
.description('his command allows you to update a specific service on the rancher env with a specific tag \n\n' + .description(
'adf-cli kubectl-image --clusterEnv ${clusterEnv} --clusterUrl ${clusterUrl} --username ${username} --token ${token} --label ${label} --namespaces ${namespaces} --dockerRepo ${dockerRepo} --tag ${tag}') 'This command allows you to update a specific service on the rancher env with a specific tag \n\n' +
'adf-cli kubectl-image --clusterEnv ${clusterEnv} --clusterUrl ${clusterUrl} --username ${username} --token ${token} --label ${label} --namespaces ${namespaces} --dockerRepo ${dockerRepo} --tag ${tag}'
)
.option('--tag [type]', 'tag') .option('--tag [type]', 'tag')
.option('--installCheck [type]', 'install kube ctl') .option('--installCheck [type]', 'install kube ctl')
.option('--username [type]', 'username') .option('--username [type]', 'username')
@@ -47,9 +46,9 @@ const main = (args: kube.KubeArgs) => {
.option('--dockerRepo [type]', 'docker Repo') .option('--dockerRepo [type]', 'docker Repo')
.option('--label [type]', 'pod label') .option('--label [type]', 'pod label')
.option('--namespaces [type]', 'list of namespaces') .option('--namespaces [type]', 'list of namespaces')
.parse(process.argv); .parse(argv);
if (process.argv.includes('-h') || process.argv.includes('--help')) { if (argv.includes('-h') || argv.includes('--help')) {
program.outputHelp(); program.outputHelp();
return; return;
} }
@@ -64,7 +63,7 @@ const main = (args: kube.KubeArgs) => {
kube.setContext(args.clusterEnv, args.username); kube.setContext(args.clusterEnv, args.username);
kube.useContext(args.clusterEnv); kube.useContext(args.clusterEnv);
let namespaces: string []; let namespaces: string[];
if (args.namespaces === null || args.namespaces === 'default') { if (args.namespaces === null || args.namespaces === 'default') {
logger.info(`No namespaces provided. Fetch all of them`); logger.info(`No namespaces provided. Fetch all of them`);
namespaces = kube.getNamespaces(); namespaces = kube.getNamespaces();
@@ -84,3 +83,5 @@ const main = (args: kube.KubeArgs) => {
}); });
} }
}; };
export default main;

View File

@@ -17,6 +17,7 @@
* limitations under the License. * limitations under the License.
*/ */
import { argv, exit } from 'node:process';
import * as path from 'path'; import * as path from 'path';
import * as fs from 'fs'; import * as fs from 'fs';
import * as checker from 'license-checker'; import * as checker from 'license-checker';
@@ -73,7 +74,7 @@ function getPackageFile(packagePath: string): PackageInfo {
return JSON.parse(fs.readFileSync(packagePath).toString()); return JSON.parse(fs.readFileSync(packagePath).toString());
} catch { } catch {
console.error('Error parsing package.json file'); console.error('Error parsing package.json file');
process.exit(1); exit(1);
} }
} }
@@ -83,9 +84,9 @@ export default function main(_args: string[], workingDir: string) {
.usage('licenses [options]') .usage('licenses [options]')
.option('-p, --package <path>', 'Path to package file (default: package.json in working directory)') .option('-p, --package <path>', 'Path to package file (default: package.json in working directory)')
.option('-d, --outDir <dir>', 'Ouput directory (default: working directory)') .option('-d, --outDir <dir>', 'Ouput directory (default: working directory)')
.parse(process.argv); .parse(argv);
if (process.argv.includes('-h') || process.argv.includes('--help')) { if (argv.includes('-h') || argv.includes('--help')) {
program.outputHelp(); program.outputHelp();
return; return;
} }
@@ -98,74 +99,83 @@ export default function main(_args: string[], workingDir: string) {
if (!fs.existsSync(packagePath)) { if (!fs.existsSync(packagePath)) {
console.error('The package.json file was not found'); console.error('The package.json file was not found');
process.exit(1); exit(1);
} }
const templatePath = path.resolve(__dirname, '../templates/licensePage.ejs'); const templatePath = path.resolve(__dirname, '../templates/licensePage.ejs');
if (!fs.existsSync(templatePath)) { if (!fs.existsSync(templatePath)) {
console.error(`Cannot find the report template: ${templatePath}`); console.error(`Cannot find the report template: ${templatePath}`);
process.exit(1); exit(1);
} }
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
console.info(`Checking ${packagePath}`); console.info(`Checking ${packagePath}`);
checker.init({ checker.init(
start: workingDir, {
production: true, start: workingDir,
failOn: 'GPL' production: true,
}, function(err: any, packages: any[]) { failOn: 'GPL'
if (err) { },
console.error(err); (err: any, packages: any[]) => {
reject(err); if (err) {
} else { console.error(err);
// eslint-disable-next-line guard-for-in reject(err);
for (const packageName in packages) { } else {
const pack = packages[packageName]; // eslint-disable-next-line guard-for-in
pack['licenseExp'] = pack['licenses'].toString() for (const packageName in packages) {
.replace(/\*/, '') const pack = packages[packageName];
.replace(/[a-zA-Z0-9\-.]+/g, (match: string) => { pack['licenseExp'] = pack['licenses']
const lowerMatch = match.toLowerCase(); .toString()
.replace(/\*/g, '')
.replace(/[a-zA-Z0-9\-.]+/g, (match: string) => {
const lowerMatch = match.toLowerCase();
if ((lowerMatch !== 'and') && (lowerMatch !== 'or') && (lowerMatch !== 'with')) { if (lowerMatch !== 'and' && lowerMatch !== 'or' && lowerMatch !== 'with') {
return licenseWithMDLinks(match); return licenseWithMDLinks(match);
} else { } else {
return match; return match;
}
});
if (!pack['repository']) {
const lastAtSignPos = packageName.lastIndexOf('@');
const mainName = packageName.substring(0, lastAtSignPos);
if (missingRepositories[mainName]) {
pack['repository'] = missingRepositories[mainName];
} }
});
if (!pack['repository']) {
const lastAtSignPos = packageName.lastIndexOf('@');
const mainName = packageName.substring(0, lastAtSignPos);
if (missingRepositories[mainName]) {
pack['repository'] = missingRepositories[mainName];
} }
} }
const packageJson: PackageInfo = getPackageFile(packagePath);
ejs.renderFile(
templatePath,
{
packages,
projVersion: packageJson.version,
projName: packageJson.name
},
{},
(ejsError: any, mdText: string) => {
if (ejsError) {
console.error(ejsError);
reject(ejsError);
} else {
const outputPath = path.resolve(program.outDir || workingDir);
const outputFile = path.join(outputPath, `license-info-${packageJson.version}.md`);
fs.writeFileSync(outputFile, mdText);
// eslint-disable-next-line no-console
console.log(`Report saved as ${outputFile}`);
resolve(0);
}
}
);
} }
const packageJson: PackageInfo = getPackageFile(packagePath);
ejs.renderFile(templatePath, {
packages,
projVersion: packageJson.version,
projName: packageJson.name
}, {}, (ejsError: any, mdText: string) => {
if (ejsError) {
console.error(ejsError);
reject(ejsError);
} else {
const outputPath = path.resolve(program.outDir || workingDir);
const outputFile = path.join(outputPath, `license-info-${packageJson.version}.md`);
fs.writeFileSync(outputFile, mdText);
// eslint-disable-next-line no-console
console.log(`Report saved as ${outputFile}`);
resolve(0);
}
});
} }
}); );
}); });
} }

View File

@@ -15,6 +15,8 @@
* limitations under the License. * limitations under the License.
*/ */
import { exit } from 'node:process';
/* eslint-disable */ /* eslint-disable */
let log = null; let log = null;
@@ -23,9 +25,9 @@ log = {
info: console.log.bind(console), info: console.log.bind(console),
warn: console.warn.bind(console), warn: console.warn.bind(console),
error: console.error.bind(console), error: console.error.bind(console),
fatal: x => { fatal: (err) => {
console.error(x); console.error(err);
process.exit(100); exit(100);
}, },
createChild: () => log createChild: () => log
}; };

View File

@@ -17,6 +17,7 @@
* limitations under the License. * limitations under the License.
*/ */
import { argv } from 'node:process';
import * as path from 'path'; import * as path from 'path';
import fs = require('fs'); import fs = require('fs');
import { exec } from './exec'; import { exec } from './exec';
@@ -31,16 +32,7 @@ export interface PublishArgs {
dryrun?: boolean; dryrun?: boolean;
} }
const projects = [ const projects = ['cli', 'core', 'insights', 'testing', 'content-services', 'process-services', 'process-services-cloud', 'extensions'];
'cli',
'core',
'insights',
'testing',
'content-services',
'process-services',
'process-services-cloud',
'extensions'
];
async function npmPublish(args: PublishArgs, project: string) { async function npmPublish(args: PublishArgs, project: string) {
if (args.dryrun) { if (args.dryrun) {
@@ -75,7 +67,6 @@ async function npmPublish(args: PublishArgs, project: string) {
await sleep(30000); await sleep(30000);
} else { } else {
logger.info(`@alfresco/adf-${project}@${version} already exist`); logger.info(`@alfresco/adf-${project}@${version} already exist`);
} }
} }
@@ -94,8 +85,7 @@ function npmCheckExist(project: string, version: string) {
function changeRegistry(args: PublishArgs, project: string) { function changeRegistry(args: PublishArgs, project: string) {
logger.info(`Change registry... to ${args.npmRegistry} `); logger.info(`Change registry... to ${args.npmRegistry} `);
const folder = `${args.pathProject}/dist/libs/${project}`; const folder = `${args.pathProject}/dist/libs/${project}`;
const content = const content = `strict-ssl=true
`strict-ssl=true
always-auth=true always-auth=true
@alfresco:registry=https://${args.npmRegistry} @alfresco:registry=https://${args.npmRegistry}
//${args.npmRegistry}/:_authToken="${args.tokenRegistry}"`; //${args.npmRegistry}/:_authToken="${args.tokenRegistry}"`;
@@ -118,23 +108,20 @@ function removeNpmConfig(args: PublishArgs, project: string) {
} }
} }
export default async function(args: PublishArgs) { export default async function main(args: PublishArgs) {
await main(args);
}
async function main(args) {
program program
.version('0.1.0') .version('0.1.0')
.description('Move in the folder where you have your Dockerfile and run the command \n\n adf-cli docker-publish --dockerRepo "${docker_repository}" --dockerTags "${TAGS}" --pathProject "$(pwd)') .description(
'Move in the folder where you have your Dockerfile and run the command \n\n adf-cli docker-publish --dockerRepo "${docker_repository}" --dockerTags "${TAGS}" --pathProject "$(pwd)'
)
.option('--tag [type]', 'tag') .option('--tag [type]', 'tag')
.option('--npmRegistry [type]', 'npm Registry') .option('--npmRegistry [type]', 'npm Registry')
.option('--tokenRegistry [type]', 'token Registry') .option('--tokenRegistry [type]', 'token Registry')
.option('--pathProject [type]', 'pathProject') .option('--pathProject [type]', 'pathProject')
.option('--dryrun [type]', 'dryrun') .option('--dryrun [type]', 'dryrun')
.parse(process.argv); .parse(argv);
if (process.argv.includes('-h') || process.argv.includes('--help')) { if (argv.includes('-h') || argv.includes('--help')) {
program.outputHelp(); program.outputHelp();
return; return;
} }
@@ -147,5 +134,5 @@ async function main(args) {
async function sleep(ms: number) { async function sleep(ms: number) {
logger.info(`Waiting for ${ms} milliseconds...`); logger.info(`Waiting for ${ms} milliseconds...`);
return new Promise(resolve => setTimeout(resolve, ms)); return new Promise((resolve) => setTimeout(resolve, ms));
} }

View File

@@ -17,6 +17,7 @@
/* eslint-disable @typescript-eslint/naming-convention */ /* eslint-disable @typescript-eslint/naming-convention */
import { exit } from 'node:process';
import { PluginInterface } from './plugin-model'; import { PluginInterface } from './plugin-model';
import { logger } from '../logger'; import { logger } from '../logger';
import { ProcessServiceHealth } from './process-services-health'; import { ProcessServiceHealth } from './process-services-health';
@@ -50,13 +51,13 @@ export class ProcessServiceCheckPlugin {
} }
]; ];
console.table(pluginStatus); console.table(pluginStatus);
process.exit(1); exit(1);
} }
} catch (e) { } catch (e) {
this.logConfigurationError(e); this.logConfigurationError(e);
pluginStatus = [{ PluginName: this.plugInInfo.name, Status: 'Inactive', BE: 'DOWN', FE: 'Disabled' }]; pluginStatus = [{ PluginName: this.plugInInfo.name, Status: 'Inactive', BE: 'DOWN', FE: 'Disabled' }];
console.table(pluginStatus); console.table(pluginStatus);
process.exit(1); exit(1);
} }
} }

View File

@@ -17,6 +17,7 @@
* limitations under the License. * limitations under the License.
*/ */
import { argv } from 'node:process';
import { exec } from './exec'; import { exec } from './exec';
import program from 'commander'; import program from 'commander';
import { logger } from './logger'; import { logger } from './logger';
@@ -48,24 +49,21 @@ function replacePerform(args: CommitArgs, sha: string) {
} }
} }
export default function(args: CommitArgs) { export default function main(args: CommitArgs) {
main(args);
}
function main(args) {
program program
.version('0.1.0') .version('0.1.0')
.description('This command allows you to update the commit sha as part of the package.json.\n' + .description(
'Your package.json must to have an existing property called "commit.\n\n' + 'This command allows you to update the commit sha as part of the package.json.\n' +
'adf-cli update-commit-sha --pointer "HEAD~1" --pathProject "$(pwd)"\n\n' + 'Your package.json must to have an existing property called "commit.\n\n' +
'adf-cli update-commit-sha --pathProject "$(pwd)" --skipGnu') 'adf-cli update-commit-sha --pointer "HEAD~1" --pathProject "$(pwd)"\n\n' +
'adf-cli update-commit-sha --pathProject "$(pwd)" --skipGnu'
)
.option('--pointer [type]', 'pointer') .option('--pointer [type]', 'pointer')
.option('--pathPackage [type]', 'pathPackage') .option('--pathPackage [type]', 'pathPackage')
.option('--skipGnu [type]', 'skipGnu') .option('--skipGnu [type]', 'skipGnu')
.parse(process.argv); .parse(argv);
if (process.argv.includes('-h') || process.argv.includes('--help')) { if (argv.includes('-h') || argv.includes('--help')) {
program.outputHelp(); program.outputHelp();
return; return;
} }

View File

@@ -17,6 +17,7 @@
* limitations under the License. * limitations under the License.
*/ */
import { argv } from 'node:process';
import program from 'commander'; import program from 'commander';
import * as path from 'path'; import * as path from 'path';
import * as fs from 'fs'; import * as fs from 'fs';
@@ -46,8 +47,8 @@ function parseAlfrescoLibs(workingDir: string): PackageInfo {
const json = require(packagePath); const json = require(packagePath);
const isAlfrescoLib = (key: string) => key.startsWith('@alfresco'); const isAlfrescoLib = (key: string) => key.startsWith('@alfresco');
dependencies = Object.keys((json.dependencies || [])).filter(isAlfrescoLib); dependencies = Object.keys(json.dependencies || []).filter(isAlfrescoLib);
devDependencies = Object.keys((json.devDependencies || [])).filter(isAlfrescoLib); devDependencies = Object.keys(json.devDependencies || []).filter(isAlfrescoLib);
} }
return { return {
@@ -57,10 +58,7 @@ function parseAlfrescoLibs(workingDir: string): PackageInfo {
} }
function formatNpmCommand(deps: string[], tag: string): string { function formatNpmCommand(deps: string[], tag: string): string {
return [ return ['npm i -E', deps.map((name) => `${name}@${tag}`).join(' ')].join(' ');
'npm i -E',
deps.map(name => `${name}@${tag}`).join(' ')
].join(' ');
} }
function runNpmCommand(command: string, workingDir: string) { function runNpmCommand(command: string, workingDir: string) {
@@ -72,23 +70,17 @@ function runNpmCommand(command: string, workingDir: string) {
function updateLibs(pkg: PackageInfo, tag: string, workingDir: string) { function updateLibs(pkg: PackageInfo, tag: string, workingDir: string) {
if (pkg.dependencies && pkg.dependencies.length > 0) { if (pkg.dependencies && pkg.dependencies.length > 0) {
runNpmCommand( runNpmCommand(formatNpmCommand(pkg.dependencies, tag), workingDir);
formatNpmCommand(pkg.dependencies, tag),
workingDir
);
} }
if (pkg.devDependencies && pkg.devDependencies.length > 0) { if (pkg.devDependencies && pkg.devDependencies.length > 0) {
runNpmCommand( runNpmCommand(formatNpmCommand(pkg.devDependencies, tag) + ' -D', workingDir);
formatNpmCommand(pkg.devDependencies, tag) + ' -D',
workingDir
);
} }
} }
function parseTag(args: UpdateArgs): string { function parseTag(args: UpdateArgs): string {
if (args.alpha) { if (args.alpha) {
return 'alpha'; return 'alpha';
} }
if (args.beta) { if (args.beta) {
@@ -100,17 +92,19 @@ function parseTag(args: UpdateArgs): string {
export default function main(args: UpdateArgs, workingDir: string) { export default function main(args: UpdateArgs, workingDir: string) {
program program
.description('This command allows you to update the adf dependencies and js-api with different versions\n\n' + .description(
'Update adf libs and js-api with latest alpha\n\n' + 'This command allows you to update the adf dependencies and js-api with different versions\n\n' +
'adf-cli update-version --alpha') 'Update adf libs and js-api with latest alpha\n\n' +
'adf-cli update-version --alpha'
)
.option('--pathPackage [dir]', 'Directory that contains package.json file', 'current directory') .option('--pathPackage [dir]', 'Directory that contains package.json file', 'current directory')
.option('--alpha', 'use alpha') .option('--alpha', 'use alpha')
.option('--beta', 'use beta') .option('--beta', 'use beta')
.option('--version [tag]', 'use specific version can be also alpha/beta/latest', 'latest') .option('--version [tag]', 'use specific version can be also alpha/beta/latest', 'latest')
.option('--vjs [tag]', 'Upgrade only JS-API to a specific version') .option('--vjs [tag]', 'Upgrade only JS-API to a specific version')
.parse(process.argv); .parse(argv);
if (process.argv.includes('-h') || process.argv.includes('--help')) { if (argv.includes('-h') || argv.includes('--help')) {
program.outputHelp(); program.outputHelp();
return; return;
} }
@@ -118,9 +112,7 @@ export default function main(args: UpdateArgs, workingDir: string) {
workingDir = args.pathPackage || workingDir; workingDir = args.pathPackage || workingDir;
const tag = args.vjs || parseTag(args); const tag = args.vjs || parseTag(args);
const pkg = args.vjs const pkg = args.vjs ? { dependencies: ['@alfresco/js-api'] } : parseAlfrescoLibs(workingDir);
? { dependencies: ['@alfresco/js-api'] }
: parseAlfrescoLibs(workingDir);
updateLibs(pkg, tag, workingDir); updateLibs(pkg, tag, workingDir);
} }