weavatrix 0.1.1 → 0.1.3

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.
Files changed (42) hide show
  1. package/README.md +117 -21
  2. package/SECURITY.md +31 -0
  3. package/package.json +16 -4
  4. package/skill/SKILL.md +69 -12
  5. package/src/analysis/coverage-reports.js +14 -11
  6. package/src/analysis/dead-check.js +87 -6
  7. package/src/analysis/dep-check.js +84 -8
  8. package/src/analysis/dep-rules.js +74 -8
  9. package/src/analysis/duplicates.compute.js +215 -215
  10. package/src/analysis/duplicates.js +15 -15
  11. package/src/analysis/duplicates.run.js +52 -51
  12. package/src/analysis/duplicates.tokenize.js +182 -182
  13. package/src/analysis/endpoints.js +50 -5
  14. package/src/analysis/graph-analysis.aggregate.js +16 -4
  15. package/src/analysis/internal-audit.collect.js +154 -31
  16. package/src/analysis/internal-audit.reach.js +52 -11
  17. package/src/analysis/internal-audit.run.js +72 -21
  18. package/src/build-graph.js +2 -1
  19. package/src/child-env.js +7 -0
  20. package/src/graph/builder/lang-js.js +66 -23
  21. package/src/graph/internal-builder.build.js +48 -10
  22. package/src/graph/internal-builder.langs.js +49 -3
  23. package/src/graph/internal-builder.resolvers.js +96 -20
  24. package/src/mcp/catalog.mjs +10 -8
  25. package/src/mcp/graph-context.mjs +107 -17
  26. package/src/mcp/sync-payload.mjs +110 -0
  27. package/src/mcp/tools-actions.mjs +42 -18
  28. package/src/mcp/tools-graph.mjs +46 -12
  29. package/src/mcp/tools-health.mjs +42 -18
  30. package/src/mcp/tools-impact.mjs +55 -43
  31. package/src/mcp-rg.mjs +2 -1
  32. package/src/mcp-server.mjs +25 -16
  33. package/src/mcp-source-tools.mjs +16 -5
  34. package/src/process.js +4 -3
  35. package/src/repo-path.js +53 -0
  36. package/src/security/advisory-store.js +51 -7
  37. package/src/security/installed.js +44 -31
  38. package/src/security/malware-heuristics.exclusions.js +134 -134
  39. package/src/security/malware-heuristics.js +15 -15
  40. package/src/security/malware-heuristics.roots.js +142 -142
  41. package/src/security/malware-heuristics.scan.js +85 -85
  42. package/src/security/malware-heuristics.sweep.js +122 -122
@@ -10,6 +10,7 @@
10
10
  import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
11
11
  import { join, dirname } from "node:path";
12
12
  import { homedir } from "node:os";
13
+ import { createHash } from "node:crypto";
13
14
  import { uniqueBy } from "../util.js";
14
15
 
15
16
  export const DEFAULT_STORE = join(homedir(), ".weavatrix", "advisories.json");
