weavatrix 0.1.0 → 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 +59 -18
  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 +6 -3
  18. package/src/graph/internal-builder.langs.js +17 -6
  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 +26 -17
  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,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";
@@ -1,142 +1,142 @@
1
- // Content roots + path-to-package mapping for the malware scanner (split out of
2
- // malware-heuristics.js): npm node_modules, Python site-packages, Go vendor/ and module cache.
3
- import { readFileSync, readdirSync, existsSync, statSync } from "node:fs";
4
- import { homedir } from "node:os";
5
- import { delimiter, join, relative } from "node:path";
6
- import { normPath } from "./malware-heuristics.exclusions.js";
7
-
8
- const pep503 = (name) => String(name || "").toLowerCase().replace(/[-_.]+/g, "-");
9
-
10
- // node_modules/@scope/name/... → @scope/name ; node_modules/name/... → name
11
- export function pkgOfNodeModulesPath(p) {
12
- const s = String(p).replace(/\\/g, "/");
13
- const i = s.lastIndexOf("node_modules/");
14
- if (i < 0) return "";
15
- const rest = s.slice(i + "node_modules/".length).split("/");
16
- return rest[0]?.startsWith("@") ? `${rest[0]}/${rest[1] || ""}` : rest[0] || "";
17
- }
18
-
19
- function existingDir(p) {
20
- try { return p && existsSync(p) && statSync(p).isDirectory(); } catch { return false; }
21
- }
22
-
23
- function sitePackageRoots(repoPath) {
24
- const roots = [];
25
- for (const venv of [".venv", "venv", "env"]) {
26
- const win = join(repoPath, venv, "Lib", "site-packages");
27
- if (existingDir(win)) roots.push(win);
28
- try {
29
- for (const d of readdirSync(join(repoPath, venv, "lib"))) {
30
- const posix = join(repoPath, venv, "lib", String(d), "site-packages");
31
- if (/^python/i.test(String(d)) && existingDir(posix)) roots.push(posix);
32
- }
33
- } catch { /* no posix venv layout */ }
34
- }
35
- return [...new Set(roots.map((r) => join(r)))];
36
- }
37
-
38
- function pyTopLevelMap(sitePackagesRoot) {
39
- const map = new Map();
40
- let entries = [];
41
- try { entries = readdirSync(sitePackagesRoot); } catch { return map; }
42
- for (const e of entries) {
43
- if (!/\.dist-info$/i.test(e)) continue;
44
- const dist = e.replace(/-\d[\w.!+-]*\.dist-info$/i, "");
45
- const canonical = pep503(dist);
46
- try {
47
- const top = readFileSync(join(sitePackagesRoot, e, "top_level.txt"), "utf8");
48
- for (const line of top.split(/\r?\n/).map((x) => x.trim()).filter(Boolean)) map.set(line, canonical);
49
- } catch { /* metadata often omits top_level.txt */ }
50
- try {
51
- const meta = readFileSync(join(sitePackagesRoot, e, "METADATA"), "utf8");
52
- const m = meta.match(/^Name:\s*(.+)$/mi);
53
- if (m) map.set(dist, pep503(m[1]));
54
- } catch { /* no metadata */ }
55
- }
56
- return map;
57
- }
58
-
59
- function pkgOfSitePackagesPath(file, sitePackagesRoot, topMap) {
60
- const rel = normPath(relative(sitePackagesRoot, file));
61
- if (!rel || rel.startsWith("..")) return "";
62
- const first = rel.split("/")[0] || "";
63
- if (!first || first === "__pycache__") return "";
64
- if (/\.dist-info$|\.egg-info$/i.test(first)) return "";
65
- const top = first.replace(/\.(py|so|pyd|dll|pth)$/i, "");
66
- return topMap.get(top) || pep503(top);
67
- }
68
-
69
- function vendorModuleNames(installed) {
70
- return [...new Set((installed || []).filter((p) => p.ecosystem === "Go" && p.name).map((p) => String(p.name)))].sort((a, b) => b.length - a.length);
71
- }
72
-
73
- function pkgOfVendorPath(file, vendorRoot, moduleNames) {
74
- const rel = normPath(relative(vendorRoot, file));
75
- if (!rel || rel.startsWith("..")) return "";
76
- for (const name of moduleNames) if (rel === name || rel.startsWith(`${name}/`)) return name;
77
- const parts = rel.split("/");
78
- if (parts[0]?.includes(".") && parts.length >= 3) return parts.slice(0, 3).join("/");
79
- return parts.slice(0, 2).join("/") || parts[0] || "";
80
- }
81
-
82
- function goCacheRoots() {
83
- const roots = [];
84
- if (process.env.GOMODCACHE) roots.push(...String(process.env.GOMODCACHE).split(delimiter));
85
- for (const gp of String(process.env.GOPATH || join(homedir(), "go")).split(delimiter)) roots.push(join(gp, "pkg", "mod"));
86
- return [...new Set(roots.filter(existingDir))];
87
- }
88
-
89
- function goModCacheEscape(modulePath) {
90
- return String(modulePath || "").split("/").map((part) => part.replace(/[A-Z]/g, (c) => `!${c.toLowerCase()}`)).join("/");
91
- }
92
-
93
- function goModuleSourceRoots(installed) {
94
- const roots = [];
95
- const caches = goCacheRoots();
96
- const goPkgs = (installed || []).filter((p) => p.ecosystem === "Go" && p.name && p.version);
97
- for (const p of goPkgs) {
98
- const mod = goModCacheEscape(p.name);
99
- const ver = String(p.version).startsWith("v") ? String(p.version) : `v${p.version}`;
100
- for (const cache of caches) {
101
- const dir = join(cache, `${mod}@${ver}`);
102
- if (existingDir(dir)) roots.push({ kind: "Go", root: dir, packages: 1, pathToPkg: () => p.name });
103
- }
104
- }
105
- return roots;
106
- }
107
-
108
- export function buildContentRoots(repoPath, installed) {
109
- const roots = [];
110
- const nmDir = join(repoPath, "node_modules");
111
- const jsPkgDirs = existingDir(nmDir) ? listPkgDirs(nmDir) : [];
112
- if (jsPkgDirs.length) roots.push({ kind: "npm", root: nmDir, packages: jsPkgDirs.length, pathToPkg: pkgOfNodeModulesPath });
113
-
114
- for (const sp of sitePackageRoots(repoPath)) {
115
- const topMap = pyTopLevelMap(sp);
116
- let packages = 0;
117
- try { packages = readdirSync(sp).filter((e) => !e.startsWith(".") && !/\.dist-info$|\.egg-info$|__pycache__/i.test(e)).length; } catch { /* unreadable */ }
118
- roots.push({ kind: "PyPI", root: sp, packages, pathToPkg: (file) => pkgOfSitePackagesPath(file, sp, topMap) });
119
- }
120
-
121
- const vendorRoot = join(repoPath, "vendor");
122
- if (existingDir(vendorRoot)) {
123
- const modules = vendorModuleNames(installed);
124
- roots.push({ kind: "Go", root: vendorRoot, packages: modules.length || 1, pathToPkg: (file) => pkgOfVendorPath(file, vendorRoot, modules) });
125
- }
126
- roots.push(...goModuleSourceRoots(installed));
127
- return roots;
128
- }
129
-
130
- export function listPkgDirs(nmDir) {
131
- const out = [];
132
- let entries;
133
- try { entries = readdirSync(nmDir); } catch { return out; }
134
- for (const e of entries) {
135
- if (e.startsWith(".")) continue;
136
- if (e.startsWith("@")) {
137
- let scoped; try { scoped = readdirSync(join(nmDir, e)); } catch { continue; }
138
- for (const s of scoped) out.push({ pkg: `${e}/${s}`, dir: join(nmDir, e, s) });
139
- } else out.push({ pkg: e, dir: join(nmDir, e) });
140
- }
141
- return out;
142
- }
1
+ // Content roots + path-to-package mapping for the malware scanner (split out of
2
+ // malware-heuristics.js): npm node_modules, Python site-packages, Go vendor/ and module cache.
3
+ import { readFileSync, readdirSync, existsSync, statSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { delimiter, join, relative } from "node:path";
6
+ import { normPath } from "./malware-heuristics.exclusions.js";
7
+
8
+ const pep503 = (name) => String(name || "").toLowerCase().replace(/[-_.]+/g, "-");
9
+
10
+ // node_modules/@scope/name/... → @scope/name ; node_modules/name/... → name
11
+ export function pkgOfNodeModulesPath(p) {
12
+ const s = String(p).replace(/\\/g, "/");
13
+ const i = s.lastIndexOf("node_modules/");
14
+ if (i < 0) return "";
15
+ const rest = s.slice(i + "node_modules/".length).split("/");
16
+ return rest[0]?.startsWith("@") ? `${rest[0]}/${rest[1] || ""}` : rest[0] || "";
17
+ }
18
+
19
+ function existingDir(p) {
20
+ try { return p && existsSync(p) && statSync(p).isDirectory(); } catch { return false; }
21
+ }
22
+
23
+ function sitePackageRoots(repoPath) {
24
+ const roots = [];
25
+ for (const venv of [".venv", "venv", "env"]) {
26
+ const win = join(repoPath, venv, "Lib", "site-packages");
27
+ if (existingDir(win)) roots.push(win);
28
+ try {
29
+ for (const d of readdirSync(join(repoPath, venv, "lib"))) {
30
+ const posix = join(repoPath, venv, "lib", String(d), "site-packages");
31
+ if (/^python/i.test(String(d)) && existingDir(posix)) roots.push(posix);
32
+ }
33
+ } catch { /* no posix venv layout */ }
34
+ }
35
+ return [...new Set(roots.map((r) => join(r)))];
36
+ }
37
+
38
+ function pyTopLevelMap(sitePackagesRoot) {
39
+ const map = new Map();
40
+ let entries = [];
41
+ try { entries = readdirSync(sitePackagesRoot); } catch { return map; }
42
+ for (const e of entries) {
43
+ if (!/\.dist-info$/i.test(e)) continue;
44
+ const dist = e.replace(/-\d[\w.!+-]*\.dist-info$/i, "");
45
+ const canonical = pep503(dist);
46
+ try {
47
+ const top = readFileSync(join(sitePackagesRoot, e, "top_level.txt"), "utf8");
48
+ for (const line of top.split(/\r?\n/).map((x) => x.trim()).filter(Boolean)) map.set(line, canonical);
49
+ } catch { /* metadata often omits top_level.txt */ }
50
+ try {
51
+ const meta = readFileSync(join(sitePackagesRoot, e, "METADATA"), "utf8");
52
+ const m = meta.match(/^Name:\s*(.+)$/mi);
53
+ if (m) map.set(dist, pep503(m[1]));
54
+ } catch { /* no metadata */ }
55
+ }
56
+ return map;
57
+ }
58
+
59
+ function pkgOfSitePackagesPath(file, sitePackagesRoot, topMap) {
60
+ const rel = normPath(relative(sitePackagesRoot, file));
61
+ if (!rel || rel.startsWith("..")) return "";
62
+ const first = rel.split("/")[0] || "";
63
+ if (!first || first === "__pycache__") return "";
64
+ if (/\.dist-info$|\.egg-info$/i.test(first)) return "";
65
+ const top = first.replace(/\.(py|so|pyd|dll|pth)$/i, "");
66
+ return topMap.get(top) || pep503(top);
67
+ }
68
+
69
+ function vendorModuleNames(installed) {
70
+ return [...new Set((installed || []).filter((p) => p.ecosystem === "Go" && p.name).map((p) => String(p.name)))].sort((a, b) => b.length - a.length);
71
+ }
72
+
73
+ function pkgOfVendorPath(file, vendorRoot, moduleNames) {
74
+ const rel = normPath(relative(vendorRoot, file));
75
+ if (!rel || rel.startsWith("..")) return "";
76
+ for (const name of moduleNames) if (rel === name || rel.startsWith(`${name}/`)) return name;
77
+ const parts = rel.split("/");
78
+ if (parts[0]?.includes(".") && parts.length >= 3) return parts.slice(0, 3).join("/");
79
+ return parts.slice(0, 2).join("/") || parts[0] || "";
80
+ }
81
+
82
+ function goCacheRoots() {
83
+ const roots = [];
84
+ if (process.env.GOMODCACHE) roots.push(...String(process.env.GOMODCACHE).split(delimiter));
85
+ for (const gp of String(process.env.GOPATH || join(homedir(), "go")).split(delimiter)) roots.push(join(gp, "pkg", "mod"));
86
+ return [...new Set(roots.filter(existingDir))];
87
+ }
88
+
89
+ function goModCacheEscape(modulePath) {
90
+ return String(modulePath || "").split("/").map((part) => part.replace(/[A-Z]/g, (c) => `!${c.toLowerCase()}`)).join("/");
91
+ }
92
+
93
+ function goModuleSourceRoots(installed) {
94
+ const roots = [];
95
+ const caches = goCacheRoots();
96
+ const goPkgs = (installed || []).filter((p) => p.ecosystem === "Go" && p.name && p.version);
97
+ for (const p of goPkgs) {
98
+ const mod = goModCacheEscape(p.name);
99
+ const ver = String(p.version).startsWith("v") ? String(p.version) : `v${p.version}`;
100
+ for (const cache of caches) {
101
+ const dir = join(cache, `${mod}@${ver}`);
102
+ if (existingDir(dir)) roots.push({ kind: "Go", root: dir, packages: 1, pathToPkg: () => p.name });
103
+ }
104
+ }
105
+ return roots;
106
+ }
107
+
108
+ export function buildContentRoots(repoPath, installed) {
109
+ const roots = [];
110
+ const nmDir = join(repoPath, "node_modules");
111
+ const jsPkgDirs = existingDir(nmDir) ? listPkgDirs(nmDir) : [];
112
+ if (jsPkgDirs.length) roots.push({ kind: "npm", root: nmDir, packages: jsPkgDirs.length, pathToPkg: pkgOfNodeModulesPath });
113
+
114
+ for (const sp of sitePackageRoots(repoPath)) {
115
+ const topMap = pyTopLevelMap(sp);
116
+ let packages = 0;
117
+ try { packages = readdirSync(sp).filter((e) => !e.startsWith(".") && !/\.dist-info$|\.egg-info$|__pycache__/i.test(e)).length; } catch { /* unreadable */ }
118
+ roots.push({ kind: "PyPI", root: sp, packages, pathToPkg: (file) => pkgOfSitePackagesPath(file, sp, topMap) });
119
+ }
120
+
121
+ const vendorRoot = join(repoPath, "vendor");
122
+ if (existingDir(vendorRoot)) {
123
+ const modules = vendorModuleNames(installed);
124
+ roots.push({ kind: "Go", root: vendorRoot, packages: modules.length || 1, pathToPkg: (file) => pkgOfVendorPath(file, vendorRoot, modules) });
125
+ }
126
+ roots.push(...goModuleSourceRoots(installed));
127
+ return roots;
128
+ }
129
+
130
+ export function listPkgDirs(nmDir) {
131
+ const out = [];
132
+ let entries;
133
+ try { entries = readdirSync(nmDir); } catch { return out; }
134
+ for (const e of entries) {
135
+ if (e.startsWith(".")) continue;
136
+ if (e.startsWith("@")) {
137
+ let scoped; try { scoped = readdirSync(join(nmDir, e)); } catch { continue; }
138
+ for (const s of scoped) out.push({ pkg: `${e}/${s}`, dir: join(nmDir, e, s) });
139
+ } else out.push({ pkg: e, dir: join(nmDir, e) });
140
+ }
141
+ return out;
142
+ }