@efraindrummer/ghostdeps 0.2.0 → 0.4.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/dist/cli.js CHANGED
@@ -5,15 +5,20 @@ import path from 'node:path';
5
5
  import { stripVTControlCharacters } from 'node:util';
6
6
  import chalk from 'chalk';
7
7
  import { Command, CommanderError, InvalidArgumentError, Option } from 'commander';
8
+ import { analyzeWithAi, detectAiConfig } from './ai/advisor.js';
8
9
  import { analyzeAll, sortReports, summarize } from './analyzer.js';
9
10
  import { DiskCache, defaultCacheDir } from './clients/cache.js';
10
11
  import { GitHubClient } from './clients/github.js';
11
12
  import { RateLimitGate } from './clients/http.js';
12
13
  import { NpmClient } from './clients/npm.js';
13
14
  import { createIgnoreMatcher, loadConfig } from './config.js';
15
+ import { inspectPackageDiff } from './diff/inspect.js';
14
16
  import { GhostDepsError, errorMessage } from './errors.js';
17
+ import { applyFixPlan, createFixPlan, detectPackageManager, generateProposals } from './fix/remediator.js';
18
+ import { startMcpServer } from './mcp/server.js';
15
19
  import { readLockfile, resolveTransitive } from './parser/lockfile.js';
16
20
  import { readManifest } from './parser/manifest.js';
21
+ import { renderHtml } from './render/html.js';
17
22
  import { renderMarkdown } from './render/markdown.js';
18
23
  import { renderSarif } from './render/sarif.js';
19
24
  import { renderExplain, renderSummary, renderTable } from './render/table.js';
@@ -49,9 +54,21 @@ function collectList(value, previous = []) {
49
54
  }
50
55
  const log = (msg) => process.stderr.write(`${msg}\n`);
51
56
  async function run(opts, command, version) {
57
+ if (opts.mcp) {
58
+ startMcpServer(version);
59
+ return new Promise(() => { }); // Escuchar indefinidamente sobre stdio
60
+ }
52
61
  const fromCli = (key) => command.getOptionValueSource(key) === 'cli';
53
- const format = opts.json ? 'json' : opts.format;
54
- const quiet = format !== 'table'; // en json/markdown, stderr solo para avisos importantes
62
+ let format = opts.format;
63
+ if (opts.json)
64
+ format = 'json';
65
+ if (opts.html) {
66
+ format = 'html';
67
+ if (typeof opts.html === 'string' && !opts.output) {
68
+ opts.output = opts.html;
69
+ }
70
+ }
71
+ const quiet = format !== 'table';
55
72
  // --- Configuración efectiva: CLI > archivo > defaults ---
56
73
  const config = await loadConfig(opts.path, opts.config);
57
74
  const dev = fromCli('dev') ? opts.dev : (config.dev ?? opts.dev);
@@ -116,6 +133,30 @@ async function run(opts, command, version) {
116
133
  const failing = failUnder === undefined
117
134
  ? []
118
135
  : sorted.filter((r) => r.status === 'evaluated' && r.result && r.result.score < failUnder).map((r) => r.name);
136
+ // --- Asesor de Ciberseguridad IA ---
137
+ let aiResult = null;
138
+ if (opts.ai) {
139
+ const hasRisks = sorted.some((r) => r.status === 'evaluated' && r.result && r.result.score < 70);
140
+ const aiConfig = detectAiConfig({ provider: opts.aiProvider, model: opts.aiModel });
141
+ if (!aiConfig) {
142
+ log(chalk.yellow('\n⚠ Modo --ai activado pero no se detectó ninguna clave de API.\n' +
143
+ ' Exporta GEMINI_API_KEY, ANTHROPIC_API_KEY u OPENAI_API_KEY en tu entorno.'));
144
+ }
145
+ else if (!hasRisks) {
146
+ if (!quiet)
147
+ log(chalk.green('\n🤖 IA: Todas las dependencias están saludables (score ≥ 70). No se requieren reemplazos.'));
148
+ }
149
+ else {
150
+ if (!quiet)
151
+ log(chalk.cyan(`\n🤖 Consultando a ${aiConfig.provider} (${aiConfig.model}) para análisis de mitigación y reemplazos...`));
152
+ try {
153
+ aiResult = await analyzeWithAi(sorted, summary, { provider: opts.aiProvider, model: opts.aiModel });
154
+ }
155
+ catch (err) {
156
+ log(chalk.red(`\n✖ Error consultando a la IA: ${err.message}`));
157
+ }
158
+ }
159
+ }
119
160
  // --- Salida ---
120
161
  let rendered;
121
162
  if (format === 'json') {
@@ -125,11 +166,12 @@ async function run(opts, command, version) {
125
166
  generatedAt: now.toISOString(),
126
167
  manifest: manifest.manifestPath,
127
168
  config: config.source,
128
- options: { dev, transitive, depth: depth ?? null, failUnder: failUnder ?? null, authenticated: Boolean(token) },
169
+ options: { dev, transitive, depth: depth ?? null, failUnder: failUnder ?? null, authenticated: Boolean(token), ai: opts.ai },
129
170
  thresholds: config.thresholds,
130
171
  summary,
131
172
  ignored,
132
173
  failUnder: failUnder === undefined ? null : { threshold: failUnder, failing },
174
+ aiAnalysis: aiResult,
133
175
  packages: sorted,
134
176
  }, null, 2);
135
177
  }
@@ -142,6 +184,19 @@ async function run(opts, command, version) {
142
184
  failing,
143
185
  ignored,
144
186
  });
