weavatrix 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +146 -0
- package/bin/weavatrix-mcp.mjs +6 -0
- package/package.json +50 -0
- package/skill/SKILL.md +56 -0
- package/src/analysis/coverage-reports.js +232 -0
- package/src/analysis/dead-check.js +136 -0
- package/src/analysis/dep-check.js +310 -0
- package/src/analysis/dep-rules.js +221 -0
- package/src/analysis/duplicates-worker.js +11 -0
- package/src/analysis/duplicates.compute.js +215 -0
- package/src/analysis/duplicates.js +15 -0
- package/src/analysis/duplicates.run.js +51 -0
- package/src/analysis/duplicates.tokenize.js +182 -0
- package/src/analysis/endpoints.js +156 -0
- package/src/analysis/findings.js +52 -0
- package/src/analysis/graph-analysis.aggregate.js +280 -0
- package/src/analysis/graph-analysis.js +7 -0
- package/src/analysis/graph-analysis.refs.js +146 -0
- package/src/analysis/graph-analysis.summaries.js +62 -0
- package/src/analysis/internal-audit.collect.js +117 -0
- package/src/analysis/internal-audit.js +9 -0
- package/src/analysis/internal-audit.reach.js +47 -0
- package/src/analysis/internal-audit.run.js +189 -0
- package/src/analysis/manifests.js +169 -0
- package/src/analysis/source-complexity.ast.js +97 -0
- package/src/analysis/source-complexity.constants.js +55 -0
- package/src/analysis/source-complexity.js +14 -0
- package/src/analysis/source-complexity.report.js +76 -0
- package/src/analysis/source-complexity.walk.js +174 -0
- package/src/build-graph.js +102 -0
- package/src/config.js +5 -0
- package/src/graph/build-worker.js +30 -0
- package/src/graph/builder/lang-csharp.js +40 -0
- package/src/graph/builder/lang-css.js +29 -0
- package/src/graph/builder/lang-go.js +53 -0
- package/src/graph/builder/lang-html.js +29 -0
- package/src/graph/builder/lang-java.js +29 -0
- package/src/graph/builder/lang-js.js +168 -0
- package/src/graph/builder/lang-python.js +78 -0
- package/src/graph/builder/lang-rust.js +45 -0
- package/src/graph/builder/spec-pkg.js +87 -0
- package/src/graph/graph-filter.js +44 -0
- package/src/graph/internal-builder.build.js +217 -0
- package/src/graph/internal-builder.js +12 -0
- package/src/graph/internal-builder.langs.js +86 -0
- package/src/graph/internal-builder.resolvers.js +116 -0
- package/src/graph/layout.js +35 -0
- package/src/infra/infra-items.js +255 -0
- package/src/infra/infra-registry.js +184 -0
- package/src/infra/infra.detect.js +119 -0
- package/src/infra/infra.js +38 -0
- package/src/infra/infra.match.js +102 -0
- package/src/infra/infra.scan.js +93 -0
- package/src/mcp/catalog.mjs +68 -0
- package/src/mcp/graph-context.mjs +276 -0
- package/src/mcp/tools-actions.mjs +132 -0
- package/src/mcp/tools-graph.mjs +274 -0
- package/src/mcp/tools-health.mjs +209 -0
- package/src/mcp/tools-impact.mjs +189 -0
- package/src/mcp-rg.mjs +51 -0
- package/src/mcp-server.mjs +171 -0
- package/src/mcp-source-tools.mjs +139 -0
- package/src/process.js +77 -0
- package/src/scan/discover.inventory.js +78 -0
- package/src/scan/discover.js +5 -0
- package/src/scan/discover.list.js +79 -0
- package/src/scan/discover.stack.js +227 -0
- package/src/scan/search.core.js +24 -0
- package/src/scan/search.git.js +102 -0
- package/src/scan/search.js +9 -0
- package/src/scan/search.node.js +83 -0
- package/src/scan/search.preview.js +49 -0
- package/src/scan/search.rg.js +145 -0
- package/src/security/advisory-store.js +177 -0
- package/src/security/installed.js +247 -0
- package/src/security/malware-file-heuristics.js +121 -0
- package/src/security/malware-heuristics.exclusions.js +134 -0
- package/src/security/malware-heuristics.js +15 -0
- package/src/security/malware-heuristics.roots.js +142 -0
- package/src/security/malware-heuristics.scan.js +87 -0
- package/src/security/malware-heuristics.sweep.js +122 -0
- package/src/security/malware-scoring.js +84 -0
- package/src/security/match.js +85 -0
- package/src/security/registry-sig.classify.js +136 -0
- package/src/security/registry-sig.js +18 -0
- package/src/security/registry-sig.rules.js +188 -0
- package/src/security/typosquat.js +72 -0
- package/src/util.js +27 -0
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { readFileSync, readdirSync, existsSync, statSync, openSync, readSync, closeSync } from "node:fs";
|
|
2
|
+
import { join, relative } from "node:path";
|
|
3
|
+
import { MALWARE_ALLOWLIST, classifyPythonPth } from "./registry-sig.js";
|
|
4
|
+
|
|
5
|
+
const normPath = (p) => String(p || "").replace(/\\/g, "/").replace(/\/+$/, "");
|
|
6
|
+
const existingDir = (p) => {
|
|
7
|
+
try { return p && existsSync(p) && statSync(p).isDirectory(); } catch { return false; }
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
const PY_PTH_RE = /\.pth$/i;
|
|
11
|
+
const BINARY_CANDIDATE_RE = /\.(exe|dll|dylib|so|node|bin)$/i;
|
|
12
|
+
const BINARY_SUSPICIOUS_NAME_RE = /(^|[\\/])(postinstall|install|setup|update|loader|payload|helper|agent|service|runner)(\.[^\\/]+)?$/i;
|
|
13
|
+
const NATIVE_SCRIPT_RE = /\b(node-gyp|node-pre-gyp|prebuild|node-gyp-build|cmake-js|cmake|make|napi|neon|cargo|go\s+build)\b/i;
|
|
14
|
+
const NATIVE_DEP_RE = /^(node-addon-api|bindings|nan|prebuild-install|node-gyp|node-gyp-build|node-pre-gyp|@mapbox\/node-pre-gyp|cmake-js)$/i;
|
|
15
|
+
const KNOWN_BINARY_PKG_RE = /^(?:@esbuild\/|@swc\/|@rollup\/rollup-|@img\/|@parcel\/watcher|esbuild$|sharp$|electron$|playwright$|@playwright\/|puppeteer$|cypress$|sass-embedded$|lightningcss$|tree-sitter$|tree-sitter-wasms$|better-sqlite3$|sqlite3$|bcrypt$|fsevents$|re2$|canvas$|workerd$)/i;
|
|
16
|
+
const BUNDLED_BINARY_RULE = {
|
|
17
|
+
key: "bundled-binary",
|
|
18
|
+
severity: "medium",
|
|
19
|
+
nearZeroFp: false,
|
|
20
|
+
noisy: true,
|
|
21
|
+
what: "bundled executable/native binary without native-build package metadata",
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
function readJsonFile(file) {
|
|
25
|
+
try { return JSON.parse(readFileSync(file, "utf8")); } catch { return null; }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function hasNativeBuildHint(dir, pkgJson) {
|
|
29
|
+
const pj = pkgJson || {};
|
|
30
|
+
if (pj.gypfile || pj.binary || pj.os || pj.cpu) return true;
|
|
31
|
+
if (existingDir(join(dir, "prebuilds")) || existsSync(join(dir, "binding.gyp"))) return true;
|
|
32
|
+
const scriptText = Object.values(pj.scripts || {}).join("\n");
|
|
33
|
+
if (NATIVE_SCRIPT_RE.test(scriptText)) return true;
|
|
34
|
+
const deps = { ...(pj.dependencies || {}), ...(pj.optionalDependencies || {}), ...(pj.devDependencies || {}) };
|
|
35
|
+
return Object.keys(deps).some((name) => NATIVE_DEP_RE.test(name));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function binaryMagic(file) {
|
|
39
|
+
let fd = null;
|
|
40
|
+
try {
|
|
41
|
+
fd = openSync(file, "r");
|
|
42
|
+
const b = Buffer.alloc(8);
|
|
43
|
+
const n = readSync(fd, b, 0, b.length, 0);
|
|
44
|
+
if (n >= 2 && b[0] === 0x4d && b[1] === 0x5a) return "PE";
|
|
45
|
+
if (n >= 4 && b[0] === 0x7f && b[1] === 0x45 && b[2] === 0x4c && b[3] === 0x46) return "ELF";
|
|
46
|
+
if (n >= 4) {
|
|
47
|
+
const hex = b.subarray(0, 4).toString("hex");
|
|
48
|
+
if (["feedface", "feedfacf", "cefaedfe", "cffaedfe", "cafebabe", "cafebabf"].includes(hex)) return "Mach-O";
|
|
49
|
+
}
|
|
50
|
+
} catch { /* not readable */ }
|
|
51
|
+
finally { if (fd != null) { try { closeSync(fd); } catch { /* ignore */ } } }
|
|
52
|
+
return "";
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function shouldSkipMetaPath(rel) {
|
|
56
|
+
const p = normPath(rel).toLowerCase();
|
|
57
|
+
return /(^|\/)(node_modules|\.git|docs?|documentation|test|tests|__tests__|fixtures?|examples?|coverage|dist-types)(\/|$)/.test(p) || /\.(map|md|mdx|markdown|rst|txt|d\.ts)$/i.test(p);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function binaryArtifactSweep(pkgDirs, capFiles = 12000) {
|
|
61
|
+
const hits = [];
|
|
62
|
+
let seen = 0;
|
|
63
|
+
for (const { pkg, dir } of pkgDirs) {
|
|
64
|
+
if (seen >= capFiles) break;
|
|
65
|
+
if (MALWARE_ALLOWLIST.has(pkg) || KNOWN_BINARY_PKG_RE.test(pkg)) continue;
|
|
66
|
+
const pj = readJsonFile(join(dir, "package.json")) || {};
|
|
67
|
+
if (hasNativeBuildHint(dir, pj)) continue;
|
|
68
|
+
const stack = [dir];
|
|
69
|
+
while (stack.length && seen < capFiles) {
|
|
70
|
+
const cur = stack.pop();
|
|
71
|
+
let entries = [];
|
|
72
|
+
try { entries = readdirSync(cur, { withFileTypes: true }); } catch { continue; }
|
|
73
|
+
for (const e of entries) {
|
|
74
|
+
const full = join(cur, e.name);
|
|
75
|
+
const rel = relative(dir, full);
|
|
76
|
+
if (shouldSkipMetaPath(rel)) continue;
|
|
77
|
+
if (e.isDirectory()) { stack.push(full); continue; }
|
|
78
|
+
if (!e.isFile()) continue;
|
|
79
|
+
seen++;
|
|
80
|
+
if (!BINARY_CANDIDATE_RE.test(e.name) && !BINARY_SUSPICIOUS_NAME_RE.test(full)) continue;
|
|
81
|
+
let st; try { st = statSync(full); } catch { continue; }
|
|
82
|
+
if (!st.size || st.size > 80_000_000) continue;
|
|
83
|
+
const kind = binaryMagic(full);
|
|
84
|
+
if (!kind) continue;
|
|
85
|
+
hits.push({
|
|
86
|
+
pkg,
|
|
87
|
+
file: full,
|
|
88
|
+
line: 0,
|
|
89
|
+
text: `${kind} binary ${normPath(rel)} in package with no native-build metadata`,
|
|
90
|
+
rule: BUNDLED_BINARY_RULE,
|
|
91
|
+
});
|
|
92
|
+
break;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return hits;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function pythonPthSweep(contentRoots) {
|
|
100
|
+
const hits = [];
|
|
101
|
+
for (const root of contentRoots) {
|
|
102
|
+
if (root.kind !== "PyPI") continue;
|
|
103
|
+
let entries = [];
|
|
104
|
+
try { entries = readdirSync(root.root, { withFileTypes: true }); } catch { continue; }
|
|
105
|
+
for (const e of entries) {
|
|
106
|
+
if (!e.isFile() || !PY_PTH_RE.test(e.name)) continue;
|
|
107
|
+
const file = join(root.root, e.name);
|
|
108
|
+
let text = "";
|
|
109
|
+
try { text = readFileSync(file, "utf8"); } catch { continue; }
|
|
110
|
+
const pkg = root.pathToPkg(file) || e.name.replace(PY_PTH_RE, "");
|
|
111
|
+
for (const sig of classifyPythonPth(text)) {
|
|
112
|
+
hits.push({ pkg, file, line: sig.line || 0, text: sig.snippet || "", rule: sig });
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return hits;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function fileHeuristicSweep(contentRoots, pkgDirs) {
|
|
120
|
+
return [...pythonPthSweep(contentRoots), ...binaryArtifactSweep(pkgDirs)];
|
|
121
|
+
}
|
|
@@ -0,0 +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
|
+
}
|
|
@@ -0,0 +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";
|
|
@@ -0,0 +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
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// scanMalware orchestration (split out of malware-heuristics.js): phase A install scripts +
|
|
2
|
+
// lockfile origins, phase B content sweep, path-aware file heuristics, then scoring.
|
|
3
|
+
import { readFileSync, existsSync } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { resolveRg } from "../scan/search.js";
|
|
6
|
+
import { classifyInstallScript, classifyResolvedUrl, isCloudSdkMetadataUse } from "./registry-sig.js";
|
|
7
|
+
import { fileHeuristicSweep } from "./malware-file-heuristics.js";
|
|
8
|
+
import { buildMalwareFindings } from "./malware-scoring.js";
|
|
9
|
+
import { parseMalwareExclusions, isManifestUrlNoise, isDocUrlNoise, isMalwareSignalExcluded, lifecycleScriptSnippet } from "./malware-heuristics.exclusions.js";
|
|
10
|
+
import { buildContentRoots, listPkgDirs } from "./malware-heuristics.roots.js";
|
|
11
|
+
import { rgSweep, nodeSweep } from "./malware-heuristics.sweep.js";
|
|
12
|
+
|
|
13
|
+
// → { findings, scanMode } ; importedPkgs = Set of packages the repo's own code imports (evidence note).
|
|
14
|
+
export async function scanMalware(repoPath, { installed = [], importedPkgs = new Set(), rgPath = "", forceNode = false, timeoutMs = 60000, malwareExclusions = {} } = {}) {
|
|
15
|
+
const nmDir = join(repoPath, "node_modules");
|
|
16
|
+
const contentRoots = buildContentRoots(repoPath, installed);
|
|
17
|
+
const byPkg = new Map(); // pkg -> [{rule signal, file, line, snippet}]
|
|
18
|
+
const exclusions = parseMalwareExclusions(malwareExclusions);
|
|
19
|
+
let excludedSignals = 0;
|
|
20
|
+
const add = (pkg, sig, file = "", line = 0, snippet = "") => {
|
|
21
|
+
if (!pkg) return;
|
|
22
|
+
const signal = { ...sig, file, line, snippet: snippet || sig.snippet || "" };
|
|
23
|
+
if (isManifestUrlNoise(file, signal) || isDocUrlNoise(file, signal) || isCloudSdkMetadataUse(pkg, signal.key) || isMalwareSignalExcluded(pkg, signal, exclusions)) {
|
|
24
|
+
excludedSignals++;
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
(byPkg.get(pkg) || byPkg.set(pkg, []).get(pkg)).push(signal);
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
// ---- phase A: install scripts (from node_modules package.jsons) + lockfile resolved origins ----
|
|
31
|
+
const pkgDirs = existsSync(nmDir) ? listPkgDirs(nmDir) : [];
|
|
32
|
+
const lockScriptMeta = new Map(
|
|
33
|
+
(installed || [])
|
|
34
|
+
.filter((p) => p.ecosystem === "npm" && p.source === "package-lock" && p.hasInstallScript !== undefined)
|
|
35
|
+
.map((p) => [`${p.name}@${p.version}`, !!p.hasInstallScript])
|
|
36
|
+
);
|
|
37
|
+
for (const { pkg, dir } of pkgDirs) {
|
|
38
|
+
try {
|
|
39
|
+
const pj = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
|
|
40
|
+
const scriptSnippet = lifecycleScriptSnippet(pj.scripts);
|
|
41
|
+
if (scriptSnippet && lockScriptMeta.get(`${pkg}@${pj.version || ""}`) === false) {
|
|
42
|
+
add(pkg, {
|
|
43
|
+
key: "install-script-drift",
|
|
44
|
+
severity: "high",
|
|
45
|
+
nearZeroFp: false,
|
|
46
|
+
what: "installed package has lifecycle scripts absent from package-lock metadata",
|
|
47
|
+
snippet: scriptSnippet,
|
|
48
|
+
}, join(dir, "package.json"));
|
|
49
|
+
}
|
|
50
|
+
for (const sig of classifyInstallScript(pj.scripts)) add(pkg, sig, join(dir, "package.json"));
|
|
51
|
+
} catch { /* not a package */ }
|
|
52
|
+
}
|
|
53
|
+
for (const p of installed) {
|
|
54
|
+
const sig = p.resolved ? classifyResolvedUrl(p.resolved) : null;
|
|
55
|
+
if (sig) add(p.name, sig, "package-lock.json");
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// ---- phase B: content sweep ----
|
|
59
|
+
let scanMode = "none";
|
|
60
|
+
if (contentRoots.length) {
|
|
61
|
+
const rg = forceNode ? null : await resolveRg("auto", rgPath);
|
|
62
|
+
let swept = false;
|
|
63
|
+
if (rg) {
|
|
64
|
+
const { hits, errored, total } = await rgSweep(rg, contentRoots, timeoutMs);
|
|
65
|
+
if (errored < total) {
|
|
66
|
+
// honest label: full when every rule ran, partial when some rules failed (don't claim
|
|
67
|
+
// full coverage we didn't get); every-rule-failed falls through to the Node sweep below.
|
|
68
|
+
const kinds = [...new Set(contentRoots.map((r) => r.kind))].join("+");
|
|
69
|
+
scanMode = errored ? `ripgrep-partial (${total - errored}/${total} sweeps; ${kinds})` : `ripgrep-full (${kinds})`;
|
|
70
|
+
swept = true;
|
|
71
|
+
for (const h of hits) add(h.pkg, h.rule, h.file, h.line, h.text);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
if (!swept) {
|
|
75
|
+
scanMode = rg ? "node-limited (ripgrep failed)" : "node-limited";
|
|
76
|
+
for (const h of nodeSweep(nmDir, pkgDirs)) add(h.pkg, h.rule, h.file, h.line, h.text);
|
|
77
|
+
}
|
|
78
|
+
} else {
|
|
79
|
+
scanMode = "skipped";
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// ---- path-aware cheap checks: things that need file names or magic bytes, not just regex text.
|
|
83
|
+
// These run regardless of rg availability and stay bounded; content regex still does the broad sweep.
|
|
84
|
+
for (const h of fileHeuristicSweep(contentRoots, pkgDirs)) add(h.pkg, h.rule, h.file, h.line, h.text);
|
|
85
|
+
|
|
86
|
+
return buildMalwareFindings({ byPkg, importedPkgs, contentRoots, scanMode, excludedSignals });
|
|
87
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
// Content sweeps for the malware scanner (split out of malware-heuristics.js): a ripgrep sweep
|
|
2
|
+
// over all content roots when rg is available, else a bounded Node fallback over entry files.
|
|
3
|
+
import { readFileSync, readdirSync, existsSync, statSync } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { runCommand } from "../process.js";
|
|
6
|
+
import { CONTENT_RULES, classifyContent } from "./registry-sig.js";
|
|
7
|
+
import { normPath } from "./malware-heuristics.exclusions.js";
|
|
8
|
+
|
|
9
|
+
const SKIP_GLOBS = [
|
|
10
|
+
"!**/*.map", "!**/*.md", "!**/*.mdx", "!**/*.markdown", "!**/*.mdown", "!**/*.mkd", "!**/*.rst", "!**/*.d.ts",
|
|
11
|
+
"!**/doc/**", "!**/docs/**", "!**/documentation/**",
|
|
12
|
+
"!**/test/**", "!**/tests/**", "!**/__tests__/**", "!**/fixtures/**", "!**/example/**", "!**/examples/**"
|
|
13
|
+
];
|
|
14
|
+
|
|
15
|
+
function globalRuleRegex(rule) {
|
|
16
|
+
const flags = rule.re.flags.includes("g") ? rule.re.flags : `${rule.re.flags}g`;
|
|
17
|
+
return new RegExp(rule.re.source, flags);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function matchRuleOffsets(rule, lineText, subText = "") {
|
|
21
|
+
const text = String(lineText || "");
|
|
22
|
+
if (text) {
|
|
23
|
+
const offsets = [];
|
|
24
|
+
const re = globalRuleRegex(rule);
|
|
25
|
+
let guard = 0;
|
|
26
|
+
let m;
|
|
27
|
+
while ((m = re.exec(text)) && guard++ < 24) {
|
|
28
|
+
offsets.push(m.index);
|
|
29
|
+
if (!m[0].length) re.lastIndex++;
|
|
30
|
+
}
|
|
31
|
+
if (!offsets.length && rule.key === "obfuscated-code") {
|
|
32
|
+
const at = subText ? text.indexOf(subText) : 0;
|
|
33
|
+
if (at >= 0) offsets.push(at);
|
|
34
|
+
}
|
|
35
|
+
return offsets;
|
|
36
|
+
}
|
|
37
|
+
if (subText && (rule.key === "obfuscated-code" || rule.re.test(subText))) return [0];
|
|
38
|
+
return [];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function rootOfFile(file, roots) {
|
|
42
|
+
const f = normPath(file).toLowerCase();
|
|
43
|
+
return roots.find((r) => {
|
|
44
|
+
const root = normPath(r.root).toLowerCase();
|
|
45
|
+
return f === root || f.startsWith(`${root}/`);
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function chunks(list, size) {
|
|
50
|
+
const out = [];
|
|
51
|
+
for (let i = 0; i < list.length; i += size) out.push(list.slice(i, i + size));
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export async function rgSweep(rg, contentRoots, timeoutMs) {
|
|
56
|
+
const hits = []; // {pkg, file, line, text, rule}
|
|
57
|
+
let errored = 0; // a failed/broken rule must not masquerade as "scanned, 0 hits"
|
|
58
|
+
let total = 0;
|
|
59
|
+
for (const rule of CONTENT_RULES) {
|
|
60
|
+
for (const group of chunks(contentRoots, 40)) {
|
|
61
|
+
total++;
|
|
62
|
+
const args = ["--json", "-i", "--no-ignore", "--hidden", "--follow", "--max-filesize", "2M", "--max-count", "20", ...SKIP_GLOBS.flatMap((g) => ["-g", g]), "-e", rule.pattern, "--", ...group.map((r) => r.root)];
|
|
63
|
+
let r;
|
|
64
|
+
try { r = await runCommand(rg, args, { timeoutMs }); } catch { errored++; continue; }
|
|
65
|
+
if (r.exitCode === 2 && !String(r.stdout || "").trim()) { errored++; continue; }
|
|
66
|
+
for (const line of String(r.stdout || "").split(/\r?\n/)) {
|
|
67
|
+
if (!line) continue;
|
|
68
|
+
let obj; try { obj = JSON.parse(line); } catch { continue; }
|
|
69
|
+
if (obj.type !== "match") continue;
|
|
70
|
+
const file = obj.data?.path?.text || "";
|
|
71
|
+
const root = rootOfFile(file, group);
|
|
72
|
+
const pkg = root?.pathToPkg(file) || "";
|
|
73
|
+
if (!pkg) continue;
|
|
74
|
+
const lineText = String(obj.data?.lines?.text || "");
|
|
75
|
+
const subText = String(obj.data?.submatches?.[0]?.match?.text || "");
|
|
76
|
+
for (const at of matchRuleOffsets(rule, lineText, subText)) {
|
|
77
|
+
const text = (lineText ? lineText.slice(Math.max(0, at - 60), at + 180) : subText).trim().slice(0, 240);
|
|
78
|
+
hits.push({ pkg, file, line: obj.data?.line_number || 0, text, rule });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return { hits, errored, total };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// no-rg fallback: each package's package.json main/bin entries + root JS files, bounded
|
|
87
|
+
export function nodeSweep(nmDir, pkgDirs, capFiles = 3000) {
|
|
88
|
+
const hits = [];
|
|
89
|
+
let seenFiles = 0;
|
|
90
|
+
for (const { pkg, dir } of pkgDirs) {
|
|
91
|
+
if (seenFiles >= capFiles) break;
|
|
92
|
+
let pj = null;
|
|
93
|
+
try { pj = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")); } catch { continue; }
|
|
94
|
+
const cands = new Set();
|
|
95
|
+
for (const f of [pj.main, pj.module, pj.browser]) if (typeof f === "string") cands.add(f);
|
|
96
|
+
if (pj.bin) for (const b of typeof pj.bin === "string" ? [pj.bin] : Object.values(pj.bin)) cands.add(b);
|
|
97
|
+
let rootJs = [];
|
|
98
|
+
try { rootJs = readdirSync(dir).filter((f) => /\.(c|m)?js$/.test(f)).slice(0, 6); } catch { /* gone */ }
|
|
99
|
+
for (const f of rootJs) cands.add(f);
|
|
100
|
+
if (!cands.size) cands.add("index.js");
|
|
101
|
+
for (const rel of cands) {
|
|
102
|
+
if (seenFiles >= capFiles) break;
|
|
103
|
+
const full = join(dir, String(rel));
|
|
104
|
+
try {
|
|
105
|
+
if (!existsSync(full) || statSync(full).size > 2_000_000) continue;
|
|
106
|
+
seenFiles++;
|
|
107
|
+
const text = readFileSync(full, "utf8");
|
|
108
|
+
for (const rule of classifyContent(text)) {
|
|
109
|
+
for (const at of matchRuleOffsets(rule, text)) {
|
|
110
|
+
// snippet keeps up to 60 chars of same-line PRE-context (like the rg path) so the
|
|
111
|
+
// comment/doc-context noise filter can see "// see" markers before the match
|
|
112
|
+
const lineStart = text.lastIndexOf("\n", at) + 1;
|
|
113
|
+
const nl = text.indexOf("\n", at);
|
|
114
|
+
const snippet = text.slice(Math.max(lineStart, at - 60), Math.min(nl < 0 ? text.length : nl, at + 200)).trim().slice(0, 240);
|
|
115
|
+
hits.push({ pkg, file: full, line: at >= 0 ? text.slice(0, at).split("\n").length : 0, text: snippet, rule });
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
} catch { /* unreadable */ }
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return hits;
|
|
122
|
+
}
|