@@ -22,6 +23,13 @@ const keyOf = (ecosystem, name) => `${ecosystem}|${ecosystem === "PyPI" ? String
22
23
 
23
24
  const uniquePackages = (pkgs) => uniqueBy(pkgs, (p) => `${p.ecosystem}|${p.name}|${p.version}`);
24
25
 
26
+ export function advisoryQueryFingerprint(installed = []) {
27
+ const rows = uniquePackages(installed.filter((p) => p?.ecosystem && p?.name && p?.version && OSV_SUPPORTED_ECOSYSTEMS.has(p.ecosystem)))
28
+ .map((p) => `${p.ecosystem}|${p.name}|${p.version}`)
29
+ .sort();
30
+ return createHash("sha256").update(rows.join("\n"), "utf8").digest("hex");
31
+ }
32
+
25
33
  async function fetchJson(fetcher, url, options, timeoutMs) {
26
34
  const timeout = Math.max(50, Number(timeoutMs) || DEFAULT_FETCH_TIMEOUT_MS);
27
35
  const ctrl = typeof AbortController === "function" ? new AbortController() : null;
@@ -119,6 +127,7 @@ export async function refreshAdvisories({ installed = [], storePath = DEFAULT_ST
119
127
  const store = loadStore(storePath);
120
128
  const idsByPkg = new Map(); // pkgIndex -> [vuln ids]
121
129
  const errors = [];
130
+ let queriedOk = 0;
122
131
 
123
132
  for (let i = 0; i < pkgs.length; i += batchSize) {
124
133
  const batch = pkgs.slice(i, i + batchSize);
@@ -128,7 +137,22 @@ export async function refreshAdvisories({ installed = [], storePath = DEFAULT_ST
128
137
  headers: { "Content-Type": "application/json" },
129
138
  body: JSON.stringify({ queries: batch.map((p) => ({ package: { ecosystem: p.ecosystem, name: p.name }, version: p.version })) }),
130
139
  }, timeoutMs);
131
- (json.results || []).forEach((r, j) => { if (r && Array.isArray(r.vulns) && r.vulns.length) idsByPkg.set(i + j, r.vulns.map((v) => v.id)); });
140
+ if (!Array.isArray(json?.results) || json.results.length !== batch.length) {
141
+ throw new Error(`OSV querybatch returned ${Array.isArray(json?.results) ? json.results.length : "no"} result(s) for ${batch.length} query item(s)`);
142
+ }
143
+ for (const [resultIndex, result] of json.results.entries()) {
144
+ if (!result || typeof result !== "object" || Array.isArray(result)) {
145
+ throw new Error(`OSV querybatch result ${resultIndex + 1} is not an object`);
146
+ }
147
+ if (result.vulns !== undefined && !Array.isArray(result.vulns)) {
148
+ throw new Error(`OSV querybatch result ${resultIndex + 1} has a non-array vulns field`);
149
+ }
150
+ if (Array.isArray(result.vulns) && result.vulns.some((v) => !v || typeof v.id !== "string" || !v.id.trim())) {
151
+ throw new Error(`OSV querybatch result ${resultIndex + 1} contains an advisory without a valid id`);
152
+ }
153
+ }
154
+ queriedOk += batch.length;
155
+ json.results.forEach((r, j) => { if (r && Array.isArray(r.vulns) && r.vulns.length) idsByPkg.set(i + j, r.vulns.map((v) => v.id)); });
132
156
  } catch (error) {
133
157
  errors.push(`querybatch ${Math.floor(i / batchSize) + 1}/${Math.ceil(pkgs.length / batchSize)}: ${error.message}`);
134
158
  }
@@ -141,16 +165,24 @@ export async function refreshAdvisories({ installed = [], storePath = DEFAULT_ST
141
165
  for (const [id, pkgList] of wanted) {
142
166
  try {
143
167
  const rec = await fetchJson(fetcher, OSV_VULN_URL + encodeURIComponent(id), {}, timeoutMs);
144
- if (!rec || !rec.id) continue;
145
- fetched++;
168
+ if (!rec || typeof rec.id !== "string" || !rec.id) throw new Error("OSV detail response is missing its advisory id");
169
+ if (rec.id !== id) throw new Error(`OSV detail id mismatch (expected ${id}, received ${rec.id})`);
170
+ let normalized = 0;
146
171
  for (const p of pkgList) {
147
172
  const row = normalizeRecord(rec, p.ecosystem, p.name);
148
- if (!row) continue;
173
+ if (!row) {
174
+ errors.push(`${id}: OSV detail does not describe ${p.ecosystem}:${p.name} reported by querybatch`);
175
+ continue;
176
+ }
177
+ normalized++;
149
178
  const key = keyOf(p.ecosystem, p.name);
150
179
  const list = store.records[key] || (store.records[key] = []);
151
180
  const at = list.findIndex((x) => x.id === row.id);
152
181
  if (at >= 0) list[at] = row; else list.push(row);
153
182
  }
183
+ // Count a detail response as fetched only after at least one package-specific row was
184
+ // validated. A malformed or unrelated response must never make coverage look complete.
185
+ if (normalized > 0) fetched++;
154
186
  } catch (error) {
155
187
  errors.push(`${id}: ${error.message}`);
156
188
  }
@@ -158,20 +190,32 @@ export async function refreshAdvisories({ installed = [], storePath = DEFAULT_ST
158
190
 
159
191
  // A refresh where NOTHING was fetched but errors occurred (offline, OSV blocked) must NOT stamp
160
192
  // fetched_at — that would turn an empty cache into "No known vulnerabilities as of <today>".
161
- if (errors.length && fetched === 0 && (idsByPkg.size === 0 || wanted.size > 0)) {
193
+ if (errors.length && queriedOk === 0) {
162
194
  return { ok: false, queried: pkgs.length, unsupported, error: `advisory refresh failed: ${errors[0]}${errors.length > 1 ? ` (+${errors.length - 1} more)` : ""}`, errors };
163
195
  }
164
196
  store.meta.fetched_at = new Date().toISOString();
197
+ const status = errors.length ? "PARTIAL" : "OK";
165
198
  // per-repo stamp: the cache only covers packages that were QUERIED — a repo that never refreshed must
166
199
  // show "fetch advisories", not "0 vulnerabilities as of <someone else's date>" (false assurance).
167
200
  // repoKeys[] lets one online pass (a "refresh all repos") stamp every repo whose packages it covered.
168
201
  const stampRepos = [...new Set([repoKey, ...repoKeys].filter(Boolean))];
169
- if (stampRepos.length) { store.meta.repos = store.meta.repos || {}; for (const k of stampRepos) store.meta.repos[k] = store.meta.fetched_at; }
202
+ if (stampRepos.length) {
203
+ store.meta.repos = store.meta.repos || {};
204
+ for (const k of stampRepos) store.meta.repos[k] = {
205
+ fetched_at: store.meta.fetched_at,
206
+ status,
207
+ queried: pkgs.length,
208
+ queried_ok: queriedOk,
209
+ unsupported,
210
+ error_count: errors.length,
211
+ query_fingerprint: advisoryQueryFingerprint(pkgs),
212
+ };
213
+ }
170
214
  try {
171
215
  mkdirSync(dirname(storePath), { recursive: true });
172
216
  writeFileSync(storePath, JSON.stringify(store), "utf8");
173
217
  } catch (error) {
174
218
  return { ok: false, error: `store write failed: ${error.message}`, errors };
175
219
  }
176
- return { ok: true, queried: pkgs.length, unsupported, vulnerable: wanted.size, fetched, saved: existsSync(storePath), errors };
220
+ return { ok: true, status, queried: pkgs.length, queriedOk, unsupported, vulnerable: wanted.size, fetched, saved: existsSync(storePath), errors };
177
221
  }
@@ -2,10 +2,11 @@
2
2
  // (package-lock v1/v2/v3, basic yarn.lock, requirements.txt ==pins, go.sum), plus a top-level
3
3
  // node_modules walk — which also yields the lockfile-DRIFT signal (installed ≠ locked → tampering or
4
4
  // stale install). Parsers are pure + exported for tests; collectInstalled is the thin fs wrapper.
5
- import { existsSync, readFileSync, readdirSync } from "node:fs";
6
- import { join } from "node:path";
5
+ import { readFileSync, readdirSync } from "node:fs";
6
+ import { join, relative } from "node:path";
7
7
  import { parseGoMod } from "../analysis/manifests.js";
8
8
  import { uniqueBy } from "../util.js";
9
+ import { createRepoBoundary } from "../repo-path.js";
9
10
 
10
11
  const pep503 = (name) => String(name).toLowerCase().replace(/[-_.]+/g, "-"); // PyPI canonical name
11
12
 
@@ -144,21 +145,19 @@ export function parseGoModPackages(text) {
144
145
  }
145
146
 
146
147
  // Top-level node_modules walk (incl. @scopes): the ground truth of what is REALLY on disk.
147
- function walkNodeModules(repoPath) {
148
+ function walkNodeModules(repoPath, { readJsonFile = readJson, readdir = readdirSync } = {}) {
148
149
  const out = [];
149
150
  const nm = join(repoPath, "node_modules");
150
151
  const readPkg = (dir, name) => {
151
- try {
152
- const pj = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
153
- if (pj && pj.version) out.push({ ecosystem: "npm", name: pj.name || name, version: pj.version, dev: false, integrity: "", source: "node_modules" });
154
- } catch { /* not a package dir */ }
152
+ const pj = readJsonFile(join(dir, "package.json"));
153
+ if (pj && pj.version) out.push({ ecosystem: "npm", name: pj.name || name, version: pj.version, dev: false, integrity: "", source: "node_modules" });
155
154
  };
156
155
  let entries;
157
- try { entries = readdirSync(nm); } catch { return out; }
156
+ try { entries = readdir(nm); } catch { return out; }
158
157
  for (const e of entries) {
159
158
  if (e.startsWith(".")) continue;
160
159
  if (e.startsWith("@")) {
161
- let scoped; try { scoped = readdirSync(join(nm, e)); } catch { continue; }
160
+ let scoped; try { scoped = readdir(join(nm, e)); } catch { continue; }
162
161
  for (const s of scoped) readPkg(join(nm, e, s), `${e}/${s}`);
163
162
  } else readPkg(join(nm, e), e);
164
163
  }
@@ -170,58 +169,72 @@ const readJson = (p) => { try { return JSON.parse(readFileSync(p, "utf8")); } ca
170
169
 
171
170
  const SUBPROJECT_SKIP = new Set([".git", ".idea", ".vscode", ".venv", "venv", "env", "node_modules", "vendor", "dist", "build", "coverage", "__pycache__", ".tox", "testdata"]);
172
171
 
173
- function projectDirs(repoPath) {
174
- const dirs = [repoPath];
172
+ function projectDirs(boundary) {
173
+ const dirs = boundary.root ? [boundary.root] : [];
175
174
  let entries = [];
176
- try { entries = readdirSync(repoPath, { withFileTypes: true }); } catch { return dirs; }
175
+ try { entries = readdirSync(boundary.root, { withFileTypes: true }); } catch { return dirs; }
177
176
  for (const e of entries) {
178
177
  if (!e.isDirectory() || e.name.startsWith(".") || SUBPROJECT_SKIP.has(e.name)) continue;
179
- dirs.push(join(repoPath, e.name));
178
+ const resolved = boundary.resolve(e.name);
179
+ if (resolved.ok) dirs.push(resolved.path);
180
180
  if (dirs.length >= 101) break;
181
181
  }
182
182
  return dirs;
183
183
  }
184
184
 
185
- function collectReqFiles(dir) {
185
+ function collectReqFiles(dir, readdir = readdirSync) {
186
186
  const reqFiles = [];
187
- try { for (const n of readdirSync(dir)) if (/^requirements[\w.-]*\.(txt|in)$/i.test(n)) reqFiles.push(join(dir, n)); } catch { /* unreadable root */ }
188
- try { for (const n of readdirSync(join(dir, "requirements"))) if (/\.(txt|in)$/i.test(n)) reqFiles.push(join(dir, "requirements", n)); } catch { /* no requirements/ dir */ }
187
+ try { for (const n of readdir(dir)) if (/^requirements[\w.-]*\.(txt|in)$/i.test(n)) reqFiles.push(join(dir, n)); } catch { /* unreadable root */ }
188
+ try { for (const n of readdir(join(dir, "requirements"))) if (/\.(txt|in)$/i.test(n)) reqFiles.push(join(dir, "requirements", n)); } catch { /* no requirements/ dir */ }
189
189
  return reqFiles;
190
190
  }
191
191
 
192
192
  // → { installed: [{ecosystem,name,version,dev,source}], drift: [{name, locked, installed}] }
193
193
  export function collectInstalled(repoPath) {
194
- const dirs = projectDirs(repoPath);
194
+ const boundary = createRepoBoundary(repoPath);
195
+ if (!boundary.root) return { installed: [], drift: [] };
196
+ const inside = (path) => boundary.resolve(relative(boundary.root, path) || ".");
197
+ const boundedText = (path) => { const resolved = inside(path); return resolved.ok ? readText(resolved.path) : null; };
198
+ const boundedJson = (path) => { const resolved = inside(path); return resolved.ok ? readJson(resolved.path) : null; };
199
+ const boundedReaddir = (path, options) => {
200
+ const resolved = inside(path);
201
+ if (!resolved.ok) throw new Error("path is outside the repository");
202
+ return readdirSync(resolved.path, options);
203
+ };
204
+ const dirs = projectDirs(boundary);
195
205
  const lock = [];
196
206
  const yarn = [];
197
207
  const disk = [];
198
208
  for (const dir of dirs) {
199
- const lockHere = parsePackageLock(readJson(join(dir, "package-lock.json")) || {});
209
+ const lockHere = parsePackageLock(boundedJson(join(dir, "package-lock.json")) || {});
200
210
  lock.push(...lockHere);
201
- if (!lockHere.length) yarn.push(...parseYarnLock(readText(join(dir, "yarn.lock")) || ""));
202
- disk.push(...walkNodeModules(dir));
211
+ if (!lockHere.length) yarn.push(...parseYarnLock(boundedText(join(dir, "yarn.lock")) || ""));
212
+ disk.push(...walkNodeModules(dir, { readJsonFile: boundedJson, readdir: boundedReaddir }));
203
213
  }
204
214
  // Python: venv site-packages = the ground truth (exact installed versions); requirements*.txt (root +
205
215
  // a requirements/ dir) and poetry/uv/Pipfile locks fill in when there's no venv. venv wins per name.
206
- const venvPy = dirs.flatMap((dir) => collectVenvPackages(dir));
207
- const reqFiles = dirs.flatMap((dir) => collectReqFiles(dir));
216
+ const venvPy = dirs.flatMap((dir) => collectVenvPackages(dir, { readdir: boundedReaddir }));
217
+ const reqFiles = dirs.flatMap((dir) => collectReqFiles(dir, boundedReaddir));
208
218
  const venvNames = new Set(venvPy.map((p) => p.name));
209
219
  const pyDeclared = [
210
- ...reqFiles.flatMap((f) => parseRequirements(readText(f) || "")),
211
- ...dirs.flatMap((dir) => parseTomlLockPackages(readText(join(dir, "poetry.lock")) || "", "poetry-lock")),
212
- ...dirs.flatMap((dir) => parseTomlLockPackages(readText(join(dir, "uv.lock")) || "", "uv-lock")),
213
- ...dirs.flatMap((dir) => parsePipfileLock(readJson(join(dir, "Pipfile.lock")) || null)),
220
+ ...reqFiles.flatMap((f) => parseRequirements(boundedText(f) || "")),
221
+ ...dirs.flatMap((dir) => parseTomlLockPackages(boundedText(join(dir, "poetry.lock")) || "", "poetry-lock")),
222
+ ...dirs.flatMap((dir) => parseTomlLockPackages(boundedText(join(dir, "uv.lock")) || "", "uv-lock")),
223
+ ...dirs.flatMap((dir) => parsePipfileLock(boundedJson(join(dir, "Pipfile.lock")) || null)),
214
224
  ].filter((p) => !venvNames.has(p.name)); // installed version supersedes the declared pin
215
225
  const py = [...venvPy, ...pyDeclared];
216
226
  // Go: go.sum (exact, hashed) first, then go.mod require versions as a fallback. Walk the repo root
217
227
  // AND its immediate subdirectories so a Go MONOREPO (per-folder modules, no root go.mod — e.g. gpro)
218
228
  // still scans; dedupe() collapses the go.sum/go.mod overlap and cross-module shared deps.
219
- const goFromDir = (dir) => [...parseGoSum(readText(join(dir, "go.sum")) || ""), ...parseGoModPackages(readText(join(dir, "go.mod")) || "")];
220
- const go = [...goFromDir(repoPath)];
221
- if (!go.length || existsSync(join(repoPath, "go.work"))) {
229
+ const goFromDir = (dir) => [...parseGoSum(boundedText(join(dir, "go.sum")) || ""), ...parseGoModPackages(boundedText(join(dir, "go.mod")) || "")];
230
+ const go = [...goFromDir(boundary.root)];
231
+ if (!go.length || boundary.resolve("go.work").ok) {
222
232
  let subs = [];
223
- try { subs = readdirSync(repoPath, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith(".") && !["node_modules", "vendor", "dist", "build", "testdata"].includes(e.name)); } catch { /* unreadable root */ }
224
- for (const s of subs.slice(0, 100)) go.push(...goFromDir(join(repoPath, s.name)));
233
+ try { subs = boundedReaddir(boundary.root, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith(".") && !["node_modules", "vendor", "dist", "build", "testdata"].includes(e.name)); } catch { /* unreadable root */ }
234
+ for (const s of subs.slice(0, 100)) {
235
+ const resolved = boundary.resolve(s.name);
236
+ if (resolved.ok) go.push(...goFromDir(resolved.path));
237
+ }
225
238
  }
226
239
 
227
240
  // lockfile wins as the version source; disk fills gaps + powers the drift signal. A package
@@ -1,134 +1,134 @@
1
- // Allowlist/exclusion parsing and URL/doc-noise filters for the malware scanner (split out of
2
- // malware-heuristics.js; see that file for the scanner overview).
3
- import { NOISY_URL_KEYS, isDocFile, isBenignUrlContext } from "./registry-sig.js";
4
-
5
- export const normPath = (p) => String(p || "").replace(/\\/g, "/").replace(/\/+$/, "");
6
- const URL_RULE_KEYS = new Set(["exfil-url", "exfil-ip", "cloud-metadata-url", "network-url", "hardcoded-url"]);
7
- const URL_RE = /https?:\/\/[^\s'"`)\\<>]+/gi;
8
- const PACKAGE_JSON_SCRIPT_RE = /["']?(preinstall|install|postinstall|prepare|prepack|postpack|prepublish|prepublishonly)["']?\s*:/i;
9
- const PACKAGE_JSON_METADATA_URL_RE = /["']?(bugs|homepage|repository|funding|author|contributors|maintainers|publishConfig|license)["']?\s*:|["']?url["']?\s*:/i;
10
- const NETWORK_CALL_RE = /\b(fetch|axios\.|XMLHttpRequest|sendBeacon|https?\.request|request\(|curl\b|wget\b|iwr\b|invoke-webrequest)\b/i;
11
- const LIFECYCLE_SCRIPT_HOOKS = ["preinstall", "install", "postinstall", "prepare"];
12
-
13
- function cleanUrlToken(value) {
14
- return String(value || "").trim().replace(/[.,;:!?]+$/g, "").replace(/[)\]}]+$/g, "");
15
- }
16
-
17
- function splitAllowlistText(value) {
18
- if (Array.isArray(value)) return value.flatMap(splitAllowlistText);
19
- return String(value || "")
20
- .split(/[\r\n,]+/)
21
- .map((line) => line.replace(/\s+#.*$/, "").trim())
22
- .filter(Boolean);
23
- }
24
-
25
- function normalizeHost(value) {
26
- let s = String(value || "").trim().toLowerCase();
27
- if (!s) return "";
28
- try {
29
- if (/^https?:\/\//i.test(s)) s = new URL(s).host;
30
- } catch { /* keep raw */ }
31
- return s.replace(/^\*\./, "").replace(/^\./, "").replace(/:\d+$/, "");
32
- }
33
-
34
- function normalizeUrl(value) {
35
- const raw = cleanUrlToken(value);
36
- if (!raw) return "";
37
- try {
38
- const u = new URL(raw);
39
- const path = u.pathname.replace(/\/+$/, "");
40
- return `${u.protocol.toLowerCase()}//${u.host.toLowerCase()}${path}${u.search || ""}`;
41
- } catch {
42
- return raw.toLowerCase().replace(/\/+$/, "");
43
- }
44
- }
45
-
46
- function extractUrls(text) {
47
- return [...String(text || "").matchAll(URL_RE)].map((m) => cleanUrlToken(m[0])).filter(Boolean);
48
- }
49
-
50
- function urlMatchesAllow(allowUrl, candidate) {
51
- const a = normalizeUrl(allowUrl);
52
- const c = normalizeUrl(candidate);
53
- if (!a || !c) return false;
54
- return c === a || c.startsWith(`${a}/`) || a.startsWith(`${c}/`);
55
- }
56
-
57
- function hostMatchesAllow(allowHost, candidate) {
58
- const a = normalizeHost(allowHost);
59
- const c = normalizeHost(candidate);
60
- return !!(a && c && (c === a || c.endsWith(`.${a}`)));
61
- }
62
-
63
- export function parseMalwareExclusions(input = {}) {
64
- const out = { urls: [], hosts: [], packages: [], rules: [] };
65
- const add = (raw) => {
66
- const s = cleanUrlToken(raw);
67
- if (!s) return;
68
- const lower = s.toLowerCase();
69
- if (lower.startsWith("pkg:")) { out.packages.push(s.slice(4).trim()); return; }
70
- if (lower.startsWith("package:")) { out.packages.push(s.slice(8).trim()); return; }
71
- if (lower.startsWith("rule:")) { out.rules.push(s.slice(5).trim()); return; }
72
- if (lower.startsWith("host:")) { out.hosts.push(normalizeHost(s.slice(5))); return; }
73
- if (lower.startsWith("domain:")) { out.hosts.push(normalizeHost(s.slice(7))); return; }
74
- if (/^https?:\/\//i.test(s)) { out.urls.push(normalizeUrl(s)); out.hosts.push(normalizeHost(s)); return; }
75
- if (!s.includes("/") && s.includes(".")) { out.hosts.push(normalizeHost(s)); return; }
76
- out.packages.push(s);
77
- };
78
- if (typeof input === "string" || Array.isArray(input)) {
79
- for (const line of splitAllowlistText(input)) add(line);
80
- } else if (input && typeof input === "object") {
81
- for (const line of splitAllowlistText(input.urls || input.url || "")) add(line);
82
- for (const line of splitAllowlistText(input.domains || input.domain || "")) add(`host:${line}`);
83
- for (const line of splitAllowlistText(input.packages || input.package || "")) add(/^pkg(age)?:/i.test(line) ? line : `pkg:${line}`);
84
- for (const line of splitAllowlistText(input.rules || input.rule || "")) add(`rule:${line}`);
85
- }
86
- return {
87
- urls: [...new Set(out.urls.filter(Boolean))],
88
- hosts: [...new Set(out.hosts.filter(Boolean))],
89
- packages: [...new Set(out.packages.map((p) => p.trim()).filter(Boolean))],
90
- rules: [...new Set(out.rules.map((r) => r.trim()).filter(Boolean))],
91
- };
92
- }
93
-
94
- export function isManifestUrlNoise(file, signal) {
95
- if (!URL_RULE_KEYS.has(signal?.key)) return false;
96
- const f = normPath(file).toLowerCase();
97
- const text = `${signal?.snippet || ""}`.trim();
98
- if (/(^|\/)package\.json$/.test(f)) {
99
- if (PACKAGE_JSON_SCRIPT_RE.test(text)) return false;
100
- return PACKAGE_JSON_METADATA_URL_RE.test(text) || !NETWORK_CALL_RE.test(text);
101
- }
102
- return /(^|\/)(pkg-info|metadata)$/.test(f);
103
- }
104
-
105
- export function lifecycleScriptSnippet(scripts = {}) {
106
- for (const hook of LIFECYCLE_SCRIPT_HOOKS) {
107
- const s = String(scripts?.[hook] || "").trim();
108
- if (s) return `${hook}: ${s}`.slice(0, 200);
109
- }
110
- return "";
111
- }
112
-
113
- // weak URL rules only: URL evidence in a license/prose file or in comment/doc-link context is
114
- // documentation, not behavior (LICENSE:5 "http://www.apache.org/licenses/" was the hot FP).
115
- // Strong rules (miner/shell/exfil-url) are untouched and still scan those same files.
116
- export function isDocUrlNoise(file, signal) {
117
- if (!NOISY_URL_KEYS.has(signal?.key)) return false;
118
- return isDocFile(file) || isBenignUrlContext(signal?.snippet || "");
119
- }
120
-
121
- export function isMalwareSignalExcluded(pkg, signal, exclusions = {}) {
122
- const ex = exclusions.urls || exclusions.hosts || exclusions.packages || exclusions.rules ? exclusions : parseMalwareExclusions(exclusions);
123
- if (signal?.key && ex.rules.includes(signal.key)) return true;
124
- if (ex.packages.some((p) => p.toLowerCase() === String(pkg || "").toLowerCase()) && signal?.noisy) return true;
125
- if (!URL_RULE_KEYS.has(signal?.key)) return false;
126
- const text = `${signal?.snippet || ""}\n${signal?.file || ""}`;
127
- const urls = extractUrls(text);
128
- for (const url of urls) {
129
- if (ex.urls.some((allowed) => urlMatchesAllow(allowed, url))) return true;
130
- if (ex.hosts.some((allowed) => hostMatchesAllow(allowed, url))) return true;
131
- }
132
- if (!urls.length && ex.hosts.some((host) => host && text.toLowerCase().includes(host))) return true;
133
- return false;
134
- }
1
+ // Allowlist/exclusion parsing and URL/doc-noise filters for the malware scanner (split out of
2
+ // malware-heuristics.js; see that file for the scanner overview).
3
+ import { NOISY_URL_KEYS, isDocFile, isBenignUrlContext } from "./registry-sig.js";
4
+
5
+ export const normPath = (p) => String(p || "").replace(/\\/g, "/").replace(/\/+$/, "");
6
+ const URL_RULE_KEYS = new Set(["exfil-url", "exfil-ip", "cloud-metadata-url", "network-url", "hardcoded-url"]);
7
+ const URL_RE = /https?:\/\/[^\s'"`)\\<>]+/gi;
8
+ const PACKAGE_JSON_SCRIPT_RE = /["']?(preinstall|install|postinstall|prepare|prepack|postpack|prepublish|prepublishonly)["']?\s*:/i;
9
+ const PACKAGE_JSON_METADATA_URL_RE = /["']?(bugs|homepage|repository|funding|author|contributors|maintainers|publishConfig|license)["']?\s*:|["']?url["']?\s*:/i;
10
+ const NETWORK_CALL_RE = /\b(fetch|axios\.|XMLHttpRequest|sendBeacon|https?\.request|request\(|curl\b|wget\b|iwr\b|invoke-webrequest)\b/i;
11
+ const LIFECYCLE_SCRIPT_HOOKS = ["preinstall", "install", "postinstall", "prepare"];
12
+
13
+ function cleanUrlToken(value) {
14
+ return String(value || "").trim().replace(/[.,;:!?]+$/g, "").replace(/[)\]}]+$/g, "");
15
+ }
16
+
17
+ function splitAllowlistText(value) {
18
+ if (Array.isArray(value)) return value.flatMap(splitAllowlistText);
19
+ return String(value || "")
20
+ .split(/[\r\n,]+/)
21
+ .map((line) => line.replace(/\s+#.*$/, "").trim())
22
+ .filter(Boolean);
23
+ }
24
+
25
+ function normalizeHost(value) {
26
+ let s = String(value || "").trim().toLowerCase();
27
+ if (!s) return "";
28
+ try {
29
+ if (/^https?:\/\//i.test(s)) s = new URL(s).host;
30
+ } catch { /* keep raw */ }
31
+ return s.replace(/^\*\./, "").replace(/^\./, "").replace(/:\d+$/, "");
32
+ }
33
+
34
+ function normalizeUrl(value) {
35
+ const raw = cleanUrlToken(value);
36
+ if (!raw) return "";
37
+ try {
38
+ const u = new URL(raw);
39
+ const path = u.pathname.replace(/\/+$/, "");
40
+ return `${u.protocol.toLowerCase()}//${u.host.toLowerCase()}${path}${u.search || ""}`;
41
+ } catch {
42
+ return raw.toLowerCase().replace(/\/+$/, "");
43
+ }
44
+ }
45
+
46
+ function extractUrls(text) {
47
+ return [...String(text || "").matchAll(URL_RE)].map((m) => cleanUrlToken(m[0])).filter(Boolean);
48
+ }
49
+
50
+ function urlMatchesAllow(allowUrl, candidate) {
51
+ const a = normalizeUrl(allowUrl);
52
+ const c = normalizeUrl(candidate);
53
+ if (!a || !c) return false;
54
+ return c === a || c.startsWith(`${a}/`) || a.startsWith(`${c}/`);
55
+ }
56
+
57
+ function hostMatchesAllow(allowHost, candidate) {
58
+ const a = normalizeHost(allowHost);
59
+ const c = normalizeHost(candidate);
60
+ return !!(a && c && (c === a || c.endsWith(`.${a}`)));
61
+ }
62
+
63
+ export function parseMalwareExclusions(input = {}) {
64
+ const out = { urls: [], hosts: [], packages: [], rules: [] };
65
+ const add = (raw) => {
66
+ const s = cleanUrlToken(raw);
67
+ if (!s) return;
68
+ const lower = s.toLowerCase();
69
+ if (lower.startsWith("pkg:")) { out.packages.push(s.slice(4).trim()); return; }
70
+ if (lower.startsWith("package:")) { out.packages.push(s.slice(8).trim()); return; }
71
+ if (lower.startsWith("rule:")) { out.rules.push(s.slice(5).trim()); return; }
72
+ if (lower.startsWith("host:")) { out.hosts.push(normalizeHost(s.slice(5))); return; }
73
+ if (lower.startsWith("domain:")) { out.hosts.push(normalizeHost(s.slice(7))); return; }
74
+ if (/^https?:\/\//i.test(s)) { out.urls.push(normalizeUrl(s)); out.hosts.push(normalizeHost(s)); return; }
75
+ if (!s.includes("/") && s.includes(".")) { out.hosts.push(normalizeHost(s)); return; }
76
+ out.packages.push(s);
77
+ };
78
+ if (typeof input === "string" || Array.isArray(input)) {
79
+ for (const line of splitAllowlistText(input)) add(line);
80
+ } else if (input && typeof input === "object") {
81
+ for (const line of splitAllowlistText(input.urls || input.url || "")) add(line);
82
+ for (const line of splitAllowlistText(input.domains || input.domain || "")) add(`host:${line}`);
83
+ for (const line of splitAllowlistText(input.packages || input.package || "")) add(/^pkg(age)?:/i.test(line) ? line : `pkg:${line}`);
84
+ for (const line of splitAllowlistText(input.rules || input.rule || "")) add(`rule:${line}`);
85
+ }
86
+ return {
87
+ urls: [...new Set(out.urls.filter(Boolean))],
88
+ hosts: [...new Set(out.hosts.filter(Boolean))],
89
+ packages: [...new Set(out.packages.map((p) => p.trim()).filter(Boolean))],
90
+ rules: [...new Set(out.rules.map((r) => r.trim()).filter(Boolean))],
91
+ };
92
+ }
93
+
94
+ export function isManifestUrlNoise(file, signal) {
95
+ if (!URL_RULE_KEYS.has(signal?.key)) return false;
96
+ const f = normPath(file).toLowerCase();
97
+ const text = `${signal?.snippet || ""}`.trim();
98
+ if (/(^|\/)package\.json$/.test(f)) {
99
+ if (PACKAGE_JSON_SCRIPT_RE.test(text)) return false;
100
+ return PACKAGE_JSON_METADATA_URL_RE.test(text) || !NETWORK_CALL_RE.test(text);
101
+ }
102
+ return /(^|\/)(pkg-info|metadata)$/.test(f);
103
+ }
104
+
105
+ export function lifecycleScriptSnippet(scripts = {}) {
106
+ for (const hook of LIFECYCLE_SCRIPT_HOOKS) {
107
+ const s = String(scripts?.[hook] || "").trim();
108
+ if (s) return `${hook}: ${s}`.slice(0, 200);
109
+ }
110
+ return "";
111
+ }
112
+
113
+ // weak URL rules only: URL evidence in a license/prose file or in comment/doc-link context is
114
+ // documentation, not behavior (LICENSE:5 "http://www.apache.org/licenses/" was the hot FP).
115
+ // Strong rules (miner/shell/exfil-url) are untouched and still scan those same files.
116
+ export function isDocUrlNoise(file, signal) {
117
+ if (!NOISY_URL_KEYS.has(signal?.key)) return false;
118
+ return isDocFile(file) || isBenignUrlContext(signal?.snippet || "");
119
+ }
120
+
121
+ export function isMalwareSignalExcluded(pkg, signal, exclusions = {}) {
122
+ const ex = exclusions.urls || exclusions.hosts || exclusions.packages || exclusions.rules ? exclusions : parseMalwareExclusions(exclusions);
123
+ if (signal?.key && ex.rules.includes(signal.key)) return true;
124
+ if (ex.packages.some((p) => p.toLowerCase() === String(pkg || "").toLowerCase()) && signal?.noisy) return true;
125
+ if (!URL_RULE_KEYS.has(signal?.key)) return false;
126
+ const text = `${signal?.snippet || ""}\n${signal?.file || ""}`;
127
+ const urls = extractUrls(text);
128
+ for (const url of urls) {
129
+ if (ex.urls.some((allowed) => urlMatchesAllow(allowed, url))) return true;
130
+ if (ex.hosts.some((allowed) => hostMatchesAllow(allowed, url))) return true;
131
+ }
132
+ if (!urls.length && ex.hosts.some((host) => host && text.toLowerCase().includes(host))) return true;
133
+ return false;
134
+ }
@@ -1,15 +1,15 @@
1
- // Heuristic malware scanner over INSTALLED dependencies (defensive): install-script beacons, crypto-
2
- // miner signatures, exfiltration endpoints, obfuscation markers, non-registry install sources.
3
- // Phase A (always, cheap): every installed package's package.json scripts + lockfile `resolved` origin.
4
- // Phase B (content): ripgrep sweep of node_modules when rg is available (full coverage), else a bounded
5
- // Node fallback over each package's entry files. Multi-signal scoring per package: high/critical needs
6
- // a near-zero-FP rule OR >=2 independent rule keys; the allowlist downgrades ONLY noisy rules.
7
- // This catches known PATTERNS — it is not a sandbox or a reputation service (honest limit, in the UI).
8
- // Split into sibling modules (this file stays the import path):
9
- // malware-heuristics.exclusions.js - allowlist parsing + URL/doc noise filters
10
- // malware-heuristics.roots.js - content roots + path-to-package mapping
11
- // malware-heuristics.sweep.js - ripgrep / Node content sweeps
12
- // malware-heuristics.scan.js - scanMalware orchestration
13
- export { parseMalwareExclusions, isMalwareSignalExcluded } from "./malware-heuristics.exclusions.js";
14
- export { pkgOfNodeModulesPath } from "./malware-heuristics.roots.js";
15
- export { scanMalware } from "./malware-heuristics.scan.js";
1
+ // Heuristic malware scanner over INSTALLED dependencies (defensive): install-script beacons, crypto-
2
+ // miner signatures, exfiltration endpoints, obfuscation markers, non-registry install sources.
3
+ // Phase A (always, cheap): every installed package's package.json scripts + lockfile `resolved` origin.
4
+ // Phase B (content): ripgrep sweep of node_modules when rg is available (full coverage), else a bounded
5
+ // Node fallback over each package's entry files. Multi-signal scoring per package: high/critical needs
6
+ // a near-zero-FP rule OR >=2 independent rule keys; the allowlist downgrades ONLY noisy rules.
7
+ // This catches known PATTERNS — it is not a sandbox or a reputation service (honest limit, in the UI).
8
+ // Split into sibling modules (this file stays the import path):
9
+ // malware-heuristics.exclusions.js - allowlist parsing + URL/doc noise filters
10
+ // malware-heuristics.roots.js - content roots + path-to-package mapping
11
+ // malware-heuristics.sweep.js - ripgrep / Node content sweeps
12
+ // malware-heuristics.scan.js - scanMalware orchestration
13
+ export { parseMalwareExclusions, isMalwareSignalExcluded } from "./malware-heuristics.exclusions.js";
14
+ export { pkgOfNodeModulesPath } from "./malware-heuristics.roots.js";
15
+ export { scanMalware } from "./malware-heuristics.scan.js";