donbot-cli 1.0.10 → 1.0.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +45 -1
- package/cli/deploy.js +12 -25
- package/cli/validate/config.js +77 -0
- package/cli/validate/eslint.js +129 -0
- package/cli/validate/index.js +78 -0
- package/cli/validate/trivy.js +128 -0
- package/donbot.js +26 -15
- package/package.json +5 -1
package/README.md
CHANGED
|
@@ -7,4 +7,48 @@ Donbot CLI es una herramienta de línea de comandos para la gestión de catálog
|
|
|
7
7
|
Para instalar Donbot CLI globalmente:
|
|
8
8
|
|
|
9
9
|
```bash
|
|
10
|
-
npm install -g donbot-cli
|
|
10
|
+
npm install -g donbot-cli```
|
|
11
|
+
|
|
12
|
+
## Validación de código (`donbot validcode` / `vc`)
|
|
13
|
+
|
|
14
|
+
Las rutinas viven en el CLI (`cli/validate/`), así que no dependen de la versión de donbot
|
|
15
|
+
ni de su `npm run lint`: el resultado es el mismo en donbot 1.x y 2.x.
|
|
16
|
+
|
|
17
|
+
| Rutina | Qué revisa | Requisito |
|
|
18
|
+
|--------|------------|-----------|
|
|
19
|
+
| `eslint` | ESLint integrado: `recommended` + reglas de calidad + `eslint-plugin-security`. Detecta solas las globales de runtime (`global.X = ...`). | ninguno |
|
|
20
|
+
| `trivy` | `trivy fs`: vulnerabilidades en dependencias (package-lock), secretos y misconfiguraciones (Dockerfile, compose, etc.). | `brew install trivy`, o docker (usa `aquasec/trivy`) |
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
donbot vc # todas las rutinas
|
|
24
|
+
donbot vc --only eslint # solo una
|
|
25
|
+
donbot vc --skip trivy # omitir alguna
|
|
26
|
+
donbot vc --fix # autocorrige lo que ESLint pueda
|
|
27
|
+
donbot vc --report reporte.json # reporte JSON (útil en CI)
|
|
28
|
+
donbot dp main --skipcheck trivy # deploy omitiendo una rutina
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Sale con código 1 si hay errores de ESLint o hallazgos de Trivy en severidades `failOn`.
|
|
32
|
+
`deploy` corre las mismas rutinas antes de subir (`--novalidcode` para saltarlas).
|
|
33
|
+
|
|
34
|
+
### Configuración opcional por proyecto: `.conf/validate-donbot-cli.json`
|
|
35
|
+
|
|
36
|
+
Se hace merge sobre los valores por defecto (ver `cli/validate/config.js`):
|
|
37
|
+
|
|
38
|
+
```json
|
|
39
|
+
{
|
|
40
|
+
"eslint": {
|
|
41
|
+
"useProjectConfig": false,
|
|
42
|
+
"maxWarnings": -1,
|
|
43
|
+
"globals": { "MiGlobal": "readonly" },
|
|
44
|
+
"rules": { "no-var": "error" }
|
|
45
|
+
},
|
|
46
|
+
"trivy": {
|
|
47
|
+
"required": true,
|
|
48
|
+
"failOn": ["CRITICAL"],
|
|
49
|
+
"severity": ["HIGH", "CRITICAL"]
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Para ignorar CVEs puntuales de Trivy usa un `.trivyignore` en la raíz del proyecto.
|
package/cli/deploy.js
CHANGED
|
@@ -2,6 +2,7 @@ const path = require("path");
|
|
|
2
2
|
const { exec, execSync } = require("child_process");
|
|
3
3
|
const readline = require('readline');
|
|
4
4
|
const fs = require('fs');
|
|
5
|
+
const { runValidations } = require('./validate');
|
|
5
6
|
let config;
|
|
6
7
|
|
|
7
8
|
function getGitBranch() {
|
|
@@ -13,17 +14,6 @@ function getGitBranch() {
|
|
|
13
14
|
});
|
|
14
15
|
}
|
|
15
16
|
|
|
16
|
-
function validCode() {
|
|
17
|
-
return new Promise((resolve, reject) => {
|
|
18
|
-
try {
|
|
19
|
-
const output = execSync('npm run lint');
|
|
20
|
-
resolve(output.toString().trim());
|
|
21
|
-
} catch (error) {
|
|
22
|
-
reject(error);
|
|
23
|
-
}
|
|
24
|
-
});
|
|
25
|
-
}
|
|
26
|
-
|
|
27
17
|
const uploadCodeToServer = async (uploadCodeToServer, options) => {
|
|
28
18
|
|
|
29
19
|
console.log(`
|
|
@@ -39,15 +29,13 @@ const uploadCodeToServer = async (uploadCodeToServer, options) => {
|
|
|
39
29
|
`);
|
|
40
30
|
|
|
41
31
|
if (!options.novalidcode) {
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
console.log("
|
|
46
|
-
} catch (err) {
|
|
47
|
-
console.log("❌ El código no es válido.");
|
|
48
|
-
console.error(err.stdout?.toString() || err.message);
|
|
32
|
+
console.log("Validando código...");
|
|
33
|
+
const { ok } = await runValidations({ skip: options.skipcheck });
|
|
34
|
+
if (!ok) {
|
|
35
|
+
console.log("❌ El código no es válido. Deploy cancelado.");
|
|
49
36
|
process.exit(1);
|
|
50
37
|
}
|
|
38
|
+
console.log("✅ Código válido.");
|
|
51
39
|
}
|
|
52
40
|
|
|
53
41
|
let host, user, path_cert, password, port, path_dest, sourceDir, container_name;
|
|
@@ -111,7 +99,7 @@ const uploadCodeToServer = async (uploadCodeToServer, options) => {
|
|
|
111
99
|
});
|
|
112
100
|
};
|
|
113
101
|
|
|
114
|
-
const validCode_donbot = async (
|
|
102
|
+
const validCode_donbot = async (options = {}) => {
|
|
115
103
|
console.log(`
|
|
116
104
|
_____ _______ __ _ ______ _______ _______
|
|
117
105
|
| | | || | | || _ | | || |
|
|
@@ -125,14 +113,13 @@ const validCode_donbot = async (uploadCodeToServer, options) => {
|
|
|
125
113
|
`);
|
|
126
114
|
|
|
127
115
|
try {
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
116
|
+
const { ok } = await runValidations(options);
|
|
117
|
+
console.log(ok ? "\n✅ Código válido." : "\n❌ El código no es válido.");
|
|
118
|
+
process.exit(ok ? 0 : 1);
|
|
131
119
|
} catch (err) {
|
|
132
|
-
console.
|
|
133
|
-
console.error(err.stdout?.toString() || err.message);
|
|
120
|
+
console.error(`❌ ${err.message}`);
|
|
134
121
|
process.exit(1);
|
|
135
122
|
}
|
|
136
123
|
};
|
|
137
124
|
|
|
138
|
-
module.exports = { uploadCodeToServer, validCode_donbot };
|
|
125
|
+
module.exports = { uploadCodeToServer, validCode_donbot };
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const fs = require('fs');
|
|
3
|
+
const path = require('path');
|
|
4
|
+
|
|
5
|
+
// Configuración por defecto de las rutinas de validación.
|
|
6
|
+
// Vive en el CLI para que el resultado no dependa de la versión de donbot
|
|
7
|
+
// sobre la que se ejecuta. Cada proyecto puede ajustarla con
|
|
8
|
+
// ./.conf/validate-donbot-cli.json (se hace merge profundo sobre estos valores).
|
|
9
|
+
const DEFAULTS = {
|
|
10
|
+
eslint: {
|
|
11
|
+
enabled: true,
|
|
12
|
+
// Si es true usa el eslint.config.* del proyecto (con el ESLint del CLI).
|
|
13
|
+
useProjectConfig: false,
|
|
14
|
+
// Número máximo de warnings permitidos (-1 = sin límite).
|
|
15
|
+
maxWarnings: -1,
|
|
16
|
+
// Reglas de seguridad (eslint-plugin-security).
|
|
17
|
+
security: true,
|
|
18
|
+
ignores: [
|
|
19
|
+
'**/node_modules/**',
|
|
20
|
+
'**/tmp/**',
|
|
21
|
+
'**/dist/**',
|
|
22
|
+
'**/build/**',
|
|
23
|
+
'**/coverage/**',
|
|
24
|
+
'**/*.min.js',
|
|
25
|
+
'**/admin-web/**',
|
|
26
|
+
'**/landing/**',
|
|
27
|
+
'**/old_example/**',
|
|
28
|
+
],
|
|
29
|
+
// Globales extra (las de tipo global.X = ... se detectan solas).
|
|
30
|
+
globals: {},
|
|
31
|
+
// Reglas extra/override, formato ESLint flat config.
|
|
32
|
+
rules: {},
|
|
33
|
+
},
|
|
34
|
+
trivy: {
|
|
35
|
+
enabled: true,
|
|
36
|
+
// Si es true y no hay trivy (ni docker) la validación falla.
|
|
37
|
+
required: false,
|
|
38
|
+
scanners: ['vuln', 'secret', 'misconfig'],
|
|
39
|
+
// Severidades que se reportan.
|
|
40
|
+
severity: ['MEDIUM', 'HIGH', 'CRITICAL'],
|
|
41
|
+
// Severidades que hacen fallar la validación.
|
|
42
|
+
failOn: ['HIGH', 'CRITICAL'],
|
|
43
|
+
ignoreUnfixed: true,
|
|
44
|
+
skipDirs: ['node_modules', 'tmp', '.git'],
|
|
45
|
+
skipFiles: ['.env', '.env.development', '.env.staging', '.env.production', '.env.local'],
|
|
46
|
+
timeout: '10m',
|
|
47
|
+
// Imagen usada si trivy no está instalado pero docker sí.
|
|
48
|
+
dockerImage: 'aquasec/trivy:0.58.2',
|
|
49
|
+
},
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const CONFIG_FILE = path.join('.conf', 'validate-donbot-cli.json');
|
|
53
|
+
|
|
54
|
+
function isObject(v) {
|
|
55
|
+
return v && typeof v === 'object' && !Array.isArray(v);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function deepMerge(base, override) {
|
|
59
|
+
const out = { ...base };
|
|
60
|
+
for (const [k, v] of Object.entries(override || {})) {
|
|
61
|
+
out[k] = isObject(v) && isObject(base[k]) ? deepMerge(base[k], v) : v;
|
|
62
|
+
}
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function loadConfig(cwd = process.cwd()) {
|
|
67
|
+
const file = path.join(cwd, CONFIG_FILE);
|
|
68
|
+
if (!fs.existsSync(file)) return { config: DEFAULTS, source: null };
|
|
69
|
+
try {
|
|
70
|
+
const user = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
71
|
+
return { config: deepMerge(DEFAULTS, user), source: CONFIG_FILE };
|
|
72
|
+
} catch (err) {
|
|
73
|
+
throw new Error(`No se pudo leer ${CONFIG_FILE}: ${err.message}`);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
module.exports = { DEFAULTS, CONFIG_FILE, loadConfig };
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const fs = require('fs');
|
|
3
|
+
const path = require('path');
|
|
4
|
+
const { ESLint } = require('eslint');
|
|
5
|
+
const js = require('@eslint/js');
|
|
6
|
+
const globals = require('globals');
|
|
7
|
+
|
|
8
|
+
const SKIP_DIRS = new Set(['node_modules', '.git', 'tmp', 'dist', 'build', 'coverage', 'admin-web', 'landing']);
|
|
9
|
+
const GLOBAL_ASSIGN = /\b(?:global|globalThis)\.([A-Za-z_$][\w$]*)\s*=(?!=)/g;
|
|
10
|
+
|
|
11
|
+
// donbot registra servicios como globales en runtime (global.DonBotLoger = ...).
|
|
12
|
+
// Se detectan en el código para no depender de cómo cada versión los declara.
|
|
13
|
+
function detectRuntimeGlobals(dir, found = {}) {
|
|
14
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
15
|
+
if (entry.isDirectory()) {
|
|
16
|
+
if (!SKIP_DIRS.has(entry.name) && !entry.name.startsWith('.')) {
|
|
17
|
+
detectRuntimeGlobals(path.join(dir, entry.name), found);
|
|
18
|
+
}
|
|
19
|
+
} else if (/\.(c|m)?js$/.test(entry.name)) {
|
|
20
|
+
const src = fs.readFileSync(path.join(dir, entry.name), 'utf8');
|
|
21
|
+
for (const m of src.matchAll(GLOBAL_ASSIGN)) found[m[1]] = 'writable';
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
return found;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Config integrada en el CLI: misma base que usan los proyectos donbot
|
|
28
|
+
// (recommended + commonjs + globals node/browser) más reglas de calidad y
|
|
29
|
+
// seguridad. No depende de nada instalado en el proyecto.
|
|
30
|
+
function buildConfig(cfg, runtimeGlobals = {}) {
|
|
31
|
+
const config = [
|
|
32
|
+
{ ignores: cfg.ignores },
|
|
33
|
+
js.configs.recommended,
|
|
34
|
+
{
|
|
35
|
+
files: ['**/*.js', '**/*.cjs'],
|
|
36
|
+
languageOptions: { sourceType: 'commonjs', ecmaVersion: 'latest' },
|
|
37
|
+
},
|
|
38
|
+
{
|
|
39
|
+
files: ['**/*.mjs'],
|
|
40
|
+
languageOptions: { sourceType: 'module', ecmaVersion: 'latest' },
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
languageOptions: {
|
|
44
|
+
globals: { ...globals.node, ...globals.browser, ...runtimeGlobals, ...(cfg.globals || {}) },
|
|
45
|
+
},
|
|
46
|
+
linterOptions: { reportUnusedDisableDirectives: 'warn' },
|
|
47
|
+
rules: {
|
|
48
|
+
'no-unused-vars': ['warn', { args: 'none', caughtErrors: 'none', ignoreRestSiblings: true }],
|
|
49
|
+
'no-eval': 'error',
|
|
50
|
+
'no-implied-eval': 'error',
|
|
51
|
+
'no-new-func': 'error',
|
|
52
|
+
'no-script-url': 'error',
|
|
53
|
+
'no-proto': 'error',
|
|
54
|
+
'no-extend-native': 'error',
|
|
55
|
+
'no-return-await': 'off',
|
|
56
|
+
'no-unsafe-optional-chaining': 'error',
|
|
57
|
+
'no-promise-executor-return': 'warn',
|
|
58
|
+
'require-atomic-updates': 'off',
|
|
59
|
+
'no-self-compare': 'error',
|
|
60
|
+
'no-template-curly-in-string': 'warn',
|
|
61
|
+
'no-unreachable-loop': 'error',
|
|
62
|
+
'no-constant-binary-expression': 'error',
|
|
63
|
+
'eqeqeq': ['warn', 'smart'],
|
|
64
|
+
'no-var': 'warn',
|
|
65
|
+
// Un require local de algo que también es global en runtime es válido.
|
|
66
|
+
'no-redeclare': ['error', { builtinGlobals: false }],
|
|
67
|
+
},
|
|
68
|
+
},
|
|
69
|
+
];
|
|
70
|
+
|
|
71
|
+
if (cfg.security) {
|
|
72
|
+
const security = require('eslint-plugin-security');
|
|
73
|
+
config.push(security.configs.recommended);
|
|
74
|
+
// El plugin genera mucho ruido con estas reglas en código de servidor.
|
|
75
|
+
config.push({
|
|
76
|
+
rules: {
|
|
77
|
+
'security/detect-object-injection': 'off',
|
|
78
|
+
'security/detect-non-literal-fs-filename': 'off',
|
|
79
|
+
'security/detect-eval-with-expression': 'error',
|
|
80
|
+
'security/detect-child-process': 'warn',
|
|
81
|
+
'security/detect-unsafe-regex': 'warn',
|
|
82
|
+
'security/detect-pseudoRandomBytes': 'error',
|
|
83
|
+
'security/detect-buffer-noassert': 'error',
|
|
84
|
+
'security/detect-new-buffer': 'error',
|
|
85
|
+
'security/detect-disable-mustache-escape': 'error',
|
|
86
|
+
'security/detect-bidi-characters': 'error',
|
|
87
|
+
},
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
if (cfg.rules && Object.keys(cfg.rules).length) config.push({ rules: cfg.rules });
|
|
92
|
+
return config;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async function run(cfg, { cwd = process.cwd(), fix = false } = {}) {
|
|
96
|
+
const options = { cwd, fix, errorOnUnmatchedPattern: false };
|
|
97
|
+
|
|
98
|
+
if (cfg.useProjectConfig) {
|
|
99
|
+
options.overrideConfig = [{ ignores: cfg.ignores }];
|
|
100
|
+
} else {
|
|
101
|
+
// Ignora eslint.config.* del proyecto: plugins y reglas salen del CLI.
|
|
102
|
+
options.overrideConfigFile = true;
|
|
103
|
+
options.overrideConfig = buildConfig(cfg, detectRuntimeGlobals(cwd));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const eslint = new ESLint(options);
|
|
107
|
+
const results = await eslint.lintFiles(['.']);
|
|
108
|
+
if (fix) await ESLint.outputFixes(results);
|
|
109
|
+
|
|
110
|
+
const formatter = await eslint.loadFormatter('stylish');
|
|
111
|
+
const output = formatter.format(results);
|
|
112
|
+
|
|
113
|
+
const errors = results.reduce((n, r) => n + r.errorCount + r.fatalErrorCount, 0);
|
|
114
|
+
const warnings = results.reduce((n, r) => n + r.warningCount, 0);
|
|
115
|
+
const tooManyWarnings = cfg.maxWarnings >= 0 && warnings > cfg.maxWarnings;
|
|
116
|
+
|
|
117
|
+
return {
|
|
118
|
+
name: 'eslint',
|
|
119
|
+
ok: errors === 0 && !tooManyWarnings,
|
|
120
|
+
summary: `${results.length} archivos, ${errors} errores, ${warnings} warnings` +
|
|
121
|
+
(tooManyWarnings ? ` (máximo permitido: ${cfg.maxWarnings})` : ''),
|
|
122
|
+
output: output.trim(),
|
|
123
|
+
data: results
|
|
124
|
+
.filter((r) => r.messages.length)
|
|
125
|
+
.map((r) => ({ file: path.relative(cwd, r.filePath), messages: r.messages })),
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
module.exports = { run, buildConfig };
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const fs = require('fs');
|
|
3
|
+
const { loadConfig } = require('./config');
|
|
4
|
+
|
|
5
|
+
// Rutinas disponibles. Para agregar una nueva: exportar run(cfg, ctx) que
|
|
6
|
+
// devuelva { name, ok, summary, output, skipped?, data? } y registrarla aquí.
|
|
7
|
+
const CHECKS = {
|
|
8
|
+
eslint: require('./eslint'),
|
|
9
|
+
trivy: require('./trivy'),
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
function parseList(v) {
|
|
13
|
+
return v ? String(v).split(',').map((s) => s.trim()).filter(Boolean) : null;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function selectChecks(config, options) {
|
|
17
|
+
const only = parseList(options.only);
|
|
18
|
+
const skip = parseList(options.skip) || [];
|
|
19
|
+
for (const n of [...(only || []), ...skip]) {
|
|
20
|
+
if (!CHECKS[n]) throw new Error(`Rutina desconocida: "${n}". Disponibles: ${Object.keys(CHECKS).join(', ')}`);
|
|
21
|
+
}
|
|
22
|
+
return Object.keys(CHECKS).filter((n) => {
|
|
23
|
+
if (only) return only.includes(n);
|
|
24
|
+
return config[n]?.enabled !== false && !skip.includes(n);
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Ejecuta las rutinas de validación sobre el proyecto en cwd.
|
|
30
|
+
* @returns {Promise<{ok: boolean, results: object[]}>}
|
|
31
|
+
*/
|
|
32
|
+
async function runValidations(options = {}) {
|
|
33
|
+
const cwd = options.cwd || process.cwd();
|
|
34
|
+
const { config, source } = loadConfig(cwd);
|
|
35
|
+
const names = selectChecks(config, options);
|
|
36
|
+
|
|
37
|
+
console.log(source ? `Config: ${source}` : 'Config: valores por defecto del CLI');
|
|
38
|
+
|
|
39
|
+
const results = [];
|
|
40
|
+
for (const name of names) {
|
|
41
|
+
process.stdout.write(`\n▶ ${name}...\n`);
|
|
42
|
+
const started = Date.now();
|
|
43
|
+
let result;
|
|
44
|
+
try {
|
|
45
|
+
result = await CHECKS[name].run(config[name], { cwd, fix: !!options.fix });
|
|
46
|
+
} catch (err) {
|
|
47
|
+
result = { name, ok: false, summary: `Error interno: ${err.message}`, output: err.stack || '' };
|
|
48
|
+
}
|
|
49
|
+
result.ms = Date.now() - started;
|
|
50
|
+
results.push(result);
|
|
51
|
+
|
|
52
|
+
const icon = result.skipped ? '⚠️ ' : result.ok ? '✅' : '❌';
|
|
53
|
+
if (result.output) console.log(result.output);
|
|
54
|
+
console.log(`${icon} ${name}: ${result.summary} (${(result.ms / 1000).toFixed(1)}s)`);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const ok = results.every((r) => r.ok);
|
|
58
|
+
|
|
59
|
+
console.log('\n──────── Resumen ────────');
|
|
60
|
+
for (const r of results) {
|
|
61
|
+
console.log(`${r.skipped ? '⚠️ ' : r.ok ? '✅' : '❌'} ${r.name.padEnd(8)} ${r.summary}`);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
if (options.report) {
|
|
65
|
+
const report = {
|
|
66
|
+
date: new Date().toISOString(),
|
|
67
|
+
cwd,
|
|
68
|
+
ok,
|
|
69
|
+
results: results.map(({ output, ...r }) => r),
|
|
70
|
+
};
|
|
71
|
+
fs.writeFileSync(options.report, JSON.stringify(report, null, 2));
|
|
72
|
+
console.log(`\nReporte JSON: ${options.report}`);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
return { ok, results };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
module.exports = { runValidations, CHECKS };
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const { spawnSync } = require('child_process');
|
|
3
|
+
|
|
4
|
+
const SEVERITY_ORDER = ['UNKNOWN', 'LOW', 'MEDIUM', 'HIGH', 'CRITICAL'];
|
|
5
|
+
|
|
6
|
+
function has(cmd, args = ['--version']) {
|
|
7
|
+
const r = spawnSync(cmd, args, { stdio: 'ignore' });
|
|
8
|
+
return r.status === 0;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// Devuelve cómo ejecutar trivy: binario local o contenedor docker.
|
|
12
|
+
function resolveRunner(cfg, cwd) {
|
|
13
|
+
if (has('trivy')) return { cmd: 'trivy', prefix: [], target: '.', via: 'trivy local' };
|
|
14
|
+
if (has('docker', ['info'])) {
|
|
15
|
+
return {
|
|
16
|
+
cmd: 'docker',
|
|
17
|
+
prefix: [
|
|
18
|
+
'run', '--rm',
|
|
19
|
+
'-v', `${cwd}:/src:ro`,
|
|
20
|
+
'-v', 'donbot-cli-trivy-cache:/root/.cache/trivy',
|
|
21
|
+
cfg.dockerImage,
|
|
22
|
+
],
|
|
23
|
+
target: '/src',
|
|
24
|
+
via: `docker (${cfg.dockerImage})`,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function buildArgs(cfg, target) {
|
|
31
|
+
const args = [
|
|
32
|
+
'fs',
|
|
33
|
+
'--quiet',
|
|
34
|
+
'--format', 'json',
|
|
35
|
+
'--exit-code', '0',
|
|
36
|
+
'--scanners', cfg.scanners.join(','),
|
|
37
|
+
'--severity', cfg.severity.join(','),
|
|
38
|
+
'--timeout', cfg.timeout,
|
|
39
|
+
];
|
|
40
|
+
if (cfg.ignoreUnfixed) args.push('--ignore-unfixed');
|
|
41
|
+
for (const d of cfg.skipDirs || []) args.push('--skip-dirs', d);
|
|
42
|
+
for (const f of cfg.skipFiles || []) args.push('--skip-files', f);
|
|
43
|
+
args.push(target);
|
|
44
|
+
return args;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function collect(report) {
|
|
48
|
+
const findings = [];
|
|
49
|
+
for (const r of report.Results || []) {
|
|
50
|
+
for (const v of r.Vulnerabilities || []) {
|
|
51
|
+
findings.push({
|
|
52
|
+
type: 'vuln', target: r.Target, severity: v.Severity, id: v.VulnerabilityID,
|
|
53
|
+
title: `${v.PkgName}@${v.InstalledVersion}` + (v.FixedVersion ? ` → ${v.FixedVersion}` : '') +
|
|
54
|
+
(v.Title ? ` · ${v.Title}` : ''),
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
for (const s of r.Secrets || []) {
|
|
58
|
+
findings.push({
|
|
59
|
+
type: 'secret', target: `${r.Target}:${s.StartLine}`, severity: s.Severity,
|
|
60
|
+
id: s.RuleID, title: s.Title,
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
for (const m of r.Misconfigurations || []) {
|
|
64
|
+
if (m.Status && m.Status !== 'FAIL') continue;
|
|
65
|
+
findings.push({
|
|
66
|
+
type: 'misconfig', target: r.Target, severity: m.Severity, id: m.ID || m.AVDID,
|
|
67
|
+
title: m.Title,
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
findings.sort((a, b) => SEVERITY_ORDER.indexOf(b.severity) - SEVERITY_ORDER.indexOf(a.severity));
|
|
72
|
+
return findings;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function format(findings) {
|
|
76
|
+
if (!findings.length) return '';
|
|
77
|
+
return findings
|
|
78
|
+
.map((f) => ` ${f.severity.padEnd(8)} ${f.type.padEnd(9)} ${f.id} ${f.target}\n ${f.title || ''}`)
|
|
79
|
+
.join('\n');
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async function run(cfg, { cwd = process.cwd() } = {}) {
|
|
83
|
+
const runner = resolveRunner(cfg, cwd);
|
|
84
|
+
if (!runner) {
|
|
85
|
+
const msg = 'Trivy no está instalado y docker no está disponible ' +
|
|
86
|
+
'(instalar: brew install trivy · https://trivy.dev).';
|
|
87
|
+
return { name: 'trivy', ok: !cfg.required, skipped: true, summary: msg, output: '' };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const r = spawnSync(runner.cmd, [...runner.prefix, ...buildArgs(cfg, runner.target)], {
|
|
91
|
+
cwd,
|
|
92
|
+
encoding: 'utf8',
|
|
93
|
+
maxBuffer: 256 * 1024 * 1024,
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
if (r.status !== 0) {
|
|
97
|
+
return {
|
|
98
|
+
name: 'trivy', ok: false,
|
|
99
|
+
summary: `Error ejecutando trivy vía ${runner.via} (exit ${r.status})`,
|
|
100
|
+
output: (r.stderr || r.error?.message || '').trim(),
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
let report;
|
|
105
|
+
try {
|
|
106
|
+
report = JSON.parse(r.stdout || '{}');
|
|
107
|
+
} catch (err) {
|
|
108
|
+
return { name: 'trivy', ok: false, summary: 'Salida de trivy no es JSON válido', output: r.stdout };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const findings = collect(report);
|
|
112
|
+
const counts = {};
|
|
113
|
+
for (const f of findings) counts[f.severity] = (counts[f.severity] || 0) + 1;
|
|
114
|
+
const blocking = findings.filter((f) => cfg.failOn.includes(f.severity));
|
|
115
|
+
const countStr = SEVERITY_ORDER.slice().reverse()
|
|
116
|
+
.filter((s) => counts[s]).map((s) => `${s}: ${counts[s]}`).join(', ') || 'sin hallazgos';
|
|
117
|
+
|
|
118
|
+
return {
|
|
119
|
+
name: 'trivy',
|
|
120
|
+
ok: blocking.length === 0,
|
|
121
|
+
summary: `vía ${runner.via} · ${countStr}` +
|
|
122
|
+
(blocking.length ? ` · ${blocking.length} bloqueantes (${cfg.failOn.join('/')})` : ''),
|
|
123
|
+
output: format(findings),
|
|
124
|
+
data: findings,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
module.exports = { run };
|
package/donbot.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
'use strict';
|
|
3
|
+
const pkg = require('./package.json');
|
|
3
4
|
const { Command } = require("commander");
|
|
4
5
|
const program = new Command();
|
|
5
6
|
|
|
@@ -11,8 +12,8 @@ const flows = require('./cli/flows');
|
|
|
11
12
|
|
|
12
13
|
//Version
|
|
13
14
|
program
|
|
14
|
-
.version("DonBot
|
|
15
|
-
.description(
|
|
15
|
+
.version("DonBot " + pkg.version)
|
|
16
|
+
.description(`
|
|
16
17
|
_____ _______ __ _ ______ _______ _______
|
|
17
18
|
| | | || | | || _ | | || |
|
|
18
19
|
| _ | | _ || || || | | | | _ ||_ _|
|
|
@@ -26,14 +27,14 @@ program
|
|
|
26
27
|
|
|
27
28
|
//Creamos usuarios
|
|
28
29
|
program.
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
30
|
+
command("createuser <mail> <first_name> <last_name> <password>").
|
|
31
|
+
alias("cu").
|
|
32
|
+
description("Creamos un usuario en la base de datos").
|
|
33
|
+
action((mail, first_name, last_name, password, options) => {
|
|
34
|
+
access.registry(mail, first_name, last_name, password, options);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
//Create app Token
|
|
37
38
|
program.
|
|
38
39
|
command("access <user> <app> <description> <expiration>").
|
|
39
40
|
alias("ac").
|
|
@@ -77,6 +78,7 @@ program.
|
|
|
77
78
|
|
|
78
79
|
`).
|
|
79
80
|
option("--novalidcode", "Omitir la validación de código antes del deploy").
|
|
81
|
+
option("--skipcheck <checks>", "Omitir rutinas de validación (ej: trivy)").
|
|
80
82
|
action((type_deploy, options) => {
|
|
81
83
|
deploy.uploadCodeToServer(type_deploy, options);
|
|
82
84
|
});
|
|
@@ -84,9 +86,18 @@ program.
|
|
|
84
86
|
program.
|
|
85
87
|
command("validcode").
|
|
86
88
|
alias("vc").
|
|
87
|
-
description(`Ejecuta
|
|
88
|
-
|
|
89
|
-
|
|
89
|
+
description(`Ejecuta las rutinas de validación del CLI sobre el proyecto actual
|
|
90
|
+
(independientes de la versión de donbot).
|
|
91
|
+
|
|
92
|
+
Rutinas: eslint (calidad + seguridad), trivy (vulnerabilidades, secretos, misconfig)
|
|
93
|
+
Config opcional: ./.conf/validate-donbot-cli.json
|
|
94
|
+
`).
|
|
95
|
+
option("--only <checks>", "Ejecuta solo estas rutinas, separadas por coma (eslint,trivy)").
|
|
96
|
+
option("--skip <checks>", "Omite estas rutinas, separadas por coma").
|
|
97
|
+
option("--fix", "Aplica correcciones automáticas de ESLint").
|
|
98
|
+
option("--report <file>", "Guarda un reporte JSON con los resultados").
|
|
99
|
+
action((options) => {
|
|
100
|
+
deploy.validCode_donbot(options);
|
|
90
101
|
});
|
|
91
102
|
|
|
92
103
|
// Flow
|
|
@@ -98,8 +109,8 @@ program.
|
|
|
98
109
|
option("--cron", "Genera también un archivo de crons para iniciar los flujos").
|
|
99
110
|
option("--endpoint", "Genera también un archivo de rutas para el controlador").
|
|
100
111
|
option("--controller", "Genera también un archivo de crons para iniciar los flujos").
|
|
101
|
-
action((name,options) => {
|
|
102
|
-
flows.newflow(name,options);
|
|
112
|
+
action((name, options) => {
|
|
113
|
+
flows.newflow(name, options);
|
|
103
114
|
});
|
|
104
115
|
|
|
105
116
|
// Routes
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "donbot-cli",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.12",
|
|
4
4
|
"description": "Cli de donbot",
|
|
5
5
|
"main": "donbot.js",
|
|
6
6
|
"bin": {
|
|
@@ -9,11 +9,15 @@
|
|
|
9
9
|
"author": "Oscar Aparicio",
|
|
10
10
|
"license": "ISC",
|
|
11
11
|
"dependencies": {
|
|
12
|
+
"@eslint/js": "^9.39.5",
|
|
12
13
|
"bcryptjs": "^2.4.3",
|
|
13
14
|
"child_process": "^1.0.2",
|
|
14
15
|
"commander": "^13.1.0",
|
|
15
16
|
"dotenv": "^16.4.7",
|
|
17
|
+
"eslint": "^9.39.5",
|
|
18
|
+
"eslint-plugin-security": "^4.2.1",
|
|
16
19
|
"fs": "^0.0.1-security",
|
|
20
|
+
"globals": "^17.14.0",
|
|
17
21
|
"jsonwebtoken": "^9.0.2",
|
|
18
22
|
"mongodb": "^6.13.0",
|
|
19
23
|
"path": "^0.12.7",
|