@efraindrummer/ghostdeps 0.4.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 +10 -0
- package/README.md +44 -3
- package/dist/analyzer.js +4 -1
- package/dist/cli.js +66 -1
- package/dist/clients/npm.js +14 -0
- package/dist/config.js +35 -1
- package/dist/diff/inspect.js +13 -13
- package/dist/hooks/githook.js +84 -0
- package/dist/notifications/webhook.js +98 -0
- package/dist/parser/lockfile.js +43 -12
- package/dist/render/sarif.js +12 -0
- package/dist/scoring/scoring.js +12 -0
- package/dist/scoring/signals.js +10 -1
- package/dist/security/licenses.js +58 -0
- package/dist/security/typosquatting.js +181 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,16 @@
|
|
|
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
|
+
|
|
5
15
|
## [0.4.0] - 2026-11-25
|
|
6
16
|
|
|
7
17
|
### 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.
|
|
12
|
+
👻 GhostDeps v0.5.0 · mi-app
|
|
13
13
|
┌─────────────────────────────┬───────┬──────────────────┬───────────────┬──────────────────────────────────────────────┐
|
|
14
14
|
│ Paquete │ Score │ Días últ. commit │ Mant. activos │ Alerta principal │
|
|
15
15
|
├─────────────────────────────┼───────┼──────────────────┼───────────────┼──────────────────────────────────────────────┤
|
|
@@ -131,6 +131,9 @@ ghostdeps --version
|
|
|
131
131
|
| `--ai-provider <prov>` | Proveedor de IA: `gemini`, `anthropic` u `openai` | autodetección |
|
|
132
132
|
| `--ai-model <model>` | Modelo específico de IA a consultar | por defecto del proveedor |
|
|
133
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 | — |
|
|
134
137
|
| `--no-cache` | No lee ni escribe la caché en disco | caché activa |
|
|
135
138
|
| `--cache-ttl <horas>` | TTL de la caché | `24` |
|
|
136
139
|
| `--timeout <ms>` | Timeout por petición | `15000` |
|
|
@@ -215,7 +218,7 @@ Cómo funciona:
|
|
|
215
218
|
- Reproduce la resolución de Node (`node_modules` anidados y *hoisting*) sobre el lockfile y recorre el grafo en anchura.
|
|
216
219
|
- Cada paquete se analiza **una sola vez** aunque aparezca varias veces en el árbol (se deduplica por nombre).
|
|
217
220
|
- Los paquetes instalados desde git o `file:` se marcan como *No evaluable*; los *workspaces* (`link: true`) no se recorren.
|
|
218
|
-
- Soporta `package-lock.json` (npm ≥ 7 v2/v3), `yarn.lock` (Yarn v1) y `pnpm-lock.yaml` (pnpm v5/v6/v9).
|
|
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).
|
|
219
222
|
|
|
220
223
|
> [!TIP]
|
|
221
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.
|
|
@@ -418,6 +421,8 @@ Reglas SARIF incluidas:
|
|
|
418
421
|
- `GD009`: Patrón combinado de secuestro/hijacking (`error`)
|
|
419
422
|
- `GD010`: Publicación desactualizada en npm (`note`)
|
|
420
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`)
|
|
421
426
|
|
|
422
427
|
#### Reporte Visual Autónomo en HTML (`--html`)
|
|
423
428
|
|
|
@@ -493,7 +498,7 @@ jobs:
|
|
|
493
498
|
- uses: actions/checkout@v4
|
|
494
499
|
|
|
495
500
|
- name: Run GhostDeps Audit
|
|
496
|
-
uses: efraindrummer/ghostdeps@v0.
|
|
501
|
+
uses: efraindrummer/ghostdeps@v0.5.0
|
|
497
502
|
with:
|
|
498
503
|
fail-under: '60'
|
|
499
504
|
transitive: 'true'
|
|
@@ -501,6 +506,42 @@ jobs:
|
|
|
501
506
|
github-token: ${{ secrets.GITHUB_TOKEN }}
|
|
502
507
|
```
|
|
503
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
|
+
```
|
|
544
|
+
|
|
504
545
|
### Cómo leer la tabla
|
|
505
546
|
|
|
506
547
|
| Columna | Significado |
|
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
|
@@ -15,7 +15,9 @@ import { createIgnoreMatcher, loadConfig } from './config.js';
|
|
|
15
15
|
import { inspectPackageDiff } from './diff/inspect.js';
|
|
16
16
|
import { GhostDepsError, errorMessage } from './errors.js';
|
|
17
17
|
import { applyFixPlan, createFixPlan, detectPackageManager, generateProposals } from './fix/remediator.js';
|
|
18
|
+
import { installGitHook } from './hooks/githook.js';
|
|
18
19
|
import { startMcpServer } from './mcp/server.js';
|
|
20
|
+
import { sendWebhookNotification } from './notifications/webhook.js';
|
|
19
21
|
import { readLockfile, resolveTransitive } from './parser/lockfile.js';
|
|
20
22
|
import { readManifest } from './parser/manifest.js';
|
|
21
23
|
import { renderHtml } from './render/html.js';
|
|
@@ -122,7 +124,15 @@ async function run(opts, command, version) {
|
|
|
122
124
|
now: () => now,
|
|
123
125
|
});
|
|
124
126
|
const interactive = !quiet && process.stderr.isTTY;
|
|
125
|
-
const reports = await analyzeAll(toAnalyze, {
|
|
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) => {
|
|
126
136
|
if (interactive)
|
|
127
137
|
process.stderr.write(`\r\x1b[2K${chalk.gray(`Analizando ${done}/${total}: ${name}`)}`);
|
|
128
138
|
});
|
|
@@ -227,6 +237,28 @@ async function run(opts, command, version) {
|
|
|
227
237
|
else {
|
|
228
238
|
process.stdout.write(`${rendered}\n`);
|
|
229
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
|
+
}
|
|
230
262
|
if (gate.resetAt && gate.resetAt.getTime() > Date.now() && summary.errors > 0) {
|
|
231
263
|
log(chalk.red(`\n✖ Se agotó el rate limit de GitHub (reset ${gate.resetAt.toLocaleTimeString()}). ` +
|
|
232
264
|
'Los paquetes restantes quedaron como error; reintenta luego (los resultados ya obtenidos están en caché) ' +
|
|
@@ -270,17 +302,24 @@ async function main() {
|
|
|
270
302
|
.addOption(new Option('--ai-provider <provider>', 'proveedor de IA a utilizar').choices(['gemini', 'anthropic', 'openai']))
|
|
271
303
|
.option('--ai-model <model>', 'modelo específico de IA a consultar')
|
|
272
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')
|
|
273
308
|
.addHelpText('after', [
|
|
274
309
|
'',
|
|
275
310
|
'Subcomandos:',
|
|
276
311
|
' ghostdeps fix Inyecta overrides/resolutions en package.json para corregir dependencias críticas',
|
|
277
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',
|
|
278
314
|
'',
|
|
279
315
|
'Ejemplos:',
|
|
280
316
|
' ghostdeps --transitive --format html -o reporte.html',
|
|
281
317
|
' ghostdeps --dev --explain',
|
|
282
318
|
' ghostdeps fix --dry-run',
|
|
319
|
+
' ghostdeps hook --fail-under 50',
|
|
283
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"',
|
|
284
323
|
' ghostdeps --ai',
|
|
285
324
|
' ghostdeps --mcp',
|
|
286
325
|
'',
|
|
@@ -454,6 +493,32 @@ async function main() {
|
|
|
454
493
|
process.exitCode = EXIT.FATAL;
|
|
455
494
|
}
|
|
456
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
|
+
});
|
|
457
522
|
// Evita que Commander haga process.exit(1) en errores de uso (colisionaría con --fail-under).
|
|
458
523
|
program.exitOverride();
|
|
459
524
|
try {
|
package/dist/clients/npm.js
CHANGED
|
@@ -112,6 +112,18 @@ export function extractNpmInfo(name, doc) {
|
|
|
112
112
|
: deprecatedRaw === true
|
|
113
113
|
? 'deprecated'
|
|
114
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));
|
|
115
127
|
return {
|
|
116
128
|
name: doc.name ?? name,
|
|
117
129
|
latestVersion,
|
|
@@ -125,6 +137,8 @@ export function extractNpmInfo(name, doc) {
|
|
|
125
137
|
previousPublishers,
|
|
126
138
|
maintainersChange,
|
|
127
139
|
installScripts: inspectInstallScripts(latestDoc?.scripts),
|
|
140
|
+
hasProvenance,
|
|
141
|
+
license,
|
|
128
142
|
};
|
|
129
143
|
}
|
|
130
144
|
export class NpmClient {
|
package/dist/config.js
CHANGED
|
@@ -10,7 +10,20 @@ import path from 'node:path';
|
|
|
10
10
|
import { ConfigError } from './errors.js';
|
|
11
11
|
import { DEFAULT_WEIGHTS, THRESHOLDS } from './scoring/scoring.js';
|
|
12
12
|
export const CONFIG_FILES = ['.ghostdepsrc.json', '.ghostdepsrc'];
|
|
13
|
-
const TOP_LEVEL_KEYS = [
|
|
13
|
+
const TOP_LEVEL_KEYS = [
|
|
14
|
+
'$schema',
|
|
15
|
+
'ignore',
|
|
16
|
+
'failUnder',
|
|
17
|
+
'dev',
|
|
18
|
+
'transitive',
|
|
19
|
+
'depth',
|
|
20
|
+
'concurrency',
|
|
21
|
+
'weights',
|
|
22
|
+
'thresholds',
|
|
23
|
+
'allowedLicenses',
|
|
24
|
+
'deniedLicenses',
|
|
25
|
+
'webhook',
|
|
26
|
+
];
|
|
14
27
|
const NUMERIC_WEIGHTS = [
|
|
15
28
|
'archived',
|
|
16
29
|
'deprecated',
|
|
@@ -19,6 +32,9 @@ const NUMERIC_WEIGHTS = [
|
|
|
19
32
|
'newPublisher',
|
|
20
33
|
'hijackPattern',
|
|
21
34
|
'dormantRevivalDays',
|
|
35
|
+
'suspiciousScripts',
|
|
36
|
+
'typosquatting',
|
|
37
|
+
'licenseViolation',
|
|
22
38
|
];
|
|
23
39
|
const TIER_WEIGHTS = ['abandonment', 'unansweredIssues'];
|
|
24
40
|
const WEIGHT_KEYS = [...NUMERIC_WEIGHTS, ...TIER_WEIGHTS, 'stalePublish', 'busFactor'];
|
|
@@ -135,6 +151,24 @@ export function parseConfig(raw, source) {
|
|
|
135
151
|
config.depth = num(raw.depth, 'depth', source, 1, 100, true);
|
|
136
152
|
if (raw.concurrency !== undefined)
|
|
137
153
|
config.concurrency = num(raw.concurrency, 'concurrency', source, 1, 32, true);
|
|
154
|
+
if (raw.allowedLicenses !== undefined) {
|
|
155
|
+
if (!Array.isArray(raw.allowedLicenses) || raw.allowedLicenses.some((l) => typeof l !== 'string')) {
|
|
156
|
+
throw new ConfigError(`${source}: "allowedLicenses" debe ser un array de licencias (ej. ["MIT", "Apache-2.0"]).`);
|
|
157
|
+
}
|
|
158
|
+
config.allowedLicenses = raw.allowedLicenses.map((l) => l.trim());
|
|
159
|
+
}
|
|
160
|
+
if (raw.deniedLicenses !== undefined) {
|
|
161
|
+
if (!Array.isArray(raw.deniedLicenses) || raw.deniedLicenses.some((l) => typeof l !== 'string')) {
|
|
162
|
+
throw new ConfigError(`${source}: "deniedLicenses" debe ser un array de licencias (ej. ["GPL-3.0"]).`);
|
|
163
|
+
}
|
|
164
|
+
config.deniedLicenses = raw.deniedLicenses.map((l) => l.trim());
|
|
165
|
+
}
|
|
166
|
+
if (raw.webhook !== undefined) {
|
|
167
|
+
if (typeof raw.webhook !== 'string' || !raw.webhook.trim()) {
|
|
168
|
+
throw new ConfigError(`${source}: "webhook" debe ser una URL válida.`);
|
|
169
|
+
}
|
|
170
|
+
config.webhook = raw.webhook.trim();
|
|
171
|
+
}
|
|
138
172
|
return config;
|
|
139
173
|
}
|
|
140
174
|
export function defaultConfig() {
|
package/dist/diff/inspect.js
CHANGED
|
@@ -187,20 +187,20 @@ export async function inspectPackageDiff(packageName, options = {}) {
|
|
|
187
187
|
const aiConfig = detectAiConfig(options.aiOptions);
|
|
188
188
|
if (aiConfig) {
|
|
189
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('; ')}
|
|
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
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.`;
|
|
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
204
|
try {
|
|
205
205
|
let aiText;
|
|
206
206
|
if (aiConfig.provider === 'gemini') {
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generador e instalador de Git Hooks para prevenir la introducción de dependencias
|
|
3
|
+
* fantasmas, secuestradas o con install scripts maliciosos antes de hacer commit.
|
|
4
|
+
*/
|
|
5
|
+
import { chmod, mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
export async function installGitHook(dir, options = {}) {
|
|
8
|
+
const threshold = options.failUnder ?? 50;
|
|
9
|
+
const huskyDir = path.resolve(dir, '.husky');
|
|
10
|
+
const gitDir = path.resolve(dir, '.git');
|
|
11
|
+
let type = 'git';
|
|
12
|
+
let hookPath;
|
|
13
|
+
const isHusky = await (async () => {
|
|
14
|
+
try {
|
|
15
|
+
await readFile(path.join(huskyDir, '_', 'husky.sh'));
|
|
16
|
+
return true;
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
try {
|
|
20
|
+
await readFile(path.join(huskyDir, 'pre-commit'));
|
|
21
|
+
return true;
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
})();
|
|
28
|
+
if (isHusky) {
|
|
29
|
+
type = 'husky';
|
|
30
|
+
hookPath = path.join(huskyDir, 'pre-commit');
|
|
31
|
+
}
|
|
32
|
+
else {
|
|
33
|
+
type = 'git';
|
|
34
|
+
hookPath = path.join(gitDir, 'hooks', 'pre-commit');
|
|
35
|
+
}
|
|
36
|
+
let alreadyExisted = false;
|
|
37
|
+
let existingContent = '';
|
|
38
|
+
try {
|
|
39
|
+
existingContent = await readFile(hookPath, 'utf8');
|
|
40
|
+
alreadyExisted = true;
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
alreadyExisted = false;
|
|
44
|
+
}
|
|
45
|
+
const hookCommand = `npx --yes @efraindrummer/ghostdeps --fail-under ${threshold}`;
|
|
46
|
+
let newContent = '';
|
|
47
|
+
if (type === 'husky') {
|
|
48
|
+
if (existingContent.includes('ghostdeps')) {
|
|
49
|
+
newContent = existingContent;
|
|
50
|
+
}
|
|
51
|
+
else {
|
|
52
|
+
newContent = existingContent ? `${existingContent.trim()}\n${hookCommand}\n` : `${hookCommand}\n`;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
else {
|
|
56
|
+
// Git hook standard
|
|
57
|
+
if (existingContent.includes('ghostdeps')) {
|
|
58
|
+
newContent = existingContent;
|
|
59
|
+
}
|
|
60
|
+
else if (existingContent) {
|
|
61
|
+
newContent = `${existingContent.trim()}\n\n# GhostDeps Quality Gate\n${hookCommand}\n`;
|
|
62
|
+
}
|
|
63
|
+
else {
|
|
64
|
+
newContent = `#!/bin/sh\n# GhostDeps Pre-commit Hook\n${hookCommand}\n`;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
if (!options.dryRun) {
|
|
68
|
+
await mkdir(path.dirname(hookPath), { recursive: true });
|
|
69
|
+
await writeFile(hookPath, newContent, 'utf8');
|
|
70
|
+
try {
|
|
71
|
+
await chmod(hookPath, 0o755);
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
// Ignorar en sistemas que no soportan chmod (ej. Windows FAT/NTFS sin POSIX)
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return {
|
|
78
|
+
success: true,
|
|
79
|
+
hookPath,
|
|
80
|
+
type,
|
|
81
|
+
content: newContent,
|
|
82
|
+
alreadyExisted,
|
|
83
|
+
};
|
|
84
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
export async function sendWebhookNotification(opts) {
|
|
2
|
+
const { webhookUrl, projectName, version, summary, criticalPackages, failUnder, failingCount } = opts;
|
|
3
|
+
const timeoutMs = opts.timeoutMs ?? 10000;
|
|
4
|
+
const projectTitle = projectName ? `Proyecto: ${projectName}` : 'Auditoría GhostDeps';
|
|
5
|
+
const hasIssues = summary.critical > 0 || (failingCount !== undefined && failingCount > 0);
|
|
6
|
+
const statusEmoji = hasIssues ? '🚨' : '✅';
|
|
7
|
+
const colorHex = hasIssues ? '#ef4444' : '#10b981';
|
|
8
|
+
let body;
|
|
9
|
+
if (webhookUrl.includes('hooks.slack.com')) {
|
|
10
|
+
// Formato Slack Blocks
|
|
11
|
+
const critList = criticalPackages.length > 0
|
|
12
|
+
? criticalPackages
|
|
13
|
+
.slice(0, 8)
|
|
14
|
+
.map((p) => `• *${p.name}* (Score: ${p.score}) — ${p.mainAlert ?? 'Riesgo alto'}`)
|
|
15
|
+
.join('\n')
|
|
16
|
+
: 'Ningún paquete crítico detectado.';
|
|
17
|
+
body = {
|
|
18
|
+
text: `${statusEmoji} GhostDeps v${version}: ${projectTitle}`,
|
|
19
|
+
blocks: [
|
|
20
|
+
{
|
|
21
|
+
type: 'header',
|
|
22
|
+
text: {
|
|
23
|
+
type: 'plain_text',
|
|
24
|
+
text: `${statusEmoji} GhostDeps v${version} — ${projectName ?? 'Auditoría'}`,
|
|
25
|
+
emoji: true,
|
|
26
|
+
},
|
|
27
|
+
},
|
|
28
|
+
{
|
|
29
|
+
type: 'section',
|
|
30
|
+
fields: [
|
|
31
|
+
{ type: 'mrkdwn', text: `*Total:* ${summary.total}` },
|
|
32
|
+
{ type: 'mrkdwn', text: `*🔴 Críticos:* ${summary.critical}` },
|
|
33
|
+
{ type: 'mrkdwn', text: `*🟡 Precaución:* ${summary.caution}` },
|
|
34
|
+
{ type: 'mrkdwn', text: `*🟢 Saludables:* ${summary.healthy}` },
|
|
35
|
+
],
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
type: 'section',
|
|
39
|
+
text: {
|
|
40
|
+
type: 'mrkdwn',
|
|
41
|
+
text: `*Detalle de Dependencias en Riesgo:*\n${critList}`,
|
|
42
|
+
},
|
|
43
|
+
},
|
|
44
|
+
],
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
else if (webhookUrl.includes('discord.com/api/webhooks')) {
|
|
48
|
+
// Formato Discord Embeds
|
|
49
|
+
const critList = criticalPackages.length > 0
|
|
50
|
+
? criticalPackages
|
|
51
|
+
.slice(0, 8)
|
|
52
|
+
.map((p) => `• **${p.name}** (Score: ${p.score}) — ${p.mainAlert ?? 'Riesgo alto'}`)
|
|
53
|
+
.join('\n')
|
|
54
|
+
: 'Ningún paquete crítico detectado.';
|
|
55
|
+
body = {
|
|
56
|
+
content: `${statusEmoji} **GhostDeps Security Alert** — ${projectName ?? 'Auditoría'}`,
|
|
57
|
+
embeds: [
|
|
58
|
+
{
|
|
59
|
+
title: `Resultados de Auditoría (v${version})`,
|
|
60
|
+
color: hasIssues ? 0xef4444 : 0x10b981,
|
|
61
|
+
fields: [
|
|
62
|
+
{ name: 'Total', value: String(summary.total), inline: true },
|
|
63
|
+
{ name: '🔴 Críticos', value: String(summary.critical), inline: true },
|
|
64
|
+
{ name: '🟡 Precaución', value: String(summary.caution), inline: true },
|
|
65
|
+
{ name: '🟢 Saludables', value: String(summary.healthy), inline: true },
|
|
66
|
+
{ name: 'Dependencias Críticas', value: critList, inline: false },
|
|
67
|
+
],
|
|
68
|
+
timestamp: new Date().toISOString(),
|
|
69
|
+
},
|
|
70
|
+
],
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
else {
|
|
74
|
+
// Formato JSON Genérico
|
|
75
|
+
body = {
|
|
76
|
+
tool: 'ghostdeps',
|
|
77
|
+
version,
|
|
78
|
+
projectName,
|
|
79
|
+
timestamp: new Date().toISOString(),
|
|
80
|
+
summary,
|
|
81
|
+
failUnder: failUnder ?? null,
|
|
82
|
+
failingCount: failingCount ?? 0,
|
|
83
|
+
criticalPackages,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
try {
|
|
87
|
+
const res = await fetch(webhookUrl, {
|
|
88
|
+
method: 'POST',
|
|
89
|
+
headers: { 'content-type': 'application/json' },
|
|
90
|
+
body: JSON.stringify(body),
|
|
91
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
92
|
+
});
|
|
93
|
+
return res.ok;
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
}
|
package/dist/parser/lockfile.js
CHANGED
|
@@ -49,13 +49,22 @@ export function parseYarnLock(content) {
|
|
|
49
49
|
const trimmed = rawLine.trim();
|
|
50
50
|
if (!trimmed || trimmed.startsWith('#'))
|
|
51
51
|
continue;
|
|
52
|
-
// Header de nivel superior (ej. "foo@^1.0.0", "foo@^1.2.0":)
|
|
52
|
+
// Header de nivel superior (ej. "foo@^1.0.0", "foo@^1.2.0": o Yarn Berry "foo@npm:^1.0.0":)
|
|
53
53
|
if (!rawLine.startsWith(' ') && trimmed.endsWith(':')) {
|
|
54
54
|
flush();
|
|
55
55
|
const headerStr = trimmed.slice(0, -1);
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
const
|
|
56
|
+
if (headerStr.startsWith('__metadata'))
|
|
57
|
+
continue;
|
|
58
|
+
const rawParts = headerStr.split(',').map((p) => unquote(p.trim()));
|
|
59
|
+
const allHeaders = [];
|
|
60
|
+
for (const p of rawParts) {
|
|
61
|
+
allHeaders.push(p);
|
|
62
|
+
if (p.includes('@npm:')) {
|
|
63
|
+
allHeaders.push(p.replace(/@npm:/g, '@'));
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
currentHeaders = allHeaders;
|
|
67
|
+
const first = (rawParts[0] ?? '').replace(/@npm:/g, '@');
|
|
59
68
|
const at = first.lastIndexOf('@');
|
|
60
69
|
const name = at > 0 ? first.slice(0, at) : first;
|
|
61
70
|
currentPkg = { name, dependencies: {}, optionalDependencies: {} };
|
|
@@ -66,11 +75,11 @@ export function parseYarnLock(content) {
|
|
|
66
75
|
// Propiedades directas (2 espacios de indentación)
|
|
67
76
|
if (rawLine.startsWith(' ') && !rawLine.startsWith(' ')) {
|
|
68
77
|
section = 'none';
|
|
69
|
-
if (trimmed.startsWith('version ')) {
|
|
70
|
-
currentPkg.version = unquote(trimmed.
|
|
78
|
+
if (trimmed.startsWith('version ') || trimmed.startsWith('version:')) {
|
|
79
|
+
currentPkg.version = unquote(trimmed.replace(/^version:?\s*/, ''));
|
|
71
80
|
}
|
|
72
|
-
else if (trimmed.startsWith('resolved ')) {
|
|
73
|
-
currentPkg.resolved = unquote(trimmed.
|
|
81
|
+
else if (trimmed.startsWith('resolved ') || trimmed.startsWith('resolved:') || trimmed.startsWith('resolution:')) {
|
|
82
|
+
currentPkg.resolved = unquote(trimmed.replace(/^(resolved|resolution):?\s*/, ''));
|
|
74
83
|
}
|
|
75
84
|
else if (trimmed === 'dependencies:') {
|
|
76
85
|
section = 'dependencies';
|
|
@@ -82,10 +91,25 @@ export function parseYarnLock(content) {
|
|
|
82
91
|
}
|
|
83
92
|
// Sub-claves de dependencias (4 espacios de indentación)
|
|
84
93
|
if (rawLine.startsWith(' ') && (section === 'dependencies' || section === 'optionalDependencies')) {
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
94
|
+
let depName = '';
|
|
95
|
+
let depSpec = '';
|
|
96
|
+
if (trimmed.includes(':')) {
|
|
97
|
+
// Yarn Berry format (name: spec)
|
|
98
|
+
const colon = trimmed.indexOf(':');
|
|
99
|
+
depName = unquote(trimmed.slice(0, colon).trim());
|
|
100
|
+
depSpec = unquote(trimmed.slice(colon + 1).trim());
|
|
101
|
+
if (depSpec.startsWith('npm:'))
|
|
102
|
+
depSpec = depSpec.slice(4);
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
// Yarn v1 format (name spec)
|
|
106
|
+
const parts = trimmed.split(/\s+/);
|
|
107
|
+
if (parts.length >= 2) {
|
|
108
|
+
depName = unquote(parts[0] ?? '');
|
|
109
|
+
depSpec = unquote(parts.slice(1).join(' '));
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
if (depName && depSpec) {
|
|
89
113
|
if (section === 'dependencies') {
|
|
90
114
|
currentPkg.dependencies[depName] = depSpec;
|
|
91
115
|
}
|
|
@@ -313,9 +337,16 @@ function resolveYarnTransitive(lock, direct, options) {
|
|
|
313
337
|
const result = [];
|
|
314
338
|
const findEntry = (name, spec) => {
|
|
315
339
|
if (spec) {
|
|
340
|
+
const cleanSpec = spec.startsWith('npm:') ? spec.slice(4) : spec;
|
|
316
341
|
const directKey = `${name}@${spec}`;
|
|
317
342
|
if (entries.has(directKey))
|
|
318
343
|
return entries.get(directKey);
|
|
344
|
+
const cleanKey = `${name}@${cleanSpec}`;
|
|
345
|
+
if (entries.has(cleanKey))
|
|
346
|
+
return entries.get(cleanKey);
|
|
347
|
+
const berryKey = `${name}@npm:${cleanSpec}`;
|
|
348
|
+
if (entries.has(berryKey))
|
|
349
|
+
return entries.get(berryKey);
|
|
319
350
|
}
|
|
320
351
|
const prefix = `${name}@`;
|
|
321
352
|
for (const [k, v] of entries) {
|
package/dist/render/sarif.js
CHANGED
|
@@ -72,6 +72,18 @@ export const SARIF_RULES = {
|
|
|
72
72
|
shortDescription: { text: 'Script de ciclo de vida de instalación potencialmente peligroso (pre/install/postinstall)' },
|
|
73
73
|
defaultConfiguration: { level: 'error' },
|
|
74
74
|
},
|
|
75
|
+
'typosquatting': {
|
|
76
|
+
id: 'GD012',
|
|
77
|
+
name: 'TyposquattingSuspect',
|
|
78
|
+
shortDescription: { text: 'Posible intento de typosquatting o suplantación de paquete popular' },
|
|
79
|
+
defaultConfiguration: { level: 'error' },
|
|
80
|
+
},
|
|
81
|
+
'license-violation': {
|
|
82
|
+
id: 'GD013',
|
|
83
|
+
name: 'LicenseComplianceViolation',
|
|
84
|
+
shortDescription: { text: 'Infracción de política de licencias permitidas/denegadas o licencia copyleft' },
|
|
85
|
+
defaultConfiguration: { level: 'warning' },
|
|
86
|
+
},
|
|
75
87
|
};
|
|
76
88
|
export function renderSarif(reports, options) {
|
|
77
89
|
const t = options.thresholds ?? THRESHOLDS;
|
package/dist/scoring/scoring.js
CHANGED
|
@@ -18,6 +18,8 @@ export const DEFAULT_WEIGHTS = Object.freeze({
|
|
|
18
18
|
newPublisher: 15,
|
|
19
19
|
hijackPattern: 15,
|
|
20
20
|
suspiciousScripts: 35,
|
|
21
|
+
typosquatting: 50,
|
|
22
|
+
licenseViolation: 30,
|
|
21
23
|
dormantRevivalDays: 365,
|
|
22
24
|
});
|
|
23
25
|
export const THRESHOLDS = Object.freeze({
|
|
@@ -31,10 +33,12 @@ export const CATEGORY_LABELS = {
|
|
|
31
33
|
};
|
|
32
34
|
/** Prioridad para desempatar la alerta principal cuando dos penalizaciones pesan igual. */
|
|
33
35
|
const PRIORITY = [
|
|
36
|
+
'typosquatting',
|
|
34
37
|
'suspicious-install-scripts',
|
|
35
38
|
'hijack-pattern',
|
|
36
39
|
'archived',
|
|
37
40
|
'deprecated',
|
|
41
|
+
'license-violation',
|
|
38
42
|
'new-publisher',
|
|
39
43
|
'maintainers-changed',
|
|
40
44
|
'abandoned',
|
|
@@ -111,6 +115,14 @@ export function computeScore(s, w = DEFAULT_WEIGHTS, t = THRESHOLDS) {
|
|
|
111
115
|
.join(', ');
|
|
112
116
|
add('suspicious-install-scripts', w.suspiciousScripts ?? 35, `Script de instalación potencialmente peligroso: ${reasons}`);
|
|
113
117
|
}
|
|
118
|
+
// --- Typosquatting / Similitud sospechosa con paquetes populares ---
|
|
119
|
+
if (s.typosquatting) {
|
|
120
|
+
add('typosquatting', w.typosquatting ?? 50, `Posible typosquatting: ${s.typosquatting.similarityReason}`);
|
|
121
|
+
}
|
|
122
|
+
// --- Infracción de políticas de licencias ---
|
|
123
|
+
if (s.licenseDenied) {
|
|
124
|
+
add('license-violation', w.licenseViolation ?? 30, s.licenseDeniedReason ?? 'Infracción de política de licencias de software');
|
|
125
|
+
}
|
|
114
126
|
const total = penalties.reduce((acc, p) => acc + p.points, 0);
|
|
115
127
|
const score = Math.max(0, Math.min(100, 100 - total));
|
|
116
128
|
const sorted = [...penalties].sort((a, b) => b.points - a.points || PRIORITY.indexOf(a.id) - PRIORITY.indexOf(b.id));
|
package/dist/scoring/signals.js
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
1
|
+
import { checkLicenseCompliance } from '../security/licenses.js';
|
|
2
|
+
import { detectTyposquatting } from '../security/typosquatting.js';
|
|
1
3
|
import { daysBetween, daysSince } from '../utils.js';
|
|
2
4
|
/** Convierte datos crudos de npm + GitHub en señales normalizadas para el scoring. */
|
|
3
|
-
export function buildSignals(npm, gh, now) {
|
|
5
|
+
export function buildSignals(npm, gh, now, options = {}) {
|
|
4
6
|
const newPublisher = npm.latestPublisher !== null &&
|
|
5
7
|
npm.previousPublishers.length > 0 &&
|
|
6
8
|
!npm.previousPublishers.includes(npm.latestPublisher);
|
|
9
|
+
const typo = detectTyposquatting(npm.name);
|
|
10
|
+
const lic = checkLicenseCompliance(npm.license, options);
|
|
7
11
|
return {
|
|
8
12
|
daysSinceLastCommit: daysSince(gh.lastCommitAt, now),
|
|
9
13
|
daysSinceLastPublish: daysSince(npm.latestPublishedAt, now),
|
|
@@ -16,5 +20,10 @@ export function buildSignals(npm, gh, now) {
|
|
|
16
20
|
maintainersAdded: npm.maintainersChange?.added ?? [],
|
|
17
21
|
newPublisher,
|
|
18
22
|
installScripts: npm.installScripts,
|
|
23
|
+
typosquatting: typo,
|
|
24
|
+
hasProvenance: npm.hasProvenance,
|
|
25
|
+
license: npm.license,
|
|
26
|
+
licenseDenied: lic.isDenied,
|
|
27
|
+
licenseDeniedReason: lic.reason,
|
|
19
28
|
};
|
|
20
29
|
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Módulo de auditoría y compliance legal de licencias de software.
|
|
3
|
+
* Clasifica licencias permisivas vs copyleft (GPL/AGPL) y evalúa
|
|
4
|
+
* reglas de inclusión/exclusión del proyecto.
|
|
5
|
+
*/
|
|
6
|
+
const COPYLEFT_REGEX = /\b(gpl|agpl|lgpl|sspl|eupl|osl)\b/i;
|
|
7
|
+
/**
|
|
8
|
+
* Normaliza nombres de licencias (ej. "Apache 2.0" -> "Apache-2.0").
|
|
9
|
+
*/
|
|
10
|
+
export function normalizeLicense(lic) {
|
|
11
|
+
if (!lic || !lic.trim())
|
|
12
|
+
return 'UNKNOWN';
|
|
13
|
+
const clean = lic.trim();
|
|
14
|
+
if (/^apache\s*2(\.0)?$/i.test(clean))
|
|
15
|
+
return 'Apache-2.0';
|
|
16
|
+
if (/^bsd\s*3[\s-]*clause$/i.test(clean))
|
|
17
|
+
return 'BSD-3-Clause';
|
|
18
|
+
if (/^bsd\s*2[\s-]*clause$/i.test(clean))
|
|
19
|
+
return 'BSD-2-Clause';
|
|
20
|
+
if (/^mit$/i.test(clean))
|
|
21
|
+
return 'MIT';
|
|
22
|
+
if (/^isc$/i.test(clean))
|
|
23
|
+
return 'ISC';
|
|
24
|
+
return clean;
|
|
25
|
+
}
|
|
26
|
+
export function checkLicenseCompliance(rawLicense, options = {}) {
|
|
27
|
+
const license = normalizeLicense(rawLicense);
|
|
28
|
+
const isUnlicensed = license === 'UNKNOWN' ||
|
|
29
|
+
/^unlicensed$/i.test(license) ||
|
|
30
|
+
/^see license in/i.test(license);
|
|
31
|
+
const isCopyleft = COPYLEFT_REGEX.test(license);
|
|
32
|
+
const allowed = options.allowedLicenses?.map((l) => l.trim().toLowerCase());
|
|
33
|
+
const denied = options.deniedLicenses?.map((l) => l.trim().toLowerCase());
|
|
34
|
+
let isDenied = false;
|
|
35
|
+
let reason;
|
|
36
|
+
const licLower = license.toLowerCase();
|
|
37
|
+
if (denied && denied.some((d) => licLower === d || licLower.includes(d))) {
|
|
38
|
+
isDenied = true;
|
|
39
|
+
reason = `Licencia "${license}" denegada explícitamente por política del proyecto`;
|
|
40
|
+
}
|
|
41
|
+
else if (allowed && allowed.length > 0 && !allowed.some((a) => licLower === a || licLower.includes(a))) {
|
|
42
|
+
isDenied = true;
|
|
43
|
+
reason = `Licencia "${license}" no forma parte de las licencias permitidas`;
|
|
44
|
+
}
|
|
45
|
+
else if (isUnlicensed) {
|
|
46
|
+
reason = 'Dependencia sin licencia formal declarada (riesgo de propiedad intelectual)';
|
|
47
|
+
}
|
|
48
|
+
else if (isCopyleft) {
|
|
49
|
+
reason = `Licencia con cláusula Copyleft (${license}) que puede comprometer código privativo`;
|
|
50
|
+
}
|
|
51
|
+
return {
|
|
52
|
+
license,
|
|
53
|
+
isCopyleft,
|
|
54
|
+
isDenied,
|
|
55
|
+
isUnlicensed,
|
|
56
|
+
reason,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Módulo de detección de Typosquatting y confusión de dependencias.
|
|
3
|
+
* Compara las dependencias analizadas contra un registro de paquetes populares de npm
|
|
4
|
+
* calculando distancia de Levenshtein y normalización de separadores.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* Top 120 paquetes más populares y atacados del ecosistema npm.
|
|
8
|
+
*/
|
|
9
|
+
export const TOP_NPM_PACKAGES = Object.freeze([
|
|
10
|
+
'express',
|
|
11
|
+
'react',
|
|
12
|
+
'react-dom',
|
|
13
|
+
'vue',
|
|
14
|
+
'angular',
|
|
15
|
+
'lodash',
|
|
16
|
+
'axios',
|
|
17
|
+
'chalk',
|
|
18
|
+
'commander',
|
|
19
|
+
'debug',
|
|
20
|
+
'dotenv',
|
|
21
|
+
'moment',
|
|
22
|
+
'request',
|
|
23
|
+
'uuid',
|
|
24
|
+
'winston',
|
|
25
|
+
'typescript',
|
|
26
|
+
'tslib',
|
|
27
|
+
'glob',
|
|
28
|
+
'semver',
|
|
29
|
+
'rxjs',
|
|
30
|
+
'webpack',
|
|
31
|
+
'esbuild',
|
|
32
|
+
'vite',
|
|
33
|
+
'cross-env',
|
|
34
|
+
'core-js',
|
|
35
|
+
'body-parser',
|
|
36
|
+
'cookie-parser',
|
|
37
|
+
'cors',
|
|
38
|
+
'fs-extra',
|
|
39
|
+
'async',
|
|
40
|
+
'yargs',
|
|
41
|
+
'prettier',
|
|
42
|
+
'eslint',
|
|
43
|
+
'postcss',
|
|
44
|
+
'rimraf',
|
|
45
|
+
'mkdirp',
|
|
46
|
+
'minimist',
|
|
47
|
+
'inquirer',
|
|
48
|
+
'nodemon',
|
|
49
|
+
'superagent',
|
|
50
|
+
'mongoose',
|
|
51
|
+
'sequelize',
|
|
52
|
+
'prisma',
|
|
53
|
+
'next',
|
|
54
|
+
'jest',
|
|
55
|
+
'vitest',
|
|
56
|
+
'mocha',
|
|
57
|
+
'chai',
|
|
58
|
+
'bcrypt',
|
|
59
|
+
'jsonwebtoken',
|
|
60
|
+
'passport',
|
|
61
|
+
'socket.io',
|
|
62
|
+
'cheerio',
|
|
63
|
+
'sharp',
|
|
64
|
+
'puppeteer',
|
|
65
|
+
'playwright',
|
|
66
|
+
'babel-core',
|
|
67
|
+
'webpack-cli',
|
|
68
|
+
'ts-node',
|
|
69
|
+
'colors',
|
|
70
|
+
'chokidar',
|
|
71
|
+
'nanoid',
|
|
72
|
+
'ora',
|
|
73
|
+
'nodemailer',
|
|
74
|
+
'ioredis',
|
|
75
|
+
'redis',
|
|
76
|
+
'pg',
|
|
77
|
+
'mysql2',
|
|
78
|
+
'ws',
|
|
79
|
+
'fastify',
|
|
80
|
+
'got',
|
|
81
|
+
'node-fetch',
|
|
82
|
+
'undici',
|
|
83
|
+
'dayjs',
|
|
84
|
+
'date-fns',
|
|
85
|
+
'zod',
|
|
86
|
+
'yup',
|
|
87
|
+
'joi',
|
|
88
|
+
'dotenv-expand',
|
|
89
|
+
'dotenv-safe',
|
|
90
|
+
'commander',
|
|
91
|
+
'minimatch',
|
|
92
|
+
'source-map',
|
|
93
|
+
'path-to-regexp',
|
|
94
|
+
'tar',
|
|
95
|
+
'archiver',
|
|
96
|
+
'adm-zip',
|
|
97
|
+
'yaml',
|
|
98
|
+
'multer',
|
|
99
|
+
'helmet',
|
|
100
|
+
'morgan',
|
|
101
|
+
'node-sass',
|
|
102
|
+
'sass',
|
|
103
|
+
'less',
|
|
104
|
+
'pnpm',
|
|
105
|
+
'yarn',
|
|
106
|
+
'npm',
|
|
107
|
+
]);
|
|
108
|
+
/**
|
|
109
|
+
* Distancia de Levenshtein (número mínimo de inserciones, borrados o sustituciones).
|
|
110
|
+
*/
|
|
111
|
+
export function levenshtein(a, b) {
|
|
112
|
+
if (a === b)
|
|
113
|
+
return 0;
|
|
114
|
+
if (!a.length)
|
|
115
|
+
return b.length;
|
|
116
|
+
if (!b.length)
|
|
117
|
+
return a.length;
|
|
118
|
+
const row = Array.from({ length: b.length + 1 }, (_, i) => i);
|
|
119
|
+
for (let i = 1; i <= a.length; i++) {
|
|
120
|
+
let prev = i;
|
|
121
|
+
for (let j = 1; j <= b.length; j++) {
|
|
122
|
+
const val = a[i - 1] === b[j - 1] ? row[j - 1] : Math.min(row[j - 1], row[j], prev) + 1;
|
|
123
|
+
row[j - 1] = prev;
|
|
124
|
+
prev = val;
|
|
125
|
+
}
|
|
126
|
+
row[b.length] = prev;
|
|
127
|
+
}
|
|
128
|
+
return row[b.length];
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Inspecciona un nombre de paquete para determinar si es un intento de typosquatting.
|
|
132
|
+
*/
|
|
133
|
+
export function detectTyposquatting(packageName, topPackages = TOP_NPM_PACKAGES) {
|
|
134
|
+
const normalizedSuspect = packageName.toLowerCase().trim();
|
|
135
|
+
// Extraer el nombre base si tiene scope (@scope/pkg -> pkg)
|
|
136
|
+
const baseSuspect = normalizedSuspect.startsWith('@')
|
|
137
|
+
? (normalizedSuspect.split('/')[1] ?? normalizedSuspect)
|
|
138
|
+
: normalizedSuspect;
|
|
139
|
+
// Si es exactamente el paquete legítimo, no es typosquatting
|
|
140
|
+
if (topPackages.includes(baseSuspect)) {
|
|
141
|
+
return null;
|
|
142
|
+
}
|
|
143
|
+
const strippedSuspect = baseSuspect.replace(/[-_.]/g, '');
|
|
144
|
+
for (const target of topPackages) {
|
|
145
|
+
const strippedTarget = target.replace(/[-_.]/g, '');
|
|
146
|
+
// 1. Caso separadores omitidos o cambiados: e.g. "crossenv" vs "cross-env", "fsextra" vs "fs-extra"
|
|
147
|
+
if (strippedSuspect === strippedTarget && baseSuspect !== target) {
|
|
148
|
+
return {
|
|
149
|
+
suspectName: packageName,
|
|
150
|
+
targetPackage: target,
|
|
151
|
+
similarityReason: `Nombre idéntico omitiendo o alterando separadores respecto al popular "${target}"`,
|
|
152
|
+
distance: 1,
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
// 2. Distancia de Levenshtein = 1 (e.g. "loadsh" -> "lodash", "cha1k" -> "chalk")
|
|
156
|
+
if (Math.abs(baseSuspect.length - target.length) <= 1 && target.length >= 4) {
|
|
157
|
+
const dist = levenshtein(baseSuspect, target);
|
|
158
|
+
if (dist === 1) {
|
|
159
|
+
return {
|
|
160
|
+
suspectName: packageName,
|
|
161
|
+
targetPackage: target,
|
|
162
|
+
similarityReason: `Difiere por solo 1 carácter del paquete popular "${target}" (posible engaño visual)`,
|
|
163
|
+
distance: 1,
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
// 3. Distancia de Levenshtein = 2 para paquetes largos (>= 8 caracteres)
|
|
168
|
+
if (Math.abs(baseSuspect.length - target.length) <= 2 && target.length >= 8) {
|
|
169
|
+
const dist = levenshtein(baseSuspect, target);
|
|
170
|
+
if (dist === 2) {
|
|
171
|
+
return {
|
|
172
|
+
suspectName: packageName,
|
|
173
|
+
targetPackage: target,
|
|
174
|
+
similarityReason: `Difiere por 2 caracteres del paquete popular "${target}"`,
|
|
175
|
+
distance: 2,
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
return null;
|
|
181
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@efraindrummer/ghostdeps",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Detecta dependencias fantasma (abandonadas, bus factor bajo o con señales de secuestro) evaluando la salud social y de mantenimiento del repositorio origen.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"supply-chain",
|