@efraindrummer/ghostdeps 0.3.0 → 0.5.0

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/CHANGELOG.md CHANGED
@@ -2,6 +2,26 @@
2
2
 
3
3
  Formato basado en [Keep a Changelog](https://keepachangelog.com/es-ES/1.1.0/) y [SemVer](https://semver.org/lang/es/).
4
4
 
5
+ ## [0.5.0] - 2026-11-26
6
+
7
+ ### Añadido
8
+ - **Detección de Typosquatting y Confusión de Nombres**: Detección heurística mediante distancia de Levenshtein y normalización de separadores contra los top paquetes de npm. Alerta sobre suplantaciones visuales y ataques dirigidos (ej. `crossenv` vs `cross-env`, `cha1k` vs `chalk`). Penalización configurable (-50 pts) y regla SARIF `GD012`.
9
+ - **Verificación de npm Build Provenance**: Detección de firmas criptográficas y atestaciones SLSA (Sigstore) generadas en CI oficial (GitHub Actions).
10
+ - **Auditoría de Licencias y Compliance Legal (`--allow-licenses`, `--deny-licenses`)**: Detección de licencias copyleft restrictivas (GPL, AGPL) y validación de listas de licencias permitidas o denegadas. Emite alerta y regla SARIF `GD013`.
11
+ - **Notificaciones Webhook para Slack, Discord y APIs (`--webhook`)**: Envío automático de alertas y resúmenes ejecutivos con formato nativo para Slack (Block Kit) y Discord (Embeds).
12
+ - **Generador de Git Pre-commit Hooks (`ghostdeps hook`)**: Comando de instalación automática de hooks para `.husky` o `.git/hooks/pre-commit` con quality gate configurable (`--fail-under`).
13
+ - **Soporte completo para Yarn Berry (v2, v3, v4)**: Compatibilidad con el nuevo formato YAML de `yarn.lock`, descriptores `@npm:` y resolución transitiva moderna.
14
+
15
+ ## [0.4.0] - 2026-11-25
16
+
17
+ ### Añadido
18
+ - **Detección de Lifecycle Scripts sospechosos**: inspección heurística de scripts (`preinstall`, `install`, `postinstall`) para detectar descargas remotas (`curl`, `wget`), ejecución de shells (`powershell`, `cmd.exe`, `bash`), ofuscación o evaluación en memoria (`eval`, `Buffer.from`, `base64`) y acceso a credenciales (`.env`, `.ssh`). Penalización configurable (`suspiciousScripts`, -35 pts) y regla SARIF `GD011`.
19
+ - **Soporte completo para `pnpm-lock.yaml`**: resolución recursiva de dependencias transitivas deduplicadas respetando `--depth` y árbol de procedencia (`via`). Soporta ahora los 3 grandes del ecosistema: `npm`, `yarn` y `pnpm`.
20
+ - **Reporte visual interactivo y autónomo en HTML (`--html` o `-f html`)**: informe web 100% self-contained (cero CDNs externas o dependencias remotas) con filtrado instantáneo por nivel de riesgo, búsqueda reactiva, visualización de scripts de instalación y enlaces de auditoría.
21
+ - **Subcomando de remediación automática (`ghostdeps fix`)**: genera e inyecta `overrides` (npm), `resolutions` (yarn) o `pnpm.overrides` (pnpm) en `package.json` para neutralizar dependencias transitivas vulnerables o críticas. Admite `--dry-run`, `--no-backup` y `--override <pkg=ver>`.
22
+ - **Inspector forense de diferencias entre versiones (`ghostdeps diff <paquete>`)**: comparativa de seguridad entre versiones de un paquete en npm. Alerta si cambió de publicador (`_npmUser`), adición de scripts sospechosos, nuevos mantenedores o cambios abruptos de repositorio. Admite análisis forense asistido por IA (`--ai`).
23
+ - **GitHub Action oficial (`action.yml`)**: permite integrar GhostDeps en flujos de CI/CD de GitHub (`uses: efraindrummer/ghostdeps@v0.4.0`) con soporte nativo para reportes en Markdown en el PR Summary y SARIF para GitHub Code Scanning.
24
+
5
25
  ## [0.3.0] - 2026-11-25
6
26
 
7
27
  ### Añadido
package/README.md CHANGED
@@ -9,7 +9,7 @@
9
9
  Los escáneres de vulnerabilidades te avisan cuando ya existe un CVE. GhostDeps intenta avisarte **antes**: cuando una dependencia lleva años sin commits, depende de una sola persona, está archivada/deprecated o cambió de manos de forma sospechosa (el patrón de `event-stream`, `ua-parser-js` o `xz`).
10
10
 
11
11
  ```
12
- 👻 GhostDeps v0.3.0 · mi-app
12
+ 👻 GhostDeps v0.5.0 · mi-app
13
13
  ┌─────────────────────────────┬───────┬──────────────────┬───────────────┬──────────────────────────────────────────────┐
14
14
  │ Paquete │ Score │ Días últ. commit │ Mant. activos │ Alerta principal │
15
15
  ├─────────────────────────────┼───────┼──────────────────┼───────────────┼──────────────────────────────────────────────┤
@@ -117,12 +117,13 @@ ghostdeps --version
117
117
  | `-p, --path <dir>` | Directorio con el `package.json` | directorio actual |
118
118
  | `--config <file>` | Archivo de configuración explícito | autodetección |
119
119
  | `-d, --dev` | Incluye también `devDependencies` | `false` |
120
- | `-t, --transitive` | Incluye dependencias transitivas (requiere `package-lock.json`) | `false` |
120
+ | `-t, --transitive` | Incluye dependencias transitivas (requiere `package-lock.json`, `yarn.lock` o `pnpm-lock.yaml`) | `false` |
121
121
  | `--depth <n>` | Profundidad máxima con `--transitive` (1 = solo directas) | sin límite |
122
122
  | `-i, --ignore <lista>` | Paquetes a omitir, separados por coma; admite `*` | — |
123
- | `-f, --format <fmt>` | `table`, `json` o `markdown` | `table` |
123
+ | `-f, --format <fmt>` | `table`, `json`, `markdown`, `sarif` o `html` | `table` |
124
124
  | `--json` | Atajo de `--format json` | `false` |
125
- | `-o, --output <file>` | Escribe el informe en un archivo (sin colores) | stdout |
125
+ | `--html [file]` | Genera informe interactivo en HTML (atajo de `--format html`) | `false` |
126
+ | `-o, --output <file>` | Escribe el informe en un archivo (sin colores ANSI) | stdout |
126
127
  | `--fail-under <score>` | Exit code `1` si algún paquete **evaluado** tiene score menor | — |
127
128
  | `-c, --concurrency <n>` | Paquetes analizados en paralelo (1–32) | `4` |
128
129
  | `--explain` | Desglose de penalizaciones de cada paquete | `false` |
@@ -130,6 +131,9 @@ ghostdeps --version
130
131
  | `--ai-provider <prov>` | Proveedor de IA: `gemini`, `anthropic` u `openai` | autodetección |
131
132
  | `--ai-model <model>` | Modelo específico de IA a consultar | por defecto del proveedor |
132
133
  | `--mcp` | Inicia el servidor MCP (Model Context Protocol) sobre stdio | `false` |
134
+ | `--allow-licenses <lics>` | Lista blanca de licencias permitidas separadas por coma | sin filtro |
135
+ | `--deny-licenses <lics>` | Lista negra de licencias denegadas (ej. `GPL-3.0,AGPL-3.0`) | sin filtro |
136
+ | `--webhook <url>` | URL de Webhook (Slack, Discord o HTTP) para enviar alertas | — |
133
137
  | `--no-cache` | No lee ni escribe la caché en disco | caché activa |
134
138
  | `--cache-ttl <horas>` | TTL de la caché | `24` |
135
139
  | `--timeout <ms>` | Timeout por petición | `15000` |
@@ -214,7 +218,7 @@ Cómo funciona:
214
218
  - Reproduce la resolución de Node (`node_modules` anidados y *hoisting*) sobre el lockfile y recorre el grafo en anchura.
215
219
  - Cada paquete se analiza **una sola vez** aunque aparezca varias veces en el árbol (se deduplica por nombre).
216
220
  - Los paquetes instalados desde git o `file:` se marcan como *No evaluable*; los *workspaces* (`link: true`) no se recorren.
217
- - Soporta `package-lock.json` (npm ≥ 7 v2/v3) y `yarn.lock` (Yarn v1). `pnpm-lock.yaml` está en desarrollo.
221
+ - Soporta `package-lock.json` (npm ≥ 7 v2/v3), `yarn.lock` (Yarn v1 y Yarn Berry v2/v3/v4) y `pnpm-lock.yaml` (pnpm v5/v6/v9).
218
222
 
219
223
  > [!TIP]
220
224
  > Un árbol típico tiene cientos de paquetes (~3 peticiones a GitHub cada uno). Usa **siempre** `GITHUB_TOKEN`, y combina `--depth` e `ignore` para acotar. La caché hace que las ejecuciones siguientes sean casi instantáneas.
@@ -332,6 +336,7 @@ Una vez configurado, tu agente de IA puede auditar proyectos automáticamente cu
332
336
  | `table` (default) | Terminal, con colores | `ghostdeps` |
333
337
  | `json` | Integraciones, scripts, dashboards | `ghostdeps --json > report.json` |
334
338
  | `markdown` | Comentarios de PR, `$GITHUB_STEP_SUMMARY`, wikis | `ghostdeps -f markdown -o ghostdeps.md` |
339
+ | `html` | Reporte visual interactivo y autónomo para CI / auditorías | `ghostdeps --html reporte.html` |
335
340
  | `sarif` | GitHub Code Scanning / Security alerts | `ghostdeps -f sarif -o ghostdeps.sarif` |
336
341
 
337
342
  En todos los formatos, el informe va a **stdout** (o al archivo de `-o`) y los avisos/progreso a **stderr**, así que se puede redirigir o encadenar sin problemas.
@@ -415,6 +420,127 @@ Reglas SARIF incluidas:
415
420
  - `GD008`: Publicador nuevo no habitual (`warning`)
416
421
  - `GD009`: Patrón combinado de secuestro/hijacking (`error`)
417
422
  - `GD010`: Publicación desactualizada en npm (`note`)
423
+ - `GD011`: Script de ciclo de vida de instalación potencialmente peligroso (`error`)
424
+ - `GD012`: Posible intento de typosquatting o suplantación de paquete popular (`error`)
425
+ - `GD013`: Infracción de compliance legal o política de licencias permitidas/denegadas (`warning`)
426
+
427
+ #### Reporte Visual Autónomo en HTML (`--html`)
428
+
429
+ Genera un reporte web 100% self-contained (sin dependencias externas ni fuentes en la nube, ideal para entornos air-gapped o artefactos de CI):
430
+
431
+ ```bash
432
+ ghostdeps --transitive --html reporte-seguridad.html
433
+ ```
434
+
435
+ Incluye:
436
+ - **Filtrado reactivo instantáneo:** Botones para filtrar por Crítico, Precaución, Saludable o solo dependencias con Lifecycle Scripts.
437
+ - **Buscador interactivo:** Filtra en tiempo real por nombre de paquete o alertas.
438
+ - **Acordeón de detalles:** Al hacer clic en cualquier fila, se expanden penalizaciones exactas, comandos ejecutados en `postinstall`, trazabilidad de transitivas y enlaces directos a npm y GitHub.
439
+
440
+ ### Remediación Automática (`ghostdeps fix`)
441
+
442
+ Aísla o actualiza dependencias transitivas vulnerables o críticas inyectando resoluciones forzadas en tu `package.json`:
443
+ - **npm:** genera bloque `overrides`
444
+ - **yarn:** genera bloque `resolutions`
445
+ - **pnpm:** genera bloque `pnpm.overrides`
446
+
447
+ ```bash
448
+ # Vista previa sin modificar archivos
449
+ ghostdeps fix --dry-run
450
+
451
+ # Aplicar automáticamente overrides propuestos por el escáner (crea package.json.bak)
452
+ ghostdeps fix
453
+
454
+ # Inyectar un override manual específico
455
+ ghostdeps fix --override "vulnerable-dep=^2.0.4"
456
+ ```
457
+
458
+ ### Inspección Forense de Versiones (`ghostdeps diff <paquete>`)
459
+
460
+ Permite auditar qué cambió exactamente entre dos versiones publicadas en npm de cualquier paquete, detectando cambios bruscos o patrones de secuestro de cuentas (account hijacking):
461
+
462
+ ```bash
463
+ # Comparar la última versión con la inmediata anterior
464
+ ghostdeps diff event-stream
465
+
466
+ # Comparar versiones específicas
467
+ ghostdeps diff event-stream --from 3.3.5 --to 3.3.6
468
+
469
+ # Auditoría asistida por IA
470
+ ghostdeps diff ua-parser-js --from 0.7.28 --to 0.7.29 --ai
471
+ ```
472
+
473
+ Detecta y alerta sobre:
474
+ - Cambio de publicador (`_npmUser`)
475
+ - Modificaciones en scripts de instalación (`preinstall`, `install`, `postinstall`)
476
+ - Nuevos mantenedores añadidos o dados de baja
477
+ - Nuevas dependencias agregadas
478
+ - Alteración de URL de repositorio o redirecciones
479
+
480
+ ### GitHub Action Oficial (`action.yml`)
481
+
482
+ Puedes integrar GhostDeps directamente en tus workflows de GitHub Actions:
483
+
484
+ ```yaml
485
+ # .github/workflows/security.yml
486
+ name: GhostDeps Security Audit
487
+
488
+ on:
489
+ pull_request:
490
+ branches: [main]
491
+ push:
492
+ branches: [main]
493
+
494
+ jobs:
495
+ audit:
496
+ runs-on: ubuntu-latest
497
+ steps:
498
+ - uses: actions/checkout@v4
499
+
500
+ - name: Run GhostDeps Audit
501
+ uses: efraindrummer/ghostdeps@v0.5.0
502
+ with:
503
+ fail-under: '60'
504
+ transitive: 'true'
505
+ format: 'markdown'
506
+ github-token: ${{ secrets.GITHUB_TOKEN }}
507
+ ```
508
+
509
+ ### Git Pre-commit Hook (`ghostdeps hook`)
510
+
511
+ Instala un guardia de seguridad local en tu repositorio para que ningún desarrollador cometa por error código con dependencias críticas o vulnerables:
512
+
513
+ ```bash
514
+ # Instala automáticamente en .husky/pre-commit o .git/hooks/pre-commit
515
+ ghostdeps hook --fail-under 50
516
+
517
+ # Ver el script que se instalaría sin tocar el disco
518
+ ghostdeps hook --dry-run
519
+ ```
520
+
521
+ ### Auditoría y Compliance de Licencias (`--allow-licenses` / `--deny-licenses`)
522
+
523
+ Verifica que ninguna dependencia introduzca licencias *copyleft* infecciosas (GPL/AGPL) o licencias no autorizadas en tu proyecto:
524
+
525
+ ```bash
526
+ # Prohibir licencias restrictivas
527
+ ghostdeps --deny-licenses "GPL-3.0,AGPL-3.0"
528
+
529
+ # O requerir únicamente licencias de lista blanca
530
+ ghostdeps --allow-licenses "MIT,Apache-2.0,ISC,BSD-3-Clause"
531
+ ```
532
+
533
+ ### Notificaciones a Slack, Discord y Webhooks (`--webhook`)
534
+
535
+ Envía un resumen ejecutivo del escaneo a tu canal de seguridad o alertas en CI/CD:
536
+
537
+ ```bash
538
+ # Notificar a Slack (Block Kit nativo)
539
+ ghostdeps --webhook https://hooks.slack.com/services/T00/B00/XXXX
540
+
541
+ # Notificar a Discord (Embeds nativo)
542
+ ghostdeps --webhook https://discord.com/api/webhooks/123/xyz
543
+ ```
418
544
 
419
545
  ### Cómo leer la tabla
420
546
 
package/dist/analyzer.js CHANGED
@@ -50,7 +50,10 @@ export async function analyzePackage(dep, deps) {
50
50
  // RateLimitError, TimeoutError, HttpError...: el paquete queda como error y el análisis sigue.
51
51
  return failed(err);
52
52
  }
53
- report.signals = buildSignals(report.npm, report.github, deps.now);
53
+ report.signals = buildSignals(report.npm, report.github, deps.now, {
54
+ allowedLicenses: deps.allowedLicenses,
55
+ deniedLicenses: deps.deniedLicenses,
56
+ });
54
57
  report.result = computeScore(report.signals, deps.weights ?? DEFAULT_WEIGHTS, deps.thresholds ?? THRESHOLDS);
55
58
  return report;
56
59
  }
package/dist/cli.js CHANGED
@@ -12,10 +12,15 @@ import { GitHubClient } from './clients/github.js';
12
12
  import { RateLimitGate } from './clients/http.js';
13
13
  import { NpmClient } from './clients/npm.js';
14
14
  import { createIgnoreMatcher, loadConfig } from './config.js';
15
+ import { inspectPackageDiff } from './diff/inspect.js';
15
16
  import { GhostDepsError, errorMessage } from './errors.js';
17
+ import { applyFixPlan, createFixPlan, detectPackageManager, generateProposals } from './fix/remediator.js';
18
+ import { installGitHook } from './hooks/githook.js';
16
19
  import { startMcpServer } from './mcp/server.js';
20
+ import { sendWebhookNotification } from './notifications/webhook.js';
17
21
  import { readLockfile, resolveTransitive } from './parser/lockfile.js';
18
22
  import { readManifest } from './parser/manifest.js';
23
+ import { renderHtml } from './render/html.js';
19
24
  import { renderMarkdown } from './render/markdown.js';
20
25
  import { renderSarif } from './render/sarif.js';
21
26
  import { renderExplain, renderSummary, renderTable } from './render/table.js';
@@ -56,8 +61,16 @@ async function run(opts, command, version) {
56
61
  return new Promise(() => { }); // Escuchar indefinidamente sobre stdio
57
62
  }
58
63
  const fromCli = (key) => command.getOptionValueSource(key) === 'cli';
59
- const format = opts.json ? 'json' : opts.format;
60
- const quiet = format !== 'table'; // en json/markdown, stderr solo para avisos importantes
64
+ let format = opts.format;
65
+ if (opts.json)
66
+ format = 'json';
67
+ if (opts.html) {
68
+ format = 'html';
69
+ if (typeof opts.html === 'string' && !opts.output) {
70
+ opts.output = opts.html;
71
+ }
72
+ }
73
+ const quiet = format !== 'table';
61
74
  // --- Configuración efectiva: CLI > archivo > defaults ---
62
75
  const config = await loadConfig(opts.path, opts.config);
63
76
  const dev = fromCli('dev') ? opts.dev : (config.dev ?? opts.dev);
@@ -111,7 +124,15 @@ async function run(opts, command, version) {
111
124
  now: () => now,
112
125
  });
113
126
  const interactive = !quiet && process.stderr.isTTY;
114
- const reports = await analyzeAll(toAnalyze, { npm, github, now, weights: config.weights, thresholds: config.thresholds }, concurrency, (done, total, name) => {
127
+ const reports = await analyzeAll(toAnalyze, {
128
+ npm,
129
+ github,
130
+ now,
131
+ weights: config.weights,
132
+ thresholds: config.thresholds,
133
+ allowedLicenses: opts.allowLicenses.length > 0 ? opts.allowLicenses : config.allowedLicenses,
134
+ deniedLicenses: opts.denyLicenses.length > 0 ? opts.denyLicenses : config.deniedLicenses,
135
+ }, concurrency, (done, total, name) => {
115
136
  if (interactive)
116
137
  process.stderr.write(`\r\x1b[2K${chalk.gray(`Analizando ${done}/${total}: ${name}`)}`);
117
138
  });
@@ -177,6 +198,16 @@ async function run(opts, command, version) {
177
198
  rendered += `\n\n### 🤖 Recomendaciones de Ciberseguridad (${aiResult.provider} / ${aiResult.model})\n\n${aiResult.analysis}\n`;
178
199
  }
179
200
  }
