weavatrix 0.1.1 → 0.1.2

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 (35) hide show
  1. package/README.md +57 -16
  2. package/SECURITY.md +31 -0
  3. package/package.json +16 -4
  4. package/skill/SKILL.md +16 -10
  5. package/src/analysis/coverage-reports.js +14 -11
  6. package/src/analysis/dead-check.js +7 -2
  7. package/src/analysis/duplicates.compute.js +221 -215
  8. package/src/analysis/duplicates.js +15 -15
  9. package/src/analysis/duplicates.run.js +52 -51
  10. package/src/analysis/duplicates.tokenize.js +182 -182
  11. package/src/analysis/endpoints.js +5 -3
  12. package/src/analysis/graph-analysis.aggregate.js +5 -1
  13. package/src/analysis/internal-audit.collect.js +37 -11
  14. package/src/analysis/internal-audit.run.js +8 -5
  15. package/src/build-graph.js +2 -1
  16. package/src/child-env.js +7 -0
  17. package/src/graph/internal-builder.build.js +1 -1
  18. package/src/graph/internal-builder.langs.js +8 -3
  19. package/src/graph/internal-builder.resolvers.js +10 -3
  20. package/src/mcp/catalog.mjs +9 -7
  21. package/src/mcp/graph-context.mjs +8 -5
  22. package/src/mcp/sync-payload.mjs +102 -0
  23. package/src/mcp/tools-actions.mjs +22 -13
  24. package/src/mcp/tools-impact.mjs +3 -2
  25. package/src/mcp-rg.mjs +2 -1
  26. package/src/mcp-server.mjs +22 -16
  27. package/src/mcp-source-tools.mjs +16 -5
  28. package/src/process.js +4 -3
  29. package/src/repo-path.js +53 -0
  30. package/src/security/installed.js +44 -31
  31. package/src/security/malware-heuristics.exclusions.js +134 -134
  32. package/src/security/malware-heuristics.js +15 -15
  33. package/src/security/malware-heuristics.roots.js +142 -142
  34. package/src/security/malware-heuristics.scan.js +85 -85
  35. package/src/security/malware-heuristics.sweep.js +122 -122
@@ -1,10 +1,14 @@
1
1
  import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
2
2
  import { spawnSync } from 'node:child_process'
3
3
  import { extname, join, relative } from 'node:path'
4
+ import { resolveRepoPath } from './repo-path.js'
5
+ import { childProcessEnv } from './child-env.js'
4
6
 
5
7
  const SEARCH_SKIP = new Set(['.git', 'node_modules', 'dist', 'build', 'out', '.next', 'coverage', 'vendor', '.venv', 'venv', 'env', 'target', '__pycache__', '.idea', '.vscode', '.cache', 'bin', 'obj', 'weavatrix-graphs'])
6
8
  const BINARY_EXT = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.ico', '.pdf', '.zip', '.gz', '.tar', '.exe', '.dll', '.so', '.dylib', '.woff', '.woff2', '.ttf', '.eot', '.mp4', '.mp3', '.wasm', '.class', '.jar', '.node', '.bin'])
7
9
  const MAX_SEARCH_FILE_BYTES = 1024 * 1024
10
+ const MAX_SOURCE_FILE_BYTES = 2 * 1024 * 1024
11
+ const MAX_SOURCE_CONTEXT_LINES = 1000
8
12
 