187
+ if (aiResult) {
188
+ rendered += `\n\n### 🤖 Recomendaciones de Ciberseguridad (${aiResult.provider} / ${aiResult.model})\n\n${aiResult.analysis}\n`;
189
+ }
190
+ }
191
+ else if (format === 'html') {
192
+ rendered = renderHtml(sorted, summary, now, {
193
+ version,
194
+ projectName: manifest.projectName,
195
+ thresholds: config.thresholds,
196
+ failUnder,
197
+ failing,
198
+ ignored,
199
+ });
145
200
  }
146
201
  else if (format === 'sarif') {
147
202
  rendered = renderSarif(sorted, {
@@ -152,12 +207,17 @@ async function run(opts, command, version) {
152
207
  }
153
208
  else {
154
209
  const title = manifest.projectName ? ` · ${manifest.projectName}` : '';
155
- rendered = [
210
+ const parts = [
156
211
  chalk.bold(`\n👻 GhostDeps v${version}${title}`),
157
212
  renderTable(sorted, now),
158
213
  renderSummary(summary, config.thresholds),
159
214
  ...(opts.explain ? [renderExplain(sorted)] : []),
160
- ].join('\n');
215
+ ];
216
+ if (aiResult) {
217
+ parts.push(chalk.bold.cyan(`\n🤖 Recomendaciones de Ciberseguridad (${aiResult.provider} / ${aiResult.model}):`));
218
+ parts.push(aiResult.analysis);
219
+ }
220
+ rendered = parts.join('\n');
161
221
  }
162
222
  if (opts.output) {
163
223
  const file = path.resolve(opts.output);
@@ -192,11 +252,12 @@ async function main() {
192
252
  .option('-p, --path <dir>', 'directorio que contiene el package.json', process.cwd())
193
253
  .option('--config <file>', 'archivo de configuración (por defecto .ghostdepsrc.json o "ghostdeps" en package.json)')
194
254
  .option('-d, --dev', 'incluir también devDependencies', false)
195
- .option('-t, --transitive', 'incluir dependencias transitivas (requiere package-lock.json)', false)
255
+ .option('-t, --transitive', 'incluir dependencias transitivas (requiere package-lock.json, yarn.lock o pnpm-lock.yaml)', false)
196
256
  .option('--depth <n>', 'profundidad máxima con --transitive (1 = solo directas)', positiveInt('--depth', 100))
197
257
  .option('-i, --ignore <paquetes>', 'paquetes a omitir, separados por coma; admite * (ej. "@types/*")', collectList, [])
198
- .addOption(new Option('-f, --format <formato>', 'formato de salida').choices(['table', 'json', 'markdown', 'sarif']).default('table'))
258
+ .addOption(new Option('-f, --format <formato>', 'formato de salida').choices(['table', 'json', 'markdown', 'sarif', 'html']).default('table'))
199
259
  .option('--json', 'atajo de --format json', false)
260
+ .option('--html [file]', 'generar informe interactivo en HTML (atajo de --format html)')
200
261
  .option('-o, --output <file>', 'escribir el informe en un archivo en lugar de stdout')
201
262
  .option('--fail-under <score>', 'exit code 1 si algún paquete evaluado queda por debajo del score', scoreArg)
202
263
  .option('-c, --concurrency <n>', 'paquetes analizados en paralelo', positiveInt('--concurrency', 32), 4)
@@ -205,23 +266,194 @@ async function main() {
205
266
  .option('--timeout <ms>', 'timeout por request en milisegundos', positiveInt('--timeout'), 15_000)
206
267
  .option('--max-wait <seconds>', 'espera máxima ante rate limit antes de abortar', positiveInt('--max-wait'), 60)
207
268
  .option('--explain', 'mostrar el desglose de penalizaciones de cada paquete', false)
269
+ .option('--ai', 'analizar dependencias con IA para sugerir reemplazos y plan de mitigación', false)
270
+ .addOption(new Option('--ai-provider <provider>', 'proveedor de IA a utilizar').choices(['gemini', 'anthropic', 'openai']))
271
+ .option('--ai-model <model>', 'modelo específico de IA a consultar')
272
+ .option('--mcp', 'iniciar servidor MCP (Model Context Protocol) sobre stdio para agentes de IA', false)
208
273
  .addHelpText('after', [
209
274
  '',
275
+ 'Subcomandos:',
276
+ ' ghostdeps fix Inyecta overrides/resolutions en package.json para corregir dependencias críticas',
277
+ ' ghostdeps diff <paquete> Compara dos versiones de un paquete en npm para detectar secuestros o scripts maliciosos',
278
+ '',
210
279
  'Ejemplos:',
280
+ ' ghostdeps --transitive --format html -o reporte.html',
211
281
  ' ghostdeps --dev --explain',
212
- ' ghostdeps --transitive --depth 3 --ignore "@types/*"',
213
- ' ghostdeps --format markdown -o ghostdeps.md',
214
- ' ghostdeps --fail-under 40',
282
+ ' ghostdeps fix --dry-run',
283
+ ' ghostdeps diff event-stream --from 3.3.5 --to 3.3.6',
284
+ ' ghostdeps --ai',
285
+ ' ghostdeps --mcp',
215
286
  '',
216
287
  'Variables de entorno:',
217
- ' GITHUB_TOKEN / GH_TOKEN token de GitHub (recomendado; 5000 req/h)',
218
- ' GHOSTDEPS_CACHE_DIR directorio de caché personalizado',
288
+ ' GITHUB_TOKEN / GH_TOKEN token de GitHub (recomendado; 5000 req/h)',
289
+ ' GEMINI_API_KEY clave para modo --ai con Google Gemini',
290
+ ' ANTHROPIC_API_KEY clave para modo --ai con Anthropic Claude',
291
+ ' OPENAI_API_KEY clave para modo --ai con OpenAI ChatGPT',
292
+ ' GHOSTDEPS_CACHE_DIR directorio de caché personalizado',
219
293
  '',
220
294
  'Códigos de salida: 0 OK · 1 --fail-under incumplido · 2 error fatal',
221
295
  ].join('\n'))
222
296
  .action(async (opts, command) => {
223
297
  process.exitCode = await run(opts, command, version);
224
298
  });
299
+ // --- Subcomando: ghostdeps fix ---
300
+ program
301
+ .command('fix')
302
+ .description('Genera o inyecta overrides/resolutions en package.json para remediar dependencias críticas o vulnerables.')
303
+ .option('-p, --path <dir>', 'directorio que contiene el package.json', process.cwd())
304
+ .option('--dry-run', 'muestra los cambios propuestos sin modificar package.json', false)
305
+ .option('--no-backup', 'no generar archivo package.json.bak de respaldo')
306
+ .addOption(new Option('--pm <manager>', 'gestor de paquetes forzado').choices(['npm', 'yarn', 'pnpm']))
307
+ .option('--override <pkg=version...>', 'overrides manuales en formato paquete=versión', collectList, [])
308
+ .action(async (cmdOpts) => {
309
+ const targetDir = path.resolve(cmdOpts.path);
310
+ const pkgJsonPath = path.resolve(targetDir, 'package.json');
311
+ const pm = cmdOpts.pm ?? (await detectPackageManager(targetDir));
312
+ const customOverrides = {};
313
+ for (const item of cmdOpts.override) {
314
+ const [pkg, ver] = item.split('=');
315
+ if (pkg && ver)
316
+ customOverrides[pkg.trim()] = ver.trim();
317
+ }
318
+ log(chalk.bold(`\n🔧 GhostDeps Fix — Gestor detectado: ${chalk.cyan(pm)}`));
319
+ const manifest = await readManifest(targetDir, { includeDev: false });
320
+ let all = manifest.dependencies;
321
+ try {
322
+ const { lock } = await readLockfile(targetDir);
323
+ const trans = resolveTransitive(lock, manifest.dependencies, { maxDepth: Number.POSITIVE_INFINITY });
324
+ all = [...manifest.dependencies, ...trans];
325
+ }
326
+ catch {
327
+ // Sin lockfile se analizan directas
328
+ }
329
+ const cache = new DiskCache(defaultCacheDir(), 24 * 3_600_000, true);
330
+ const npm = new NpmClient({ cache, timeoutMs: 15_000, retries: 2, userAgent: `ghostdeps-fix/${version}` });
331
+ const github = new GitHubClient({
332
+ cache,
333
+ timeoutMs: 15_000,
334
+ retries: 2,
335
+ userAgent: `ghostdeps-fix/${version}`,
336
+ gate: new RateLimitGate(),
337
+ maxRateLimitWaitMs: 30_000,
338
+ now: () => new Date(),
339
+ });
340
+ const reports = await analyzeAll(all, { npm, github, now: new Date() }, 4);
341
+ const proposals = generateProposals(reports, customOverrides);
342
+ if (proposals.length === 0) {
343
+ log(chalk.green('✔ No se encontraron dependencias críticas o vulnerables que requieran overrides.'));
344
+ process.exitCode = EXIT.OK;
345
+ return;
346
+ }
347
+ log(chalk.yellow(`\nSe detectaron ${proposals.length} dependencias para remediación:`));
348
+ for (const p of proposals) {
349
+ log(` - ${chalk.bold(p.packageName)}: ${chalk.gray(p.currentSpec)} → ${chalk.green(p.targetVersion)} (${p.reason})`);
350
+ }
351
+ const plan = await createFixPlan(pkgJsonPath, proposals, pm);
352
+ if (cmdOpts.dryRun) {
353
+ log(chalk.cyan('\n[Modo --dry-run] Vista previa del cambio a package.json:'));
354
+ log(plan.updatedContent);
355
+ process.exitCode = EXIT.OK;
356
+ return;
357
+ }
358
+ const res = await applyFixPlan(plan, { dryRun: false, backup: cmdOpts.backup });
359
+ if (res.written) {
360
+ log(chalk.green(`\n✔ package.json actualizado con ${pm === 'npm' ? 'overrides' : pm === 'yarn' ? 'resolutions' : 'pnpm.overrides'}.`));
361
+ if (res.backupPath)
362
+ log(chalk.gray(` Copia de seguridad: ${res.backupPath}`));
363
+ log(chalk.cyan(`\nEjecuta "${pm} install" para regenerar tu lockfile con las dependencias corregidas.`));
364
+ }
365
+ process.exitCode = EXIT.OK;
366
+ });
367
+ // --- Subcomando: ghostdeps diff <paquete> ---
368
+ program
369
+ .command('diff <paquete>')
370
+ .description('Compara dos versiones de un paquete de npm para detectar secuestro de cuentas, scripts peligrosos o cambios abruptos.')
371
+ .option('--from <version>', 'versión base a comparar')
372
+ .option('--to <version>', 'versión nueva (por defecto latest)')
373
+ .option('--ai', 'analizar diferencias con IA para evaluar riesgo forense de seguridad', false)
374
+ .addOption(new Option('--ai-provider <provider>', 'proveedor de IA a utilizar').choices(['gemini', 'anthropic', 'openai']))
375
+ .option('--ai-model <model>', 'modelo específico de IA')
376
+ .option('--json', 'imprimir resultado en formato JSON estructurado', false)
377
+ .action(async (packageName, cmdOpts) => {
378
+ try {
379
+ const report = await inspectPackageDiff(packageName, {
380
+ from: cmdOpts.from,
381
+ to: cmdOpts.to,
382
+ ai: cmdOpts.ai,
383
+ aiOptions: { provider: cmdOpts.aiProvider, model: cmdOpts.aiModel },
384
+ });
385
+ if (cmdOpts.json) {
386
+ process.stdout.write(JSON.stringify(report, null, 2) + '\n');
387
+ process.exitCode = EXIT.OK;
388
+ return;
389
+ }
390
+ const riskColor = report.riskLevel === 'critical'
391
+ ? chalk.bgRed.white.bold
392
+ : report.riskLevel === 'high'
393
+ ? chalk.red.bold
394
+ : report.riskLevel === 'medium'
395
+ ? chalk.yellow.bold
396
+ : chalk.green.bold;
397
+ log(chalk.bold(`\n🔍 GhostDeps Diff: ${report.packageName} (${report.fromVersion} → ${report.toVersion})`));
398
+ log(`Nivel de riesgo estimado: ${riskColor(` ${report.riskLevel.toUpperCase()} `)}\n`);
399
+ log(chalk.bold('Publicador:'));
400
+ if (report.publisher.changed) {
401
+ log(chalk.red(` ⚠ Cambió de publicador: "${report.publisher.from ?? 'N/A'}" → "${report.publisher.to ?? 'N/A'}"`));
402
+ }
403
+ else {
404
+ log(chalk.gray(` Sin cambios (${report.publisher.to ?? 'mismo publicador'})`));
405
+ }
406
+ if (report.maintainers.added.length > 0 || report.maintainers.removed.length > 0) {
407
+ log(chalk.bold('\nMantenedores:'));
408
+ if (report.maintainers.added.length > 0)
409
+ log(chalk.yellow(` + Añadidos: ${report.maintainers.added.join(', ')}`));
410
+ if (report.maintainers.removed.length > 0)
411
+ log(chalk.gray(` - Removidos: ${report.maintainers.removed.join(', ')}`));
412
+ }
413
+ if (report.installScripts.added.length > 0 ||
414
+ report.installScripts.removed.length > 0 ||
415
+ report.installScripts.modified.length > 0) {
416
+ log(chalk.bold('\nLifecycle Scripts:'));
417
+ for (const s of report.installScripts.added) {
418
+ const prefix = s.suspicious ? chalk.red.bold(' + [SOSPECHOSO]') : chalk.yellow(' +');
419
+ log(`${prefix} ${s.stage}: ${s.to}`);
420
+ }
421
+ for (const s of report.installScripts.modified) {
422
+ const prefix = s.suspicious ? chalk.red.bold(' ~ [SOSPECHOSO]') : chalk.yellow(' ~');
423
+ log(`${prefix} ${s.stage}: ${s.from} → ${s.to}`);
424
+ }
425
+ for (const s of report.installScripts.removed) {
426
+ log(chalk.gray(` - ${s.stage}: ${s.from}`));
427
+ }
428
+ }
429
+ if (report.dependencies.added.length > 0 ||
430
+ report.dependencies.removed.length > 0 ||
431
+ report.dependencies.modified.length > 0) {
432
+ log(chalk.bold('\nDependencias:'));
433
+ for (const d of report.dependencies.added)
434
+ log(chalk.green(` + ${d.name}@${d.to}`));
435
+ for (const d of report.dependencies.modified)
436
+ log(chalk.yellow(` ~ ${d.name}: ${d.from} → ${d.to}`));
437
+ for (const d of report.dependencies.removed)
438
+ log(chalk.gray(` - ${d.name}`));
439
+ }
440
+ if (report.alerts.length > 0) {
441
+ log(chalk.bold('\nAlertas de Seguridad:'));
442
+ for (const a of report.alerts)
443
+ log(` - ${chalk.yellow(a)}`);
444
+ }
445
+ if (report.aiAnalysis) {
446
+ log(chalk.bold.cyan('\n🤖 Análisis Forense con IA:'));
447
+ log(report.aiAnalysis);
448
+ }
449
+ log('');
450
+ process.exitCode = report.riskLevel === 'critical' ? EXIT.FAIL_UNDER : EXIT.OK;
451
+ }
452
+ catch (err) {
453
+ log(chalk.red(`\n✖ Error inspeccionando diff: ${err.message}`));
454
+ process.exitCode = EXIT.FATAL;
455
+ }
456
+ });
225
457
  // Evita que Commander haga process.exit(1) en errores de uso (colisionaría con --fail-under).
226
458
  program.exitOverride();
227
459
  try {
@@ -229,7 +461,6 @@ async function main() {
229
461
  }
230
462
  catch (err) {
231
463
  if (err instanceof CommanderError) {
232
- // Commander ya imprimió el mensaje (o la ayuda/versión).
233
464
  process.exitCode = err.exitCode === 0 ? EXIT.OK : EXIT.FATAL;
234
465
  return;
235
466
  }
@@ -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;
@@ -91,6 +124,7 @@ export function extractNpmInfo(name, doc) {
91
124
  latestPublisher,
92
125
  previousPublishers,
93
126
  maintainersChange,
127
+ installScripts: inspectInstallScripts(latestDoc?.scripts),
94
128
  };
95
129
  }
96
130
  export class NpmClient {
@@ -0,0 +1,223 @@
1
+ /**
2
+ * Comparador de seguridad entre versiones de un paquete (ghostdeps diff <pkg>).
3
+ * Detecta cambios bruscos entre versiones: cambio de publicador (_npmUser),
4
+ * incorporación de scripts de instalación sospechosos, dependencias nuevas,
5
+ * alteración de repositorios o bifurcación de mantenimiento.
6
+ */
7
+ import { inspectInstallScripts, registryUrl } from '../clients/npm.js';
8
+ import { fetchJson } from '../clients/http.js';
9
+ import { detectAiConfig, queryAnthropic, queryGemini, queryOpenAI } from '../ai/advisor.js';
10
+ function parsePerson(p) {
11
+ if (!p)
12
+ return null;
13
+ if (typeof p === 'string')
14
+ return p.replace(/\s*<.*$/, '').trim() || null;
15
+ if (typeof p === 'object' && p !== null) {
16
+ const obj = p;
17
+ return obj.name ?? obj.email ?? null;
18
+ }
19
+ return null;
20
+ }
21
+ function parseRepoUrl(repo) {
22
+ if (!repo)
23
+ return null;
24
+ if (typeof repo === 'string')
25
+ return repo;
26
+ if (typeof repo === 'object' && repo !== null && 'url' in repo) {
27
+ return String(repo.url ?? '');
28
+ }
29
+ return null;
30
+ }
31
+ /**
32
+ * Función pura que calcula el diff de seguridad entre dos versiones de un packument.
33
+ */
34
+ export function compareVersions(packageName, doc, fromVer, toVer) {
35
+ const versions = doc.versions ?? {};
36
+ const time = doc.time ?? {};
37
+ // Orden cronológico
38
+ const chronological = Object.entries(time)
39
+ .filter(([v]) => v !== 'created' && v !== 'modified' && versions[v] !== undefined)
40
+ .sort(([, a], [, b]) => Date.parse(a) - Date.parse(b))
41
+ .map(([v]) => v);
42
+ const targetTo = toVer ??
43
+ doc['dist-tags']?.latest ??
44
+ chronological[chronological.length - 1] ??
45
+ '';
46
+ if (!versions[targetTo]) {
47
+ throw new Error(`La versión destino "${targetTo}" no existe en el registro para ${packageName}`);
48
+ }
49
+ let targetFrom = fromVer;
50
+ if (!targetFrom) {
51
+ const idx = chronological.indexOf(targetTo);
52
+ if (idx > 0) {
53
+ targetFrom = chronological[idx - 1];
54
+ }
55
+ else {
56
+ // Si es la primera versión o no está en cronología, buscar cualquier otra previa
57
+ targetFrom = chronological.find((v) => v !== targetTo) ?? targetTo;
58
+ }
59
+ }
60
+ const vFromDoc = versions[targetFrom] ?? {};
61
+ const vToDoc = versions[targetTo] ?? {};
62
+ // 1. Publisher
63
+ const pubFrom = parsePerson(vFromDoc._npmUser);
64
+ const pubTo = parsePerson(vToDoc._npmUser);
65
+ const publisherChanged = Boolean(pubFrom && pubTo && pubFrom !== pubTo);
66
+ // 2. Maintainers
67
+ const parseMaint = (docPart) => {
68
+ const m = docPart.maintainers;
69
+ if (!m)
70
+ return [];
71
+ const arr = Array.isArray(m) ? m : [m];
72
+ return [...new Set(arr.map(parsePerson).filter((n) => !!n))].sort();
73
+ };
74
+ const maintFrom = parseMaint(vFromDoc);
75
+ const maintTo = parseMaint(vToDoc);
76
+ const maintAdded = maintTo.filter((m) => !maintFrom.includes(m));
77
+ const maintRemoved = maintFrom.filter((m) => !maintTo.includes(m));
78
+ // 3. Install scripts
79
+ const scriptsFrom = vFromDoc.scripts ?? {};
80
+ const scriptsTo = vToDoc.scripts ?? {};
81
+ const stages = ['preinstall', 'install', 'postinstall'];
82
+ const scriptsAdded = [];
83
+ const scriptsRemoved = [];
84
+ const scriptsModified = [];
85
+ const inspTo = inspectInstallScripts(scriptsTo);
86
+ const inspFrom = inspectInstallScripts(scriptsFrom);
87
+ for (const st of stages) {
88
+ const s1 = scriptsFrom[st];
89
+ const s2 = scriptsTo[st];
90
+ if (!s1 && s2) {
91
+ const isSusp = inspectInstallScripts({ [st]: s2 }).suspicious;
92
+ scriptsAdded.push({ stage: st, to: s2, suspicious: isSusp });
93
+ }
94
+ else if (s1 && !s2) {
95
+ scriptsRemoved.push({ stage: st, from: s1 });
96
+ }
97
+ else if (s1 && s2 && s1 !== s2) {
98
+ const isSusp = inspectInstallScripts({ [st]: s2 }).suspicious;
99
+ scriptsModified.push({ stage: st, from: s1, to: s2, suspicious: isSusp });
100
+ }
101
+ }
102
+ const hasSuspiciousScripts = inspTo.suspicious && !inspFrom.suspicious;
103
+ // 4. Dependencies
104
+ const depsFrom = vFromDoc.dependencies ?? {};
105
+ const depsTo = vToDoc.dependencies ?? {};
106
+ const depsAdded = [];
107
+ const depsRemoved = [];
108
+ const depsModified = [];
109
+ const allDepKeys = new Set([...Object.keys(depsFrom), ...Object.keys(depsTo)]);
110
+ for (const k of allDepKeys) {
111
+ if (!depsFrom[k] && depsTo[k]) {
112
+ depsAdded.push({ name: k, to: depsTo[k] });
113
+ }
114
+ else if (depsFrom[k] && !depsTo[k]) {
115
+ depsRemoved.push({ name: k, from: depsFrom[k] });
116
+ }
117
+ else if (depsFrom[k] !== depsTo[k]) {
118
+ depsModified.push({ name: k, from: depsFrom[k], to: depsTo[k] });
119
+ }
120
+ }
121
+ // 5. Repository
122
+ const repoFrom = parseRepoUrl(vFromDoc.repository ?? doc.repository);
123
+ const repoTo = parseRepoUrl(vToDoc.repository ?? doc.repository);
124
+ const repoChanged = Boolean(repoFrom && repoTo && repoFrom !== repoTo);
125
+ // 6. Riesgo y Alertas
126
+ const alerts = [];
127
+ let riskLevel = 'low';
128
+ if (publisherChanged) {
129
+ alerts.push(`Cambio de publicador: "${pubFrom}" → "${pubTo}"`);
130
+ riskLevel = 'medium';
131
+ }
132
+ if (maintAdded.length > 0) {
133
+ alerts.push(`Nuevos mantenedores añadidos: ${maintAdded.join(', ')}`);
134
+ }
135
+ if (repoChanged) {
136
+ alerts.push(`El repositorio fue modificado: "${repoFrom}" → "${repoTo}"`);
137
+ if (riskLevel === 'low')
138
+ riskLevel = 'medium';
139
+ }
140
+ if (scriptsAdded.length > 0 || scriptsModified.length > 0) {
141
+ alerts.push(`Se añadieron o alteraron scripts de instalación en el ciclo de vida`);
142
+ riskLevel = 'medium';
143
+ }
144
+ if (hasSuspiciousScripts) {
145
+ alerts.push(`ALERTA: Se incorporaron scripts de instalación altamente sospechosos (descargas, shell o eval)`);
146
+ riskLevel = 'critical';
147
+ }
148
+ if (publisherChanged && hasSuspiciousScripts) {
149
+ alerts.push(`CRÍTICO: Cambio simultáneo de publicador y adición de scripts sospechosos (Patrón claro de Account Hijacking)`);
150
+ riskLevel = 'critical';
151
+ }
152
+ else if (publisherChanged && scriptsAdded.length > 0) {
153
+ riskLevel = 'high';
154
+ }
155
+ return {
156
+ packageName,
157
+ fromVersion: targetFrom,
158
+ toVersion: targetTo,
159
+ publisher: { from: pubFrom, to: pubTo, changed: publisherChanged },
160
+ maintainers: { added: maintAdded, removed: maintRemoved },
161
+ installScripts: {
162
+ added: scriptsAdded,
163
+ removed: scriptsRemoved,
164
+ modified: scriptsModified,
165
+ hasSuspicious: inspTo.suspicious,
166
+ },
167
+ dependencies: { added: depsAdded, removed: depsRemoved, modified: depsModified },
168
+ repository: { from: repoFrom, to: repoTo, changed: repoChanged },
169
+ riskLevel,
170
+ alerts,
171
+ };
172
+ }
173
+ /**
174
+ * Consulta la API y opcionalmente la IA para analizar el diff entre versiones.
175
+ */
176
+ export async function inspectPackageDiff(packageName, options = {}) {
177
+ const timeoutMs = options.timeoutMs ?? 15000;
178
+ const retries = options.retries ?? 2;
179
+ const userAgent = options.userAgent ?? 'ghostdeps/diff';
180
+ const { data } = await fetchJson(registryUrl(packageName), {
181
+ timeoutMs,
182
+ retries,
183
+ headers: { accept: 'application/json', 'user-agent': userAgent },
184
+ });
185
+ const report = compareVersions(packageName, data, options.from, options.to);
186
+ if (options.ai) {
187
+ const aiConfig = detectAiConfig(options.aiOptions);
188
+ if (aiConfig) {
189
+ const prompt = `Actúa como analista de seguridad de software y malware en npm.
190
+ Analiza la siguiente diferencia entre dos versiones del paquete "${report.packageName}":
191
+ - Versión base: ${report.fromVersion}
192
+ - Versión nueva: ${report.toVersion}
193
+ - Publicador anterior: ${report.publisher.from ?? 'N/A'}
194
+ - Publicador nuevo: ${report.publisher.to ?? 'N/A'} (¿Cambió?: ${report.publisher.changed ? 'SÍ' : 'NO'})
195
+ - Scripts de ciclo de vida añadidos/modificados: ${JSON.stringify(report.installScripts, null, 2)}
196
+ - Dependencias añadidas: ${JSON.stringify(report.dependencies.added, null, 2)}
197
+ - Repositorio alterado: ${report.repository.changed ? 'SÍ' : 'NO'}
198
+ - Alertas automáticas: ${report.alerts.join('; ')}
199
+
200
+ Emite un diagnóstico forense conciso (máximo 3 párrafos en español):
201
+ 1. ¿Presenta indicios de toma de control de cuenta (account hijacking) o inyección maliciosa?
202
+ 2. ¿Qué riesgos específicos conllevan los cambios observados?
203
+ 3. Recomendación explícita: Aceptar actualización, bloquear en lockfile con override, o reportar a npm security.`;
204
+ try {
205
+ let aiText;
206
+ if (aiConfig.provider === 'gemini') {
207
+ aiText = await queryGemini(aiConfig.apiKey, aiConfig.model, prompt, 30000);
208
+ }
209
+ else if (aiConfig.provider === 'anthropic') {
210
+ aiText = await queryAnthropic(aiConfig.apiKey, aiConfig.model, prompt, 30000);
211
+ }
212
+ else {
213
+ aiText = await queryOpenAI(aiConfig.apiKey, aiConfig.model, prompt, 30000);
214
+ }
215
+ report.aiAnalysis = aiText;
216
+ }
217
+ catch (err) {
218
+ report.aiAnalysis = `(Error al consultar IA: ${err.message})`;
219
+ }
220
+ }
221
+ }
222
+ return report;
223
+ }