201
+ else if (format === 'html') {
202
+ rendered = renderHtml(sorted, summary, now, {
203
+ version,
204
+ projectName: manifest.projectName,
205
+ thresholds: config.thresholds,
206
+ failUnder,
207
+ failing,
208
+ ignored,
209
+ });
210
+ }
180
211
  else if (format === 'sarif') {
181
212
  rendered = renderSarif(sorted, {
182
213
  version,
@@ -206,6 +237,28 @@ async function run(opts, command, version) {
206
237
  else {
207
238
  process.stdout.write(`${rendered}\n`);
208
239
  }
240
+ // --- Notificación Webhook (Slack / Discord / Genérico) ---
241
+ const webhookUrl = opts.webhook || config.webhook;
242
+ if (webhookUrl) {
243
+ const critList = sorted
244
+ .filter((r) => r.result && r.result.category === 'critical')
245
+ .map((r) => ({
246
+ name: r.name,
247
+ score: r.result.score,
248
+ mainAlert: r.result.mainAlert?.message,
249
+ }));
250
+ const sent = await sendWebhookNotification({
251
+ webhookUrl,
252
+ projectName: manifest.projectName,
253
+ version,
254
+ summary,
255
+ criticalPackages: critList,
256
+ failUnder,
257
+ failingCount: failing.length,
258
+ });
259
+ if (!quiet && sent)
260
+ log(chalk.green('✔ Notificación de alertas enviada al Webhook.'));
261
+ }
209
262
  if (gate.resetAt && gate.resetAt.getTime() > Date.now() && summary.errors > 0) {
210
263
  log(chalk.red(`\n✖ Se agotó el rate limit de GitHub (reset ${gate.resetAt.toLocaleTimeString()}). ` +
211
264
  'Los paquetes restantes quedaron como error; reintenta luego (los resultados ya obtenidos están en caché) ' +
@@ -231,11 +284,12 @@ async function main() {
231
284
  .option('-p, --path <dir>', 'directorio que contiene el package.json', process.cwd())
232
285
  .option('--config <file>', 'archivo de configuración (por defecto .ghostdepsrc.json o "ghostdeps" en package.json)')
233
286
  .option('-d, --dev', 'incluir también devDependencies', false)
234
- .option('-t, --transitive', 'incluir dependencias transitivas (requiere package-lock.json)', false)
287
+ .option('-t, --transitive', 'incluir dependencias transitivas (requiere package-lock.json, yarn.lock o pnpm-lock.yaml)', false)
235
288
  .option('--depth <n>', 'profundidad máxima con --transitive (1 = solo directas)', positiveInt('--depth', 100))
236
289
  .option('-i, --ignore <paquetes>', 'paquetes a omitir, separados por coma; admite * (ej. "@types/*")', collectList, [])
237
- .addOption(new Option('-f, --format <formato>', 'formato de salida').choices(['table', 'json', 'markdown', 'sarif']).default('table'))
290
+ .addOption(new Option('-f, --format <formato>', 'formato de salida').choices(['table', 'json', 'markdown', 'sarif', 'html']).default('table'))
238
291
  .option('--json', 'atajo de --format json', false)
292
+ .option('--html [file]', 'generar informe interactivo en HTML (atajo de --format html)')
239
293
  .option('-o, --output <file>', 'escribir el informe en un archivo en lugar de stdout')
240
294
  .option('--fail-under <score>', 'exit code 1 si algún paquete evaluado queda por debajo del score', scoreArg)
241
295
  .option('-c, --concurrency <n>', 'paquetes analizados en paralelo', positiveInt('--concurrency', 32), 4)
@@ -248,15 +302,26 @@ async function main() {
248
302
  .addOption(new Option('--ai-provider <provider>', 'proveedor de IA a utilizar').choices(['gemini', 'anthropic', 'openai']))
249
303
  .option('--ai-model <model>', 'modelo específico de IA a consultar')
250
304
  .option('--mcp', 'iniciar servidor MCP (Model Context Protocol) sobre stdio para agentes de IA', false)
305
+ .option('--allow-licenses <lics>', 'lista de licencias permitidas separadas por coma', collectList, [])
306
+ .option('--deny-licenses <lics>', 'lista de licencias denegadas separadas por coma (ej. GPL-3.0,AGPL-3.0)', collectList, [])
307
+ .option('--webhook <url>', 'URL de Webhook (Slack, Discord o HTTP genérico) para enviar resumen de alertas')
251
308
  .addHelpText('after', [
252
309
  '',
310
+ 'Subcomandos:',
311
+ ' ghostdeps fix Inyecta overrides/resolutions en package.json para corregir dependencias críticas',
312
+ ' ghostdeps diff <paquete> Compara dos versiones de un paquete en npm para detectar secuestros o scripts maliciosos',
313
+ ' ghostdeps hook Instala un pre-commit hook (Husky o Git nativo) para validar calidad antes de commit',
314
+ '',
253
315
  'Ejemplos:',
316
+ ' ghostdeps --transitive --format html -o reporte.html',
254
317
  ' ghostdeps --dev --explain',
255
- ' ghostdeps --transitive --depth 3 --ignore "@types/*"',
318
+ ' ghostdeps fix --dry-run',
319
+ ' ghostdeps hook --fail-under 50',
320
+ ' ghostdeps diff event-stream --from 3.3.5 --to 3.3.6',
321
+ ' ghostdeps --webhook https://hooks.slack.com/services/...',
322
+ ' ghostdeps --deny-licenses "GPL-3.0,AGPL-3.0"',
256
323
  ' ghostdeps --ai',
257
324
  ' ghostdeps --mcp',
258
- ' ghostdeps --format markdown -o ghostdeps.md',
259
- ' ghostdeps --fail-under 40',
260
325
  '',
261
326
  'Variables de entorno:',
262
327
  ' GITHUB_TOKEN / GH_TOKEN token de GitHub (recomendado; 5000 req/h)',
@@ -270,6 +335,190 @@ async function main() {
270
335
  .action(async (opts, command) => {
271
336
  process.exitCode = await run(opts, command, version);
272
337
  });
338
+ // --- Subcomando: ghostdeps fix ---
339
+ program
340
+ .command('fix')
341
+ .description('Genera o inyecta overrides/resolutions en package.json para remediar dependencias críticas o vulnerables.')
342
+ .option('-p, --path <dir>', 'directorio que contiene el package.json', process.cwd())
343
+ .option('--dry-run', 'muestra los cambios propuestos sin modificar package.json', false)
344
+ .option('--no-backup', 'no generar archivo package.json.bak de respaldo')
345
+ .addOption(new Option('--pm <manager>', 'gestor de paquetes forzado').choices(['npm', 'yarn', 'pnpm']))
346
+ .option('--override <pkg=version...>', 'overrides manuales en formato paquete=versión', collectList, [])
347
+ .action(async (cmdOpts) => {
348
+ const targetDir = path.resolve(cmdOpts.path);
349
+ const pkgJsonPath = path.resolve(targetDir, 'package.json');
350
+ const pm = cmdOpts.pm ?? (await detectPackageManager(targetDir));
351
+ const customOverrides = {};
352
+ for (const item of cmdOpts.override) {
353
+ const [pkg, ver] = item.split('=');
354
+ if (pkg && ver)
355
+ customOverrides[pkg.trim()] = ver.trim();
356
+ }
357
+ log(chalk.bold(`\n🔧 GhostDeps Fix — Gestor detectado: ${chalk.cyan(pm)}`));
358
+ const manifest = await readManifest(targetDir, { includeDev: false });
359
+ let all = manifest.dependencies;
360
+ try {
361
+ const { lock } = await readLockfile(targetDir);
362
+ const trans = resolveTransitive(lock, manifest.dependencies, { maxDepth: Number.POSITIVE_INFINITY });
363
+ all = [...manifest.dependencies, ...trans];
364
+ }
365
+ catch {
366
+ // Sin lockfile se analizan directas
367
+ }
368
+ const cache = new DiskCache(defaultCacheDir(), 24 * 3_600_000, true);
369
+ const npm = new NpmClient({ cache, timeoutMs: 15_000, retries: 2, userAgent: `ghostdeps-fix/${version}` });
370
+ const github = new GitHubClient({
371
+ cache,
372
+ timeoutMs: 15_000,
373
+ retries: 2,
374
+ userAgent: `ghostdeps-fix/${version}`,
375
+ gate: new RateLimitGate(),
376
+ maxRateLimitWaitMs: 30_000,
377
+ now: () => new Date(),
378
+ });
379
+ const reports = await analyzeAll(all, { npm, github, now: new Date() }, 4);
380
+ const proposals = generateProposals(reports, customOverrides);
381
+ if (proposals.length === 0) {
382
+ log(chalk.green('✔ No se encontraron dependencias críticas o vulnerables que requieran overrides.'));
383
+ process.exitCode = EXIT.OK;
384
+ return;
385
+ }
386
+ log(chalk.yellow(`\nSe detectaron ${proposals.length} dependencias para remediación:`));
387
+ for (const p of proposals) {
388
+ log(` - ${chalk.bold(p.packageName)}: ${chalk.gray(p.currentSpec)} → ${chalk.green(p.targetVersion)} (${p.reason})`);
389
+ }
390
+ const plan = await createFixPlan(pkgJsonPath, proposals, pm);
391
+ if (cmdOpts.dryRun) {
392
+ log(chalk.cyan('\n[Modo --dry-run] Vista previa del cambio a package.json:'));
393
+ log(plan.updatedContent);
394
+ process.exitCode = EXIT.OK;
395
+ return;
396
+ }
397
+ const res = await applyFixPlan(plan, { dryRun: false, backup: cmdOpts.backup });
398
+ if (res.written) {
399
+ log(chalk.green(`\n✔ package.json actualizado con ${pm === 'npm' ? 'overrides' : pm === 'yarn' ? 'resolutions' : 'pnpm.overrides'}.`));
400
+ if (res.backupPath)
401
+ log(chalk.gray(` Copia de seguridad: ${res.backupPath}`));
402
+ log(chalk.cyan(`\nEjecuta "${pm} install" para regenerar tu lockfile con las dependencias corregidas.`));
403
+ }
404
+ process.exitCode = EXIT.OK;
405
+ });
406
+ // --- Subcomando: ghostdeps diff <paquete> ---
407
+ program
408
+ .command('diff <paquete>')
409
+ .description('Compara dos versiones de un paquete de npm para detectar secuestro de cuentas, scripts peligrosos o cambios abruptos.')
410
+ .option('--from <version>', 'versión base a comparar')
411
+ .option('--to <version>', 'versión nueva (por defecto latest)')
412
+ .option('--ai', 'analizar diferencias con IA para evaluar riesgo forense de seguridad', false)
413
+ .addOption(new Option('--ai-provider <provider>', 'proveedor de IA a utilizar').choices(['gemini', 'anthropic', 'openai']))
414
+ .option('--ai-model <model>', 'modelo específico de IA')
415
+ .option('--json', 'imprimir resultado en formato JSON estructurado', false)
416
+ .action(async (packageName, cmdOpts) => {
417
+ try {
418
+ const report = await inspectPackageDiff(packageName, {
419
+ from: cmdOpts.from,
420
+ to: cmdOpts.to,
421
+ ai: cmdOpts.ai,
422
+ aiOptions: { provider: cmdOpts.aiProvider, model: cmdOpts.aiModel },
423
+ });
424
+ if (cmdOpts.json) {
425
+ process.stdout.write(JSON.stringify(report, null, 2) + '\n');
426
+ process.exitCode = EXIT.OK;
427
+ return;
428
+ }
429
+ const riskColor = report.riskLevel === 'critical'
430
+ ? chalk.bgRed.white.bold
431
+ : report.riskLevel === 'high'
432
+ ? chalk.red.bold
433
+ : report.riskLevel === 'medium'
434
+ ? chalk.yellow.bold
435
+ : chalk.green.bold;
436
+ log(chalk.bold(`\n🔍 GhostDeps Diff: ${report.packageName} (${report.fromVersion} → ${report.toVersion})`));
437
+ log(`Nivel de riesgo estimado: ${riskColor(` ${report.riskLevel.toUpperCase()} `)}\n`);
438
+ log(chalk.bold('Publicador:'));
439
+ if (report.publisher.changed) {
440
+ log(chalk.red(` ⚠ Cambió de publicador: "${report.publisher.from ?? 'N/A'}" → "${report.publisher.to ?? 'N/A'}"`));
441
+ }
442
+ else {
443
+ log(chalk.gray(` Sin cambios (${report.publisher.to ?? 'mismo publicador'})`));
444
+ }
445
+ if (report.maintainers.added.length > 0 || report.maintainers.removed.length > 0) {
446
+ log(chalk.bold('\nMantenedores:'));
447
+ if (report.maintainers.added.length > 0)
448
+ log(chalk.yellow(` + Añadidos: ${report.maintainers.added.join(', ')}`));
449
+ if (report.maintainers.removed.length > 0)
450
+ log(chalk.gray(` - Removidos: ${report.maintainers.removed.join(', ')}`));
451
+ }
452
+ if (report.installScripts.added.length > 0 ||
453
+ report.installScripts.removed.length > 0 ||
454
+ report.installScripts.modified.length > 0) {
455
+ log(chalk.bold('\nLifecycle Scripts:'));
456
+ for (const s of report.installScripts.added) {
457
+ const prefix = s.suspicious ? chalk.red.bold(' + [SOSPECHOSO]') : chalk.yellow(' +');
458
+ log(`${prefix} ${s.stage}: ${s.to}`);
459
+ }
460
+ for (const s of report.installScripts.modified) {
461
+ const prefix = s.suspicious ? chalk.red.bold(' ~ [SOSPECHOSO]') : chalk.yellow(' ~');
462
+ log(`${prefix} ${s.stage}: ${s.from} → ${s.to}`);
463
+ }
464
+ for (const s of report.installScripts.removed) {
465
+ log(chalk.gray(` - ${s.stage}: ${s.from}`));
466
+ }
467
+ }
468
+ if (report.dependencies.added.length > 0 ||
469
+ report.dependencies.removed.length > 0 ||
470
+ report.dependencies.modified.length > 0) {
471
+ log(chalk.bold('\nDependencias:'));
472
+ for (const d of report.dependencies.added)
473
+ log(chalk.green(` + ${d.name}@${d.to}`));
474
+ for (const d of report.dependencies.modified)
475
+ log(chalk.yellow(` ~ ${d.name}: ${d.from} → ${d.to}`));
476
+ for (const d of report.dependencies.removed)
477
+ log(chalk.gray(` - ${d.name}`));
478
+ }
479
+ if (report.alerts.length > 0) {
480
+ log(chalk.bold('\nAlertas de Seguridad:'));
481
+ for (const a of report.alerts)
482
+ log(` - ${chalk.yellow(a)}`);
483
+ }
484
+ if (report.aiAnalysis) {
485
+ log(chalk.bold.cyan('\n🤖 Análisis Forense con IA:'));
486
+ log(report.aiAnalysis);
487
+ }
488
+ log('');
489
+ process.exitCode = report.riskLevel === 'critical' ? EXIT.FAIL_UNDER : EXIT.OK;
490
+ }
491
+ catch (err) {
492
+ log(chalk.red(`\n✖ Error inspeccionando diff: ${err.message}`));
493
+ process.exitCode = EXIT.FATAL;
494
+ }
495
+ });
496
+ // --- Subcomando: ghostdeps hook ---
497
+ program
498
+ .command('hook')
499
+ .description('Instala un pre-commit hook de Git o Husky para auditar dependencias automáticamente antes de cada commit.')
500
+ .option('-p, --path <dir>', 'directorio del repositorio git', process.cwd())
501
+ .option('--fail-under <score>', 'score mínimo requerido para permitir el commit', scoreArg, 50)
502
+ .option('--dry-run', 'muestra el contenido del hook sin escribirlo a disco', false)
503
+ .action(async (cmdOpts) => {
504
+ try {
505
+ const res = await installGitHook(cmdOpts.path, { failUnder: cmdOpts.failUnder, dryRun: cmdOpts.dryRun });
506
+ if (cmdOpts.dryRun) {
507
+ log(chalk.cyan(`\n[Modo --dry-run] Pre-commit hook para ${res.type} (${res.hookPath}):\n`));
508
+ log(res.content);
509
+ process.exitCode = EXIT.OK;
510
+ return;
511
+ }
512
+ log(chalk.green(`\n✔ Git pre-commit hook (${res.type}) instalado correctamente en:`));
513
+ log(chalk.gray(` ${res.hookPath}`));
514
+ log(chalk.cyan(`\nAhora tus commits se cancelarán si alguna dependencia evaluada tiene score < ${cmdOpts.failUnder}.`));
515
+ process.exitCode = EXIT.OK;
516
+ }
517
+ catch (err) {
518
+ log(chalk.red(`\n✖ Error instalando git hook: ${err.message}`));
519
+ process.exitCode = EXIT.FATAL;
520
+ }
521
+ });
273
522
  // Evita que Commander haga process.exit(1) en errores de uso (colisionaría con --fail-under).
274
523
  program.exitOverride();
275
524
  try {
@@ -277,7 +526,6 @@ async function main() {
277
526
  }
278
527
  catch (err) {
279
528
  if (err instanceof CommanderError) {
280
- // Commander ya imprimió el mensaje (o la ayuda/versión).
281
529
  process.exitCode = err.exitCode === 0 ? EXIT.OK : EXIT.FATAL;
282
530
  return;
283
531
  }
@@ -3,6 +3,39 @@ import { fetchJson } from './http.js';
3
3
  const REGISTRY = 'https://registry.npmjs.org';
4
4
  /** Nº de versiones previas a la última que se usan para comparar publicadores. */
5
5
  const PUBLISHER_HISTORY = 5;
6
+ const SUSPICIOUS_SCRIPT_REGEX = /\b(curl|wget|powershell|cmd\.exe|bash|sh)\b|https?:\/\/|eval\(|Buffer\.from\(|\bbase64\b|\/etc\/(passwd|shadow)|\.ssh\/|\.env\b/i;
7
+ const LIFECYCLE_STAGES = ['preinstall', 'install', 'postinstall'];
8
+ export function inspectInstallScripts(scripts) {
9
+ if (!scripts || typeof scripts !== 'object') {
10
+ return { hasInstallScripts: false, suspicious: false, scripts: [] };
11
+ }
12
+ const detected = [];
13
+ let isSuspicious = false;
14
+ for (const stage of LIFECYCLE_STAGES) {
15
+ const cmd = scripts[stage];
16
+ if (typeof cmd === 'string' && cmd.trim()) {
17
+ const match = SUSPICIOUS_SCRIPT_REGEX.test(cmd);
18
+ let reason;
19
+ if (match) {
20
+ isSuspicious = true;
21
+ if (/curl|wget|https?:\/\//i.test(cmd))
22
+ reason = 'descarga de red en la instalación';
23
+ else if (/powershell|cmd\.exe|bash|sh/i.test(cmd))
24
+ reason = 'ejecución de shell';
25
+ else if (/eval\(|base64|Buffer\.from/i.test(cmd))
26
+ reason = 'posible ofuscación / eval';
27
+ else
28
+ reason = 'patrón sospechoso';
29
+ }
30
+ detected.push({ stage, command: cmd.trim(), suspicious: match, reason });
31
+ }
32
+ }
33
+ return {
34
+ hasInstallScripts: detected.length > 0,
35
+ suspicious: isSuspicious,
36
+ scripts: detected,
37
+ };
38
+ }
6
39
  function personName(p) {
7
40
  if (!p)
8
41
  return null;
@@ -79,6 +112,18 @@ export function extractNpmInfo(name, doc) {
79
112
  : deprecatedRaw === true
80
113
  ? 'deprecated'
81
114
  : null;
115
+ let license = null;
116
+ const rawLic = latestDoc?.license ?? doc.license;
117
+ if (typeof rawLic === 'string' && rawLic.trim()) {
118
+ license = rawLic.trim();
119
+ }
120
+ else if (rawLic && typeof rawLic === 'object' && 'type' in rawLic) {
121
+ const t = rawLic.type;
122
+ if (typeof t === 'string' && t.trim())
123
+ license = t.trim();
124
+ }
125
+ const hasProvenance = Boolean(latestDoc?.dist?.attestations ||
126
+ (Array.isArray(latestDoc?.dist?.signatures) && latestDoc.dist.signatures.length > 0));
82
127
  return {
83
128
  name: doc.name ?? name,
84
129
  latestVersion,
@@ -91,6 +136,9 @@ export function extractNpmInfo(name, doc) {
91
136
  latestPublisher,
92
137
  previousPublishers,
93
138
  maintainersChange,
139
+ installScripts: inspectInstallScripts(latestDoc?.scripts),
140
+ hasProvenance,
141
+ license,
94
142
  };
95
143
  }
96
144
  export class NpmClient {