@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/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 = ['$schema', 'ignore', 'failUnder', 'dev', 'transitive', 'depth', 'concurrency', 'weights', 'thresholds'];
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() {
@@ -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
+ }
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Motor de remediación automática (ghostdeps fix).
3
+ * Genera e inyecta overrides/resolutions en package.json para aislar
4
+ * o actualizar dependencias transitivas vulnerables o fantasmas.
5
+ */
6
+ import { readFile, writeFile } from 'node:fs/promises';
7
+ import path from 'node:path';
8
+ /**
9
+ * Detecta el gestor de paquetes predominante en base al lockfile del proyecto.
10
+ */
11
+ export async function detectPackageManager(dir) {
12
+ const check = async (filename) => {
13
+ try {
14
+ await readFile(path.resolve(dir, filename));
15
+ return true;
16
+ }
17
+ catch {
18
+ return false;
19
+ }
20
+ };
21
+ if (await check('pnpm-lock.yaml'))
22
+ return 'pnpm';
23
+ if (await check('yarn.lock'))
24
+ return 'yarn';
25
+ return 'npm';
26
+ }
27
+ /**
28
+ * Propone soluciones a partir de los reportes de análisis.
29
+ */
30
+ export function generateProposals(reports, customOverrides = {}) {
31
+ const proposals = [];
32
+ // Overrides explícitos proporcionados por el usuario
33
+ for (const [pkgName, targetVersion] of Object.entries(customOverrides)) {
34
+ proposals.push({
35
+ packageName: pkgName,
36
+ currentSpec: 'custom',
37
+ targetVersion,
38
+ reason: 'Override manual indicado por el usuario',
39
+ severity: 'critical',
40
+ });
41
+ }
42
+ for (const r of reports) {
43
+ if (customOverrides[r.name])
44
+ continue;
45
+ // Paquetes críticos o con scripts sospechosos
46
+ if (r.result?.category === 'critical' || r.signals?.installScripts?.suspicious) {
47
+ if (r.npm?.latestVersion && r.npm.latestVersion !== r.spec) {
48
+ const reason = r.signals?.installScripts?.suspicious
49
+ ? 'Posible versión comprometida por scripts de instalación'
50
+ : r.result?.mainAlert?.message ?? 'Dependencia identificada como crítica';
51
+ proposals.push({
52
+ packageName: r.name,
53
+ currentSpec: r.spec,
54
+ targetVersion: r.npm.latestVersion,
55
+ reason,
56
+ severity: 'critical',
57
+ });
58
+ }
59
+ }
60
+ }
61
+ return proposals;
62
+ }
63
+ /**
64
+ * Genera el plan de modificación de package.json según el gestor (npm overrides, yarn resolutions, pnpm.overrides).
65
+ */
66
+ export async function createFixPlan(packageJsonPath, proposals, pm) {
67
+ const raw = await readFile(packageJsonPath, 'utf8');
68
+ const pkgJson = JSON.parse(raw);
69
+ let changesMade = false;
70
+ if (proposals.length > 0) {
71
+ if (pm === 'npm') {
72
+ pkgJson.overrides = pkgJson.overrides ?? {};
73
+ for (const p of proposals) {
74
+ if (pkgJson.overrides[p.packageName] !== p.targetVersion) {
75
+ pkgJson.overrides[p.packageName] = p.targetVersion;
76
+ changesMade = true;
77
+ }
78
+ }
79
+ }
80
+ else if (pm === 'yarn') {
81
+ pkgJson.resolutions = pkgJson.resolutions ?? {};
82
+ for (const p of proposals) {
83
+ if (pkgJson.resolutions[p.packageName] !== p.targetVersion) {
84
+ pkgJson.resolutions[p.packageName] = p.targetVersion;
85
+ changesMade = true;
86
+ }
87
+ }
88
+ }
89
+ else if (pm === 'pnpm') {
90
+ pkgJson.pnpm = pkgJson.pnpm ?? {};
91
+ pkgJson.pnpm.overrides = pkgJson.pnpm.overrides ?? {};
92
+ for (const p of proposals) {
93
+ if (pkgJson.pnpm.overrides[p.packageName] !== p.targetVersion) {
94
+ pkgJson.pnpm.overrides[p.packageName] = p.targetVersion;
95
+ changesMade = true;
96
+ }
97
+ }
98
+ }
99
+ }
100
+ const updatedContent = JSON.stringify(pkgJson, null, 2) + '\n';
101
+ return {
102
+ packageManager: pm,
103
+ packageJsonPath,
104
+ proposals,
105
+ originalContent: raw,
106
+ updatedContent,
107
+ changesMade,
108
+ };
109
+ }
110
+ /**
111
+ * Aplica el plan a disco. Si backup=true genera package.json.bak.
112
+ */
113
+ export async function applyFixPlan(plan, options = {}) {
114
+ if (options.dryRun || !plan.changesMade) {
115
+ return { written: false };
116
+ }
117
+ let backupPath;
118
+ if (options.backup) {
119
+ backupPath = `${plan.packageJsonPath}.bak`;
120
+ await writeFile(backupPath, plan.originalContent, 'utf8');
121
+ }
122
+ await writeFile(plan.packageJsonPath, plan.updatedContent, 'utf8');
123
+ return { written: true, backupPath };
124
+ }
@@ -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
+ }