dsh-plugin-explorer 0.1.2 → 0.2.1
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/README.md +48 -15
- package/client.js +405 -21
- package/index.js +64 -9
- package/lib/gate/LICENSE +21 -0
- package/lib/gate/osv.js +116 -0
- package/lib/gate/rules.js +628 -0
- package/lib/gate/scan.js +609 -0
- package/lib/gate/targz.js +146 -0
- package/lib/gate-scan.js +144 -0
- package/lib/installed.js +86 -0
- package/lib/npm.js +109 -0
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +2 -2
- package/scripts/verify.mjs +64 -6
package/lib/gate/scan.js
ADDED
|
@@ -0,0 +1,609 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-plugin-gate — scan orchestration and verdict aggregation.
|
|
3
|
+
*
|
|
4
|
+
* Pure module apart from node:path: no DSH/Cordis imports, unit-testable in
|
|
5
|
+
* isolation. Scans either a directory through an injected fs adapter (the
|
|
6
|
+
* host's sandboxed ctx.fs in production, node:fs in tests) or an npm
|
|
7
|
+
* tarball through lib/targz.js. Reads only; never executes scanned content
|
|
8
|
+
* and never writes.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
import { CATEGORY, SEVERITY_WEIGHT, extractHosts, hasReadAndSend, scanText } from "./rules.js";
|
|
13
|
+
import { checkOsvDeps, exactVersionDeps } from "./osv.js";
|
|
14
|
+
|
|
15
|
+
/** File extensions treated as opaque binary blobs (skipped for text scan). */
|
|
16
|
+
export const BINARY_EXTENSIONS = new Set([
|
|
17
|
+
".exe", ".dll", ".so", ".dylib", ".bin", ".class", ".pyc", ".pyo",
|
|
18
|
+
".jar", ".war", ".zip", ".gz", ".tgz", ".7z", ".rar", ".woff", ".woff2",
|
|
19
|
+
".ttf", ".otf", ".eot", ".png", ".jpg", ".jpeg", ".gif", ".webp", ".ico",
|
|
20
|
+
".pdf", ".mp3", ".mp4", ".avi", ".mov", ".wasm", ".node", ".o", ".a",
|
|
21
|
+
]);
|
|
22
|
+
|
|
23
|
+
/** Directories never descended into during a scan. */
|
|
24
|
+
export const SKIP_DIRS = new Set([".git", ".npm-cache", ".venv", "__pycache__", ".hg", ".svn"]);
|
|
25
|
+
|
|
26
|
+
const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "::1", "0.0.0.0", "[::1]"]);
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Rules whose hits depend on execution context: a hit in prose (docs) or a
|
|
30
|
+
* comment is a description, not behavior, and is downgraded to low so
|
|
31
|
+
* documentation examples do not BLOCK an otherwise clean package.
|
|
32
|
+
*/
|
|
33
|
+
export const CODE_CONTEXT_RULES = new Set([
|
|
34
|
+
"exec_sync", "exec_api", "spawn_call", "shell_true", "download_cmd",
|
|
35
|
+
"pipe_to_shell", "ps_encoded", "ps_iex", "cmd_launch", "rm_recursive",
|
|
36
|
+
"eval_call", "new_function", "function_ctor", "vm_run", "fromcharcode",
|
|
37
|
+
"atob_call", "hex_escapes", "uni_escapes", "char_array", "dynamic_require",
|
|
38
|
+
"env_in_cmd",
|
|
39
|
+
]);
|
|
40
|
+
|
|
41
|
+
/** Documentation-ish extensions: code-context hits there are prose. */
|
|
42
|
+
const DOC_EXTS = new Set([".md", ".markdown", ".rst", ".txt", ".html", ".htm", ".mdx"]);
|
|
43
|
+
|
|
44
|
+
/** @param {string} rel - relative path. */
|
|
45
|
+
function isDocFile(rel) {
|
|
46
|
+
return DOC_EXTS.has(path.extname(rel).toLowerCase());
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** @param {string|undefined} line - trimmed line text. */
|
|
50
|
+
function isCommentLine(line) {
|
|
51
|
+
const t = String(line || "").trimStart();
|
|
52
|
+
return /^(\/\/|#|\/\*|\*|;|--|<!--)/.test(t);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Extract one line of content (1-based). */
|
|
56
|
+
function lineTextOf(content, lineNo) {
|
|
57
|
+
const lines = content.split(/\r?\n/);
|
|
58
|
+
return lines[lineNo - 1] || "";
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Dependency specs that install from git, http or local file paths. */
|
|
62
|
+
const RISKY_DEP_RE = /^(git(\+[\w-]+)?:|https?:\/\/|file:)/;
|
|
63
|
+
|
|
64
|
+
/** @param {string} rel - relative file path. */
|
|
65
|
+
export function isBinaryName(rel) {
|
|
66
|
+
const ext = path.extname(rel).toLowerCase();
|
|
67
|
+
return BINARY_EXTENSIONS.has(ext);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Parse a package.json body for install-time risk surface.
|
|
72
|
+
* @param {string} text - raw package.json content.
|
|
73
|
+
* @returns {{ok:boolean, name?:string, version?:string, lifecycle?:Array<{script:string, body:string}>, hasDshBundle?:boolean, dependencyCount?:number, parseError?:string}}
|
|
74
|
+
*/
|
|
75
|
+
export function parsePackageJson(text) {
|
|
76
|
+
let pkg;
|
|
77
|
+
try {
|
|
78
|
+
pkg = JSON.parse(text);
|
|
79
|
+
} catch (e) {
|
|
80
|
+
return { ok: false, parseError: String(e && e.message || e) };
|
|
81
|
+
}
|
|
82
|
+
const lifecycle = [];
|
|
83
|
+
const scripts = pkg.scripts && typeof pkg.scripts === "object" ? pkg.scripts : {};
|
|
84
|
+
for (const key of Object.keys(scripts)) {
|
|
85
|
+
if (/^(pre|post)?(install|uninstall|prepare|prepublish|publish|link)\b/.test(key) || key === "install" || key === "preinstall" || key === "postinstall") {
|
|
86
|
+
lifecycle.push({ script: key, body: String(scripts[key]).slice(0, 500) });
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
const depCount = (pkg.dependencies ? Object.keys(pkg.dependencies).length : 0)
|
|
90
|
+
+ (pkg.devDependencies ? Object.keys(pkg.devDependencies).length : 0)
|
|
91
|
+
+ (pkg.peerDependencies ? Object.keys(pkg.peerDependencies).length : 0);
|
|
92
|
+
const depMap = {};
|
|
93
|
+
for (const field of ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]) {
|
|
94
|
+
const deps = pkg[field];
|
|
95
|
+
if (deps && typeof deps === "object") {
|
|
96
|
+
for (const [name, spec] of Object.entries(deps)) {
|
|
97
|
+
if (depMap[name] === undefined) depMap[name] = spec;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
const riskyDependencies = [];
|
|
102
|
+
for (const field of ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]) {
|
|
103
|
+
const deps = pkg[field];
|
|
104
|
+
if (deps && typeof deps === "object") {
|
|
105
|
+
for (const [name, spec] of Object.entries(deps)) {
|
|
106
|
+
if (typeof spec === "string" && RISKY_DEP_RE.test(spec)) {
|
|
107
|
+
riskyDependencies.push({ name, spec: spec.slice(0, 200), field });
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return {
|
|
113
|
+
ok: true,
|
|
114
|
+
name: pkg.name,
|
|
115
|
+
version: pkg.version,
|
|
116
|
+
lifecycle,
|
|
117
|
+
riskyDependencies,
|
|
118
|
+
depMap,
|
|
119
|
+
hasDshBundle: Boolean(pkg.dsh && pkg.dsh.bundle),
|
|
120
|
+
dependencyCount: depCount,
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Scan one file's text content. package.json gets an extra structural pass
|
|
126
|
+
* (lifecycle scripts become hits).
|
|
127
|
+
* @param {{rel:string, content:string}} file
|
|
128
|
+
* @returns {{hits:Array, notes:Array}}
|
|
129
|
+
*/
|
|
130
|
+
export function scanFileText(file) {
|
|
131
|
+
const hits = [];
|
|
132
|
+
const notes = [];
|
|
133
|
+
const docFile = isDocFile(file.rel);
|
|
134
|
+
const usesChildProcess = /\b(child_process|node:child_process)\b/.test(file.content);
|
|
135
|
+
const textHits = scanText(file.rel, file.content).map((h) => {
|
|
136
|
+
if (h.rule === "exec_api" && !usesChildProcess) {
|
|
137
|
+
return {
|
|
138
|
+
...h,
|
|
139
|
+
severity: "low",
|
|
140
|
+
hint: h.hint + " (no child_process import in this file — likely RegExp#exec or a custom function)",
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
if (h.rule === "exec_sync" && !usesChildProcess) {
|
|
144
|
+
return { ...h, severity: "medium", hint: h.hint + " (no child_process import in this file)" };
|
|
145
|
+
}
|
|
146
|
+
// Execution-context rules describe behavior only in code. In docs or
|
|
147
|
+
// comments they are prose examples — downgrade so documentation does not
|
|
148
|
+
// BLOCK an otherwise clean package. Secrets/network rules stay as-is
|
|
149
|
+
// even in comments (a leaked key or webhook is still a leak).
|
|
150
|
+
if (CODE_CONTEXT_RULES.has(h.rule) && (docFile || isCommentLine(lineTextOf(file.content, h.line)))) {
|
|
151
|
+
return {
|
|
152
|
+
...h,
|
|
153
|
+
severity: "low",
|
|
154
|
+
hint: h.hint + " (found in " + (docFile ? "documentation" : "a comment") + " — likely an example, not behavior)",
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
return h;
|
|
158
|
+
});
|
|
159
|
+
for (const h of textHits) hits.push(h);
|
|
160
|
+
if (/package\.json$/.test(file.rel)) {
|
|
161
|
+
const pkg = parsePackageJson(file.content);
|
|
162
|
+
if (pkg.ok) {
|
|
163
|
+
for (const l of pkg.lifecycle || []) {
|
|
164
|
+
const sev = /(curl|wget|download|powershell|cmd|exec|eval|http)/i.test(l.body) ? "high" : "medium";
|
|
165
|
+
hits.push({
|
|
166
|
+
rule: "lifecycle_script",
|
|
167
|
+
category: CATEGORY.SCRIPTS,
|
|
168
|
+
severity: sev,
|
|
169
|
+
file: file.rel,
|
|
170
|
+
line: 1,
|
|
171
|
+
count: 1,
|
|
172
|
+
evidence: l.script + ": " + l.body.slice(0, 180),
|
|
173
|
+
hint: "npm runs lifecycle scripts during install; execute only what you have audited.",
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
for (const d of pkg.riskyDependencies || []) {
|
|
177
|
+
hits.push({
|
|
178
|
+
rule: "risky_dependency",
|
|
179
|
+
category: CATEGORY.SCRIPTS,
|
|
180
|
+
severity: "medium",
|
|
181
|
+
file: file.rel,
|
|
182
|
+
line: 1,
|
|
183
|
+
count: 1,
|
|
184
|
+
evidence: d.field + "." + d.name + ": " + d.spec,
|
|
185
|
+
hint: "Dependency installed from git/http/file — supply-chain risk; pin a registry version instead.",
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
} else {
|
|
189
|
+
notes.push({ file: file.rel, kind: "package-parse", detail: pkg.parseError || "invalid package.json" });
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
if (/\.[jt]sx?$/i.test(file.rel)) {
|
|
193
|
+
const lines = file.content.split(/\r?\n/);
|
|
194
|
+
for (let i = 0; i < lines.length; i++) {
|
|
195
|
+
if (lines[i].length > 4000) {
|
|
196
|
+
hits.push({
|
|
197
|
+
rule: "minified_line",
|
|
198
|
+
category: CATEGORY.OBFUSCATION,
|
|
199
|
+
severity: "low",
|
|
200
|
+
file: file.rel,
|
|
201
|
+
line: i + 1,
|
|
202
|
+
count: 1,
|
|
203
|
+
evidence: "line of " + lines[i].length + " chars (>4000)",
|
|
204
|
+
hint: "Very long minified line is hard to review; prefer source maps.",
|
|
205
|
+
});
|
|
206
|
+
break;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
if (hasReadAndSend(file.content)) {
|
|
211
|
+
hits.push({
|
|
212
|
+
rule: "data_exfil_heuristic",
|
|
213
|
+
category: CATEGORY.NETWORK,
|
|
214
|
+
severity: "medium",
|
|
215
|
+
file: file.rel,
|
|
216
|
+
line: 1,
|
|
217
|
+
count: 1,
|
|
218
|
+
evidence: "same file reads local data and sends network requests",
|
|
219
|
+
hint: "Reads local files and performs network I/O in one module — the classic exfiltration shape. Verify data flow.",
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
let pkg;
|
|
223
|
+
if (/package\.json$/.test(file.rel)) {
|
|
224
|
+
const parsed = parsePackageJson(file.content);
|
|
225
|
+
if (parsed.ok) pkg = parsed;
|
|
226
|
+
}
|
|
227
|
+
return { hits, notes, pkg };
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* Walk a directory via an injected fs adapter and scan every file.
|
|
232
|
+
* fs adapter surface (subset of ctx.fs):
|
|
233
|
+
* resolve(path, opts?) -> target
|
|
234
|
+
* processPath(target) -> string
|
|
235
|
+
* listDir(target, signal?) -> [{name, type, target, size?}]
|
|
236
|
+
* readText(target, signal?) -> string
|
|
237
|
+
* @param {object} fs - fs adapter.
|
|
238
|
+
* @param {object} rootTarget - resolved root target.
|
|
239
|
+
* @param {{maxFiles?:number, maxFileBytes?:number, includeNodeModules?:boolean}} [opts]
|
|
240
|
+
* @param {AbortSignal} [signal]
|
|
241
|
+
* @returns {{files:Array<{rel:string, target:object, size?:number}>, truncatedDir:boolean, dirError?:string}}
|
|
242
|
+
*/
|
|
243
|
+
export async function collectFiles(fs, rootTarget, opts = {}, signal) {
|
|
244
|
+
const { maxFiles = 1000, includeNodeModules = false } = opts;
|
|
245
|
+
const files = [];
|
|
246
|
+
const queue = [{ target: rootTarget, rel: "." }];
|
|
247
|
+
let truncatedDir = false;
|
|
248
|
+
while (queue.length > 0) {
|
|
249
|
+
const { target, rel } = queue.shift();
|
|
250
|
+
let entries;
|
|
251
|
+
try {
|
|
252
|
+
entries = await fs.listDir(target, signal);
|
|
253
|
+
} catch (e) {
|
|
254
|
+
return { files, truncatedDir, dirError: String(e && e.message || e) };
|
|
255
|
+
}
|
|
256
|
+
for (const entry of entries) {
|
|
257
|
+
const childRel = rel === "." ? entry.name : rel + "/" + entry.name;
|
|
258
|
+
if (entry.type === "directory") {
|
|
259
|
+
if (SKIP_DIRS.has(entry.name)) continue;
|
|
260
|
+
if (entry.name === "node_modules" && !includeNodeModules) continue;
|
|
261
|
+
queue.push({ target: entry.target, rel: childRel });
|
|
262
|
+
} else if (entry.type === "file") {
|
|
263
|
+
if (entry.name === ".DS_Store") continue;
|
|
264
|
+
if (files.length >= maxFiles) {
|
|
265
|
+
truncatedDir = true;
|
|
266
|
+
return { files, truncatedDir };
|
|
267
|
+
}
|
|
268
|
+
files.push({ rel: childRel, target: entry.target, size: entry.size });
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
return { files, truncatedDir };
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* Read one file as text through the fs adapter with a byte cap and binary
|
|
277
|
+
* fallback. Returns null when the file is oversized or unreadable.
|
|
278
|
+
* @param {object} fs - fs adapter.
|
|
279
|
+
* @param {object} target - file target.
|
|
280
|
+
* @param {number} maxFileBytes - inclusive cap.
|
|
281
|
+
* @param {AbortSignal} [signal]
|
|
282
|
+
* @returns {Promise<string|null>}
|
|
283
|
+
*/
|
|
284
|
+
export async function readFileCapped(fs, target, maxFileBytes, signal) {
|
|
285
|
+
try {
|
|
286
|
+
const text = await fs.readText(target, signal);
|
|
287
|
+
return text.length <= maxFileBytes ? text : null;
|
|
288
|
+
} catch {
|
|
289
|
+
// binary or backend rejection: try raw bytes with a cap, reject NUL-heavy content
|
|
290
|
+
try {
|
|
291
|
+
const bytes = await fs.readBytes(target, signal, maxFileBytes);
|
|
292
|
+
let nul = 0;
|
|
293
|
+
for (let i = 0; i < bytes.length && i < 8192; i++) {
|
|
294
|
+
if (bytes[i] === 0) nul += 1;
|
|
295
|
+
}
|
|
296
|
+
if (nul > 16) return null; // binary
|
|
297
|
+
return Buffer.from(bytes).toString("utf8").slice(0, maxFileBytes);
|
|
298
|
+
} catch {
|
|
299
|
+
return null;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* Scan a directory end-to-end.
|
|
306
|
+
* @param {object} fs - fs adapter (ctx.fs subset).
|
|
307
|
+
* @param {string|object} root - path string (resolved with fs.resolve) or an already-resolved target.
|
|
308
|
+
* @param {{maxFiles?:number, maxFileBytes?:number, includeNodeModules?:boolean, allowlistHosts?:string[]}} [opts]
|
|
309
|
+
* @param {AbortSignal} [signal]
|
|
310
|
+
* @returns {Promise<object>} full gate result.
|
|
311
|
+
*/
|
|
312
|
+
export async function scanDirectory(fs, root, opts = {}, signal) {
|
|
313
|
+
const { maxFiles = 1000, maxFileBytes = 2 * 1024 * 1024, includeNodeModules = false, allowlistHosts = [] } = opts;
|
|
314
|
+
const rootTarget = typeof root === "string" ? await fs.resolve(root, { signal }) : root;
|
|
315
|
+
const rootPath = fs.processPath(rootTarget);
|
|
316
|
+
|
|
317
|
+
const { files, truncatedDir, dirError } = await collectFiles(fs, rootTarget, { maxFiles, includeNodeModules }, signal);
|
|
318
|
+
|
|
319
|
+
const hits = [];
|
|
320
|
+
const notes = [];
|
|
321
|
+
const hosts = new Set();
|
|
322
|
+
const readAndSendFiles = [];
|
|
323
|
+
let filesScanned = 0;
|
|
324
|
+
let pkgInfo = null;
|
|
325
|
+
|
|
326
|
+
for (const f of files) {
|
|
327
|
+
if (isBinaryName(f.rel)) {
|
|
328
|
+
hits.push({
|
|
329
|
+
rule: "binary_blob",
|
|
330
|
+
category: CATEGORY.BINARY,
|
|
331
|
+
severity: "medium",
|
|
332
|
+
file: f.rel,
|
|
333
|
+
line: 1,
|
|
334
|
+
count: 1,
|
|
335
|
+
evidence: "binary file in package (" + path.extname(f.rel) + ")",
|
|
336
|
+
hint: "Binary artifacts can hide compiled payloads; rebuild from source instead of shipping them.",
|
|
337
|
+
});
|
|
338
|
+
continue;
|
|
339
|
+
}
|
|
340
|
+
if (f.size !== undefined && f.size > maxFileBytes) {
|
|
341
|
+
notes.push({ file: f.rel, kind: "oversized", detail: f.size + " bytes > " + maxFileBytes });
|
|
342
|
+
continue;
|
|
343
|
+
}
|
|
344
|
+
const content = await readFileCapped(fs, f.target, maxFileBytes, signal);
|
|
345
|
+
if (content === null) {
|
|
346
|
+
notes.push({ file: f.rel, kind: "unreadable", detail: "binary or oversized or unreadable" });
|
|
347
|
+
continue;
|
|
348
|
+
}
|
|
349
|
+
filesScanned += 1;
|
|
350
|
+
const res = scanFileText({ rel: f.rel, content });
|
|
351
|
+
hits.push(...res.hits);
|
|
352
|
+
notes.push(...res.notes);
|
|
353
|
+
if (res.pkg) pkgInfo = res.pkg;
|
|
354
|
+
for (const h of extractHosts(content)) hosts.add(h);
|
|
355
|
+
if (hasReadAndSend(content)) readAndSendFiles.push(f.rel);
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
if (truncatedDir) notes.push({ file: ".", kind: "truncated", detail: "file count exceeded maxFiles=" + maxFiles });
|
|
359
|
+
if (dirError) notes.push({ file: ".", kind: "dir-error", detail: dirError });
|
|
360
|
+
|
|
361
|
+
if (opts.osvCheck && pkgInfo) {
|
|
362
|
+
const deps = exactVersionDeps(pkgInfo.depMap || {}, { max: opts.osvMaxDeps || 8 });
|
|
363
|
+
const osv = await checkOsvDeps(opts.fetchImpl || fetch, deps, { timeoutMs: opts.osvTimeoutMs || 10000 });
|
|
364
|
+
hits.push(...osv.hits);
|
|
365
|
+
notes.push(...osv.notes);
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
return buildResult({
|
|
369
|
+
mode: "dir",
|
|
370
|
+
target: rootPath,
|
|
371
|
+
hits,
|
|
372
|
+
notes,
|
|
373
|
+
hosts: [...hosts],
|
|
374
|
+
readAndSendFiles,
|
|
375
|
+
filesScanned,
|
|
376
|
+
filesTotal: files.length,
|
|
377
|
+
truncatedDir,
|
|
378
|
+
allowlistHosts,
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/**
|
|
383
|
+
* Scan an extracted tarball's file list (from lib/targz.js).
|
|
384
|
+
* @param {Array<{path:string, data:Buffer}>} files
|
|
385
|
+
* @param {{maxFileBytes?:number, allowlistHosts?:string[]}} [opts]
|
|
386
|
+
* @returns {object} full gate result.
|
|
387
|
+
*/
|
|
388
|
+
export function scanTarballFiles(files, opts = {}) {
|
|
389
|
+
const { maxFileBytes = 2 * 1024 * 1024, allowlistHosts = [] } = opts;
|
|
390
|
+
const hits = [];
|
|
391
|
+
const notes = [];
|
|
392
|
+
const hosts = new Set();
|
|
393
|
+
const readAndSendFiles = [];
|
|
394
|
+
let filesScanned = 0;
|
|
395
|
+
for (const f of files) {
|
|
396
|
+
if (isBinaryName(f.path)) {
|
|
397
|
+
hits.push({
|
|
398
|
+
rule: "binary_blob",
|
|
399
|
+
category: CATEGORY.BINARY,
|
|
400
|
+
severity: "medium",
|
|
401
|
+
file: f.path,
|
|
402
|
+
line: 1,
|
|
403
|
+
count: 1,
|
|
404
|
+
evidence: "binary file in package (" + path.extname(f.path) + ")",
|
|
405
|
+
hint: "Binary artifacts can hide compiled payloads; rebuild from source instead of shipping them.",
|
|
406
|
+
});
|
|
407
|
+
continue;
|
|
408
|
+
}
|
|
409
|
+
if (f.data.length > maxFileBytes) {
|
|
410
|
+
notes.push({ file: f.path, kind: "oversized", detail: f.data.length + " bytes > " + maxFileBytes });
|
|
411
|
+
continue;
|
|
412
|
+
}
|
|
413
|
+
const content = f.data.toString("utf8");
|
|
414
|
+
if (content.includes("\u0000")) {
|
|
415
|
+
notes.push({ file: f.path, kind: "binary", detail: "NUL bytes in text path" });
|
|
416
|
+
continue;
|
|
417
|
+
}
|
|
418
|
+
filesScanned += 1;
|
|
419
|
+
const res = scanFileText({ rel: f.path, content });
|
|
420
|
+
hits.push(...res.hits);
|
|
421
|
+
notes.push(...res.notes);
|
|
422
|
+
for (const h of extractHosts(content)) hosts.add(h);
|
|
423
|
+
if (hasReadAndSend(content)) readAndSendFiles.push(f.path);
|
|
424
|
+
}
|
|
425
|
+
return buildResult({
|
|
426
|
+
mode: "npm",
|
|
427
|
+
target: "tarball",
|
|
428
|
+
hits,
|
|
429
|
+
notes,
|
|
430
|
+
hosts: [...hosts],
|
|
431
|
+
readAndSendFiles,
|
|
432
|
+
filesScanned,
|
|
433
|
+
filesTotal: files.length,
|
|
434
|
+
truncatedDir: false,
|
|
435
|
+
allowlistHosts,
|
|
436
|
+
});
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/**
|
|
440
|
+
* Resolve an npm spec ("name" or "name@version") against the registry and
|
|
441
|
+
* scan the published tarball.
|
|
442
|
+
* @param {string} spec - npm package spec.
|
|
443
|
+
* @param {{fetchImpl?:Function, maxTarballBytes?:number, maxFileBytes?:number, allowlistHosts?:string[], timeoutMs?:number}} [opts]
|
|
444
|
+
* @returns {Promise<{result:object, package:object|null}>}
|
|
445
|
+
*/
|
|
446
|
+
export async function scanNpmPackage(spec, opts = {}) {
|
|
447
|
+
const { fetchImpl = fetch, maxTarballBytes = 32 * 1024 * 1024, maxFileBytes = 2 * 1024 * 1024, allowlistHosts = [], timeoutMs = 20000 } = opts;
|
|
448
|
+
const at = spec.indexOf("@", 1);
|
|
449
|
+
const name = at === -1 ? spec : spec.slice(0, at);
|
|
450
|
+
const requested = at === -1 ? null : spec.slice(at + 1);
|
|
451
|
+
const signal = AbortSignal.timeout(timeoutMs);
|
|
452
|
+
|
|
453
|
+
const metaUrl = "https://registry.npmjs.org/" + encodeURIComponent(name);
|
|
454
|
+
let meta;
|
|
455
|
+
try {
|
|
456
|
+
const res = await fetchImpl(metaUrl, { signal });
|
|
457
|
+
if (!res.ok) throw new Error("registry " + res.status + " for " + name);
|
|
458
|
+
meta = await res.json();
|
|
459
|
+
} catch (e) {
|
|
460
|
+
throw new Error("npm: cannot fetch " + name + ": " + (e && e.message || e));
|
|
461
|
+
}
|
|
462
|
+
if (meta.error) throw new Error("npm: " + name + ": " + meta.error);
|
|
463
|
+
|
|
464
|
+
const distTags = meta["dist-tags"] || {};
|
|
465
|
+
let versionMeta = null;
|
|
466
|
+
if (requested) {
|
|
467
|
+
versionMeta = meta.versions && meta.versions[requested] || null;
|
|
468
|
+
if (!versionMeta) throw new Error("npm: version " + requested + " not found for " + name);
|
|
469
|
+
} else {
|
|
470
|
+
const latest = distTags.latest;
|
|
471
|
+
versionMeta = (latest && meta.versions && meta.versions[latest]) || null;
|
|
472
|
+
if (!versionMeta) {
|
|
473
|
+
const keys = Object.keys(meta.versions || {});
|
|
474
|
+
versionMeta = keys.length > 0 ? meta.versions[keys[keys.length - 1]] : null;
|
|
475
|
+
}
|
|
476
|
+
if (!versionMeta) throw new Error("npm: no versions for " + name);
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
const tarballUrl = versionMeta.dist && versionMeta.dist.tarball;
|
|
480
|
+
if (!tarballUrl) throw new Error("npm: no tarball for " + name + "@" + versionMeta.version);
|
|
481
|
+
|
|
482
|
+
let buf;
|
|
483
|
+
try {
|
|
484
|
+
const res = await fetchImpl(tarballUrl, { signal });
|
|
485
|
+
if (!res.ok) throw new Error("tarball " + res.status);
|
|
486
|
+
const ab = await res.arrayBuffer();
|
|
487
|
+
if (ab.byteLength > maxTarballBytes) throw new Error("tarball too large (" + ab.byteLength + " bytes)");
|
|
488
|
+
buf = Buffer.from(ab);
|
|
489
|
+
} catch (e) {
|
|
490
|
+
throw new Error("npm: cannot download tarball: " + (e && e.message || e));
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
const { extractTarball } = await import("./targz.js");
|
|
494
|
+
const { files, truncated } = extractTarball(buf, { maxBytes: maxTarballBytes * 2, maxFiles: 2000 });
|
|
495
|
+
|
|
496
|
+
const result = scanTarballFiles(files, { maxFileBytes, allowlistHosts });
|
|
497
|
+
result.target = name + "@" + versionMeta.version;
|
|
498
|
+
if (truncated.files || truncated.traversal || truncated.pax) {
|
|
499
|
+
result.notes.push({ file: "tarball", kind: "truncated", detail: JSON.stringify(truncated) });
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
// lifecycle scripts from the registry metadata itself (belt and braces)
|
|
503
|
+
const scripts = versionMeta.scripts || {};
|
|
504
|
+
const lifecycle = Object.keys(scripts)
|
|
505
|
+
.filter((k) => /^(pre|post)?(install|uninstall|prepare|prepublish|publish|link)\b/.test(k))
|
|
506
|
+
.map((k) => ({ script: k, body: String(scripts[k]).slice(0, 500) }));
|
|
507
|
+
const packageInfo = {
|
|
508
|
+
name: versionMeta.name || name,
|
|
509
|
+
version: versionMeta.version,
|
|
510
|
+
lifecycle,
|
|
511
|
+
dependencyCount: Object.keys(versionMeta.dependencies || {}).length + Object.keys(versionMeta.devDependencies || {}).length,
|
|
512
|
+
hasDshBundle: Boolean(versionMeta.dsh && versionMeta.dsh.bundle),
|
|
513
|
+
};
|
|
514
|
+
for (const l of lifecycle) {
|
|
515
|
+
const sev = /(curl|wget|download|powershell|cmd|exec|eval|http)/i.test(l.body) ? "high" : "medium";
|
|
516
|
+
result.hits.push({
|
|
517
|
+
rule: "lifecycle_script",
|
|
518
|
+
category: CATEGORY.SCRIPTS,
|
|
519
|
+
severity: sev,
|
|
520
|
+
file: "package.json",
|
|
521
|
+
line: 1,
|
|
522
|
+
count: 1,
|
|
523
|
+
evidence: l.script + ": " + l.body.slice(0, 180),
|
|
524
|
+
hint: "npm runs lifecycle scripts during install; execute only what you have audited.",
|
|
525
|
+
});
|
|
526
|
+
}
|
|
527
|
+
result.package = packageInfo;
|
|
528
|
+
|
|
529
|
+
if (opts.osvCheck !== false) {
|
|
530
|
+
const depMap = {};
|
|
531
|
+
for (const field of ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]) {
|
|
532
|
+
const deps = versionMeta[field];
|
|
533
|
+
if (deps && typeof deps === "object") {
|
|
534
|
+
for (const [n, s] of Object.entries(deps)) if (depMap[n] === undefined) depMap[n] = s;
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
const deps = exactVersionDeps(depMap, { max: opts.osvMaxDeps || 8 });
|
|
538
|
+
const osv = await checkOsvDeps(opts.fetchImpl || fetch, deps, { timeoutMs: opts.osvTimeoutMs || 10000 });
|
|
539
|
+
result.hits.push(...osv.hits);
|
|
540
|
+
result.notes.push(...osv.notes);
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
return buildResult({ ...result, hosts: result.network ? result.network.hosts : [] }, { allowlistHosts });
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
/**
|
|
547
|
+
* Finalize counts, verdict, network summary and recommendations.
|
|
548
|
+
* Exported by dsh-plugin-explorer so the explorer can add registry-metadata
|
|
549
|
+
* hits (lifecycle scripts) on top of a tarball scan before the verdict is
|
|
550
|
+
* computed. Upstream keeps this helper private.
|
|
551
|
+
*/
|
|
552
|
+
export function buildResult(base, overrides = {}) {
|
|
553
|
+
const allowlistHosts = (overrides.allowlistHosts || base.allowlistHosts || []).map((h) => String(h).toLowerCase());
|
|
554
|
+
const hits = dedupeHits(base.hits || []);
|
|
555
|
+
const summary = { high: 0, medium: 0, low: 0, categories: {} };
|
|
556
|
+
for (const h of hits) {
|
|
557
|
+
summary[h.severity] += 1;
|
|
558
|
+
summary.categories[h.category] = (summary.categories[h.category] || 0) + 1;
|
|
559
|
+
}
|
|
560
|
+
const score = (summary.high || 0) * SEVERITY_WEIGHT.high + (summary.medium || 0) * SEVERITY_WEIGHT.medium + (summary.low || 0) * SEVERITY_WEIGHT.low;
|
|
561
|
+
const verdict = summary.high > 0 ? "BLOCK" : summary.medium > 0 ? "WARN" : "PASS";
|
|
562
|
+
|
|
563
|
+
const hosts = [...new Set((base.hosts || []).map((h) => h.toLowerCase()))];
|
|
564
|
+
const unallowlisted = hosts.filter((h) => !LOCAL_HOSTS.has(h) && !allowlistHosts.includes(h));
|
|
565
|
+
|
|
566
|
+
const recommendations = [];
|
|
567
|
+
if (verdict === "BLOCK") recommendations.push("BLOCK: high-severity patterns found. Do NOT install this package until every high hit is explained and resolved.");
|
|
568
|
+
if (summary.medium > 0) recommendations.push("WARN: medium-severity patterns found. Review every hit in context before deciding to install.");
|
|
569
|
+
if (summary.categories[CATEGORY.SCRIPTS] > 0) recommendations.push("Inspect npm lifecycle scripts (pre/install/postinstall) — they execute during install without your explicit action.");
|
|
570
|
+
if (summary.categories[CATEGORY.NETWORK] > 0) recommendations.push("Network I/O detected: verify every destination, and confirm no data leaves the workspace without purpose.");
|
|
571
|
+
if (summary.categories[CATEGORY.PERMISSIONS] > 0) recommendations.push("File/permission access detected: confirm reads/writes stay inside the session workspace and no credentials are touched.");
|
|
572
|
+
if (summary.categories[CATEGORY.SECRETS] > 0) recommendations.push("Hardcoded credential material found — treat the package as compromised if any hit is a live secret.");
|
|
573
|
+
if (summary.categories[CATEGORY.OBFUSCATION] > 0) recommendations.push("Obfuscated code paths found — decode and review before trusting runtime behavior.");
|
|
574
|
+
if (summary.categories[CATEGORY.BINARY] > 0) recommendations.push("Binary artifacts shipped in the package — prefer building from source.");
|
|
575
|
+
if (recommendations.length === 0) recommendations.push("No risky patterns detected by signature scan. This is a heuristic result, not a guarantee — review critical plugins manually too.");
|
|
576
|
+
if (verdict === "BLOCK") recommendations.push("Gate policy: refuse installation on BLOCK verdicts unless the maintainer provides a clean rebuild you can scan again.");
|
|
577
|
+
|
|
578
|
+
return {
|
|
579
|
+
verdict,
|
|
580
|
+
score,
|
|
581
|
+
mode: base.mode,
|
|
582
|
+
target: base.target,
|
|
583
|
+
filesScanned: base.filesScanned,
|
|
584
|
+
filesTotal: base.filesTotal,
|
|
585
|
+
summary,
|
|
586
|
+
network: {
|
|
587
|
+
hosts,
|
|
588
|
+
unallowlisted,
|
|
589
|
+
readAndSendFiles: base.readAndSendFiles || [],
|
|
590
|
+
},
|
|
591
|
+
package: base.package || null,
|
|
592
|
+
notes: base.notes || [],
|
|
593
|
+
hits,
|
|
594
|
+
recommendations,
|
|
595
|
+
};
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/** Deduplicate identical (rule, file, line, evidence) hits. */
|
|
599
|
+
function dedupeHits(hits) {
|
|
600
|
+
const seen = new Set();
|
|
601
|
+
const out = [];
|
|
602
|
+
for (const h of hits) {
|
|
603
|
+
const key = h.rule + "|" + h.file + "|" + h.line + "|" + h.evidence;
|
|
604
|
+
if (seen.has(key)) continue;
|
|
605
|
+
seen.add(key);
|
|
606
|
+
out.push(h);
|
|
607
|
+
}
|
|
608
|
+
return out;
|
|
609
|
+
}
|