9
13
  function rgSearch(repoRoot, resolveRg, query, { isRegex, glob, maxResults }) {
10
14
  const rg = resolveRg()
@@ -13,7 +17,7 @@ function rgSearch(repoRoot, resolveRg, query, { isRegex, glob, maxResults }) {
13
17
  if (!isRegex) args.push('--fixed-strings')
14
18
  if (glob) args.push('-g', glob)
15
19
  args.push('--', query, repoRoot)
16
- const res = spawnSync(rg, args, { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024, timeout: 15000 })
20
+ const res = spawnSync(rg, args, { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024, timeout: 15000, env: childProcessEnv() })
17
21
  if (res.status !== 0 && res.status !== 1) return null
18
22
  const out = []
19
23
  for (const line of (res.stdout || '').split(/\r?\n/)) {
@@ -122,14 +126,21 @@ export function readSource({ repoRoot, resolveNode, isSymbol }, g, { label, path
122
126
  }
123
127
  // explicit anchor wins: window = start_line-before .. start_line+after (how a path read escapes the file head)
124
128
  if (start_line != null && Number(start_line) > 0) focusLine = Math.floor(Number(start_line))
125
- const abs = join(repoRoot, file)
126
- if (!existsSync(abs)) return `File not found: ${file}`
129
+ const resolved = resolveRepoPath(repoRoot, file)
130
+ if (resolved.reason === 'escape') return `Refusing to read "${file}": path escapes the repository root.`
131
+ if (resolved.reason === 'not-found') return `File not found: ${file}`
132
+ if (!resolved.ok) return `Could not resolve ${file} inside the repository root.`
133
+ const abs = resolved.path
134
+ let st
135
+ try { st = statSync(abs) } catch (e) { return `Could not inspect ${file}: ${e.message}` }
136
+ if (!st.isFile()) return `Could not read ${file}: not a regular file.`
137
+ if (st.size > MAX_SOURCE_FILE_BYTES) return `Could not read ${file}: file exceeds the ${MAX_SOURCE_FILE_BYTES / 1024 / 1024} MB source-read limit.`
127
138
  let text
128
139
  try { text = readFileSync(abs, 'utf8') } catch (e) { return `Could not read ${file}: ${e.message}` }
129
140
  const lines = text.split(/\r?\n/)
130
141
  if (focusLine) focusLine = Math.min(focusLine, lines.length) // an anchor past EOF shows the tail, not nothing
131
- const b = Math.max(0, Number(before) || 0)
132
- const a = Math.max(1, Number(after) || 40)
142
+ const b = Math.min(MAX_SOURCE_CONTEXT_LINES, Math.max(0, Number(before) || 0))
143
+ const a = Math.min(MAX_SOURCE_CONTEXT_LINES, Math.max(1, Number(after) || 40))
133
144
  const start = focusLine ? Math.max(1, focusLine - b) : 1
134
145
  const end = focusLine ? Math.min(lines.length, focusLine + a) : Math.min(lines.length, 1 + b + a)
135
146
  const width = String(end).length
package/src/process.js CHANGED
@@ -1,5 +1,6 @@
1
1
  // Subprocess runner shared by the search engines and security sweeps.
2
2
  import { spawn } from "node:child_process";
3
+ import { childProcessEnv } from "./child-env.js";
3
4
 
4
5
  // Windows: .cmd/.ps1 shims (npx, etc.) can't be spawned directly by Node — they need a
5
6
  // shell. With shell:true Node does NOT quote args, so we build a quoted command line ourselves
@@ -18,13 +19,13 @@ export function runCommand(command, args = [], options = {}) {
18
19
  const child = needsShell
19
20
  ? spawn([command, ...args].map(winQuote).join(" "), [], {
20
21
  cwd: options.cwd || undefined,
21
- env: { ...process.env, ...(options.env || {}) },
22
+ env: childProcessEnv(options.env || {}),
22
23
  shell: true,
23
24
  windowsHide: true
24
25
  })
25
26
  : spawn(command, args, {
26
27
  cwd: options.cwd || undefined,
27
- env: { ...process.env, ...(options.env || {}) },
28
+ env: childProcessEnv(options.env || {}),
28
29
  windowsHide: true
29
30
  });
30
31
 
@@ -46,7 +47,7 @@ export function runCommand(command, args = [], options = {}) {
46
47
  const killTree = () => {
47
48
  if (process.platform === "win32" && child.pid) {
48
49
  try {
49
- spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { windowsHide: true });
50
+ spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { windowsHide: true, env: childProcessEnv() });
50
51
  } catch {
51
52
  try { child.kill(); } catch { /* process may already be gone */ }
52
53
  }
@@ -0,0 +1,53 @@
1
+ import { realpathSync } from "node:fs";
2
+ import { isAbsolute, relative, resolve, sep } from "node:path";
3
+
4
+ export function isPathInside(root, target) {
5
+ const rel = relative(root, target);
6
+ return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
7
+ }
8
+
9
+ // Cache the canonical root for callers that resolve many graph-derived paths.
10
+ export function createRepoBoundary(repoRoot) {
11
+ let root;
12
+ let rootError;
13
+ try {
14
+ root = realpathSync.native(repoRoot);
15
+ } catch (error) {
16
+ rootError = error;
17
+ }
18
+
19
+ return {
20
+ root,
21
+ resolve(candidate) {
22
+ if (!root) return { ok: false, reason: "invalid-root", error: rootError };
23
+ const input = String(candidate ?? "");
24
+ if (!input || input.includes("\0")) return { ok: false, reason: "invalid-path" };
25
+ if (isAbsolute(input)) return { ok: false, reason: "escape" };
26
+
27
+ let lexical;
28
+ try {
29
+ lexical = resolve(root, input);
30
+ } catch (error) {
31
+ return { ok: false, reason: "invalid-path", error };
32
+ }
33
+ if (!isPathInside(root, lexical)) return { ok: false, reason: "escape" };
34
+
35
+ let target;
36
+ try {
37
+ target = realpathSync.native(lexical);
38
+ } catch (error) {
39
+ return { ok: false, reason: error?.code === "ENOENT" ? "not-found" : "unreadable", error };
40
+ }
41
+ if (!isPathInside(root, target)) return { ok: false, reason: "escape" };
42
+
43
+ return { ok: true, path: target };
44
+ },
45
+ };
46
+ }
47
+
48
+ // Resolve one existing repo-relative path without allowing lexical traversal or
49
+ // symlink/junction escapes. Callers get a reason instead of an exception so MCP
50
+ // tools can refuse the read without exposing host filesystem details.
51
+ export function resolveRepoPath(repoRoot, candidate) {
52
+ return createRepoBoundary(repoRoot).resolve(candidate);
53
+ }
@@ -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";