dsh-vigil 0.0.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.
Files changed (56) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +188 -0
  3. package/client.js +4652 -0
  4. package/cordis.patch.yml +7 -0
  5. package/docs/DETAIL.md +66 -0
  6. package/icon.png +0 -0
  7. package/illustrations/notice.png +0 -0
  8. package/illustrations/warning.png +0 -0
  9. package/locale/en.json +7 -0
  10. package/locale/zh.json +7 -0
  11. package/package.json +75 -0
  12. package/rules/audit.yaml +130 -0
  13. package/rules/manifest.json +7 -0
  14. package/rules/sentinel.yaml +289 -0
  15. package/src/alert-route.js +194 -0
  16. package/src/approval.js +398 -0
  17. package/src/artwork-route.js +87 -0
  18. package/src/audit/ast.js +213 -0
  19. package/src/audit/install-scan.js +127 -0
  20. package/src/audit/lexer.js +307 -0
  21. package/src/audit/narrative.js +320 -0
  22. package/src/audit/rules.js +1440 -0
  23. package/src/audit/scan.js +880 -0
  24. package/src/audit-clear-route.js +89 -0
  25. package/src/audit-feed.js +265 -0
  26. package/src/audit-log.js +887 -0
  27. package/src/config-schema.js +194 -0
  28. package/src/config.js +580 -0
  29. package/src/delete/command-kinds.js +46 -0
  30. package/src/delete/lex.js +46 -0
  31. package/src/delete/parser-posix.js +1427 -0
  32. package/src/delete/parser-pwsh.js +1729 -0
  33. package/src/delete/parser.js +2082 -0
  34. package/src/delete/policy.js +680 -0
  35. package/src/delete/quarantine.js +417 -0
  36. package/src/index.js +1134 -0
  37. package/src/install-scan-route.js +58 -0
  38. package/src/install-watch.js +389 -0
  39. package/src/integrity.js +509 -0
  40. package/src/live-config.js +88 -0
  41. package/src/quarantine-route.js +74 -0
  42. package/src/quarantine-view.js +44 -0
  43. package/src/rules/pack.js +423 -0
  44. package/src/rules/update.js +341 -0
  45. package/src/rules/yaml.js +186 -0
  46. package/src/sage-action-route.js +63 -0
  47. package/src/sage-provision.js +716 -0
  48. package/src/sentinel/guard.js +392 -0
  49. package/src/sentinel/hook.js +546 -0
  50. package/src/sentinel/rules.js +488 -0
  51. package/src/sentinel/sage-load.js +79 -0
  52. package/src/sentinel/sage.js +550 -0
  53. package/src/tools.js +727 -0
  54. package/src/update-check.js +339 -0
  55. package/src/util.js +400 -0
  56. package/threats/README.md +25 -0
@@ -0,0 +1,880 @@
1
+ /**
2
+ * @module dsh-vigil/audit/scan
3
+ *
4
+ * Install-time static auditor for dsh plugin package directories (FR-1).
5
+ *
6
+ * The scanner walks a plugin package, reads only known text files under strict
7
+ * limits, and runs the built-in rule catalog over them. It NEVER imports,
8
+ * evaluates, or otherwise executes the scanned code, and it never follows
9
+ * symlinks (so a package cannot smuggle in content from outside its tree).
10
+ *
11
+ * Public API:
12
+ * - scanPluginDirectory(dir, options?) -> Promise<Report>
13
+ * - formatReportCard(report, options?) -> string
14
+ * - SCAN_LIMITS
15
+ */
16
+
17
+ import fs from 'node:fs';
18
+ import path from 'node:path';
19
+ import { performance } from 'node:perf_hooks';
20
+
21
+ import {
22
+ materializeFinding,
23
+ scanCodeFile,
24
+ scanPackageManifest,
25
+ scanPatchFile,
26
+ } from './rules.js';
27
+ import {
28
+ CATEGORIES,
29
+ CATEGORY_LABELS,
30
+ DISCLAIMER,
31
+ SEVERITY_RANK,
32
+ redactEvidence,
33
+ } from './narrative.js';
34
+
35
+ const fsp = fs.promises;
36
+
37
+ /**
38
+ * @typedef {'blocker'|'review'|'notice'|'info'} Severity
39
+ * @typedef {'credential'|'network'|'dynamic-code'|'config-tamper'|'supply-chain'|'dsh-attack'|'unknown'} Category
40
+ *
41
+ * @typedef {Object} Finding
42
+ * @property {string} id Stable per-instance id, e.g. 'VG-INJ-01#3'.
43
+ * @property {string} ruleId Catalog id, e.g. 'VG-INJ-01'.
44
+ * @property {Category} category
45
+ * @property {Severity} severity
46
+ * @property {string} title Short Chinese title.
47
+ * @property {string} file POSIX path relative to the target dir.
48
+ * @property {number|null} line 1-based line number, null for file-level.
49
+ * @property {string} evidence Trimmed source line or JSON snippet (<= 240 chars).
50
+ * @property {string} means Chinese sentence starting with '这意味着:'.
51
+ * @property {string} mitigation One concrete mitigation action, Chinese.
52
+ * @property {'confirmed'|'heuristic'} confidence
53
+ * @property {string} [ruleAttribution]
54
+ *
55
+ * @typedef {Object} Report
56
+ * @property {{ dir: string, name: string, version: string|null, isDshPlugin: boolean }} target
57
+ * @property {string} scannedAt ISO timestamp.
58
+ * @property {number} durationMs
59
+ * @property {number} filesScanned
60
+ * @property {Finding[]} findings Sorted and deduped.
61
+ * @property {{ blocker: number, review: number, notice: number, info: number, total: number, byCategory: Record<string, number> }} summary
62
+ * @property {{ filesSkipped: number, bytesSkipped: number, truncated: boolean, deadline?: boolean }} limits
63
+ * @property {string} disclaimer
64
+ */
65
+
66
+ /**
67
+ * Hard limits that bound the work of one scan.
68
+ * `maxFiles` / `maxFileBytes` can be lowered through options but never raised.
69
+ */
70
+ export const SCAN_LIMITS = Object.freeze({
71
+ maxFiles: 400,
72
+ maxFileBytes: 512 * 1024,
73
+ maxDepth: 12,
74
+ });
75
+
76
+ /** File extensions that are considered text and are eligible for scanning. */
77
+ const TEXT_EXTENSIONS = new Set([
78
+ '.js', '.mjs', '.cjs', '.ts', '.mts', '.cts', '.jsx', '.tsx',
79
+ '.json', '.yml', '.yaml', '.md',
80
+ ]);
81
+
82
+ /** Extensions analyzed as JavaScript/TypeScript. */
83
+ const CODE_EXTENSIONS = new Set(['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts', '.jsx', '.tsx']);
84
+
85
+ /** Directories that are always skipped (never traversed). */
86
+ const IGNORED_DIRECTORIES = new Set(['node_modules', '.git', '.svn', 'dist', 'build', 'coverage']);
87
+
88
+ /**
89
+ * Clamp scanner options into documented limits.
90
+ *
91
+ * @param {Record<string, unknown>} options
92
+ * @returns {{ maxFiles: number, maxFileBytes: number, maxDepth: number, includeInfo: boolean }}
93
+ */
94
+ function normalizeOptions(options) {
95
+ const source = options && typeof options === 'object' ? options : {};
96
+ const asPositiveInteger = (value, fallback, cap) => {
97
+ if (!Number.isFinite(value) || value <= 0) return fallback;
98
+ return Math.min(Math.floor(value), cap);
99
+ };
100
+ return {
101
+ maxFiles: asPositiveInteger(source.maxFiles, SCAN_LIMITS.maxFiles, SCAN_LIMITS.maxFiles),
102
+ maxFileBytes: asPositiveInteger(source.maxFileBytes, SCAN_LIMITS.maxFileBytes, SCAN_LIMITS.maxFileBytes),
103
+ maxDepth: SCAN_LIMITS.maxDepth,
104
+ includeInfo: source.includeInfo !== false,
105
+ /** Absolute timestamp; 0 disables the time budget. */
106
+ deadlineAt: Number(source.deadlineAt) > 0 ? Number(source.deadlineAt) : 0,
107
+ /** Optional progress hook: (relativePath) => void. */
108
+ onProgress: typeof source.onProgress === 'function' ? source.onProgress : null,
109
+ /** AST alias analysis tuning: enabled + level (low/medium/high). */
110
+ ast: {
111
+ enabled: !(source.ast && source.ast.enabled === false),
112
+ level: ['low', 'medium', 'high'].includes(source.ast?.level) ? source.ast.level : 'medium',
113
+ },
114
+ };
115
+ }
116
+
117
+ /** Yield to the event loop so a large scan cannot stall tool dispatch. */
118
+ const yieldToEventLoop = () => new Promise(resolve => setImmediate(resolve));
119
+
120
+ /** Deterministic string comparison (locale-independent). */
121
+ function compareStrings(a, b) {
122
+ if (a === b) return 0;
123
+ return a < b ? -1 : 1;
124
+ }
125
+
126
+ /** Deterministic finding order: severity desc, file, line, rule id. */
127
+ function compareFindings(a, b) {
128
+ const rankDiff = (SEVERITY_RANK[b.severity] ?? 0) - (SEVERITY_RANK[a.severity] ?? 0);
129
+ if (rankDiff !== 0) return rankDiff;
130
+ const fileDiff = compareStrings(a.file ?? '', b.file ?? '');
131
+ if (fileDiff !== 0) return fileDiff;
132
+ const aLine = Number.isInteger(a.line) ? a.line : Number.MAX_SAFE_INTEGER;
133
+ const bLine = Number.isInteger(b.line) ? b.line : Number.MAX_SAFE_INTEGER;
134
+ if (aLine !== bLine) return aLine - bLine;
135
+ return compareStrings(a.ruleId ?? '', b.ruleId ?? '');
136
+ }
137
+
138
+ /** Normalize a relative path into POSIX form. */
139
+ function toPosix(value) {
140
+ return String(value ?? '').replace(/\\/g, '/');
141
+ }
142
+
143
+ /** Recursively collect export target strings from an exports-like value. */
144
+ function collectExportStrings(value, out = []) {
145
+ if (typeof value === 'string') out.push(value);
146
+ else if (Array.isArray(value)) value.forEach((entry) => collectExportStrings(entry, out));
147
+ else if (value && typeof value === 'object') Object.values(value).forEach((entry) => collectExportStrings(entry, out));
148
+ return out;
149
+ }
150
+
151
+ /**
152
+ * Collect package-declared client entry paths (exports["./client"],
153
+ * dsh.client.entry, etc.), normalized to POSIX relative paths.
154
+ */
155
+ function clientEntryPaths(pkg) {
156
+ if (!pkg || typeof pkg !== 'object') return [];
157
+ const candidates = [];
158
+ const exportsField = pkg.exports;
159
+ if (exportsField && typeof exportsField === 'object' && !Array.isArray(exportsField)) {
160
+ collectExportStrings(exportsField['./client'], candidates);
161
+ }
162
+ const dshClient = pkg.dsh && typeof pkg.dsh === 'object' ? pkg.dsh.client : undefined;
163
+ if (dshClient && typeof dshClient === 'object') {
164
+ for (const key of ['entry', 'entryPoint', 'browser', 'file', 'main']) {
165
+ if (typeof dshClient[key] === 'string') candidates.push(dshClient[key]);
166
+ }
167
+ }
168
+ return candidates
169
+ .map((value) => toPosix(value).replace(/^\.\//, '').replace(/^\/+/, ''))
170
+ .filter(Boolean);
171
+ }
172
+
173
+ /**
174
+ * Heuristically decide whether a source file belongs to the browser/client
175
+ * half of a dsh plugin.
176
+ */
177
+ function isClientFile(relativePath, pkg) {
178
+ const rel = toPosix(relativePath);
179
+ if (/(?:^|\/)client\.(?:[cm]?[jt]s|[jt]sx)$/.test(rel)) return true;
180
+ if (/(?:^|\/)client\//.test(rel)) return true;
181
+ return clientEntryPaths(pkg).includes(rel);
182
+ }
183
+
184
+ /**
185
+ * Recursively discover scannable text files under `rootDir`.
186
+ *
187
+ * Rules: never follows symlinks, never enters ignored directories, bounded by
188
+ * file count / byte size / depth, and deterministic (sorted) traversal.
189
+ *
190
+ * @param {string} rootDir Absolute directory.
191
+ * @param {{ maxFiles: number, maxFileBytes: number, maxDepth: number }} options
192
+ * @returns {Promise<{
193
+ * files: { rel: string, abs: string, size: number }[],
194
+ * unreadableDirs: { rel: string, reason: string }[],
195
+ * filesSkipped: number,
196
+ * bytesSkipped: number,
197
+ * truncated: boolean
198
+ * }>}
199
+ */
200
+ async function discoverFiles(rootDir, options) {
201
+ const state = {
202
+ files: [],
203
+ unreadableDirs: [],
204
+ filesSkipped: 0,
205
+ bytesSkipped: 0,
206
+ truncated: false,
207
+ deadline: false,
208
+ visited: 0,
209
+ /** Files skipped because their extension is not scannable text. */
210
+ nonTextFiles: 0,
211
+ /** Directories skipped by policy (dist/build/…), reported honestly. */
212
+ ignoredDirectories: new Set(),
213
+ };
214
+
215
+ const expired = () => options.deadlineAt > 0 && Date.now() > options.deadlineAt;
216
+
217
+ const walk = async (absoluteDir, relativeDir, depth) => {
218
+ if (state.truncated) return;
219
+ if (expired()) {
220
+ state.truncated = true;
221
+ state.deadline = true;
222
+ return;
223
+ }
224
+ let entries;
225
+ try {
226
+ entries = await fsp.readdir(absoluteDir, { withFileTypes: true });
227
+ } catch (error) {
228
+ state.unreadableDirs.push({
229
+ rel: relativeDir || '.',
230
+ reason: truncateReason(error),
231
+ });
232
+ state.filesSkipped += 1;
233
+ return;
234
+ }
235
+ entries.sort((a, b) => compareStrings(a.name, b.name));
236
+
237
+ for (const entry of entries) {
238
+ if (state.truncated) return;
239
+ if (expired()) {
240
+ state.truncated = true;
241
+ state.deadline = true;
242
+ return;
243
+ }
244
+ state.visited += 1;
245
+ if (state.visited % 25 === 0) await yieldToEventLoop();
246
+ const rel = relativeDir ? `${relativeDir}/${entry.name}` : entry.name;
247
+
248
+ // Symlinks (including Windows junctions) are never followed.
249
+ if (entry.isSymbolicLink()) {
250
+ state.filesSkipped += 1;
251
+ continue;
252
+ }
253
+ if (entry.isDirectory()) {
254
+ if (IGNORED_DIRECTORIES.has(entry.name)) {
255
+ state.ignoredDirectories.add(entry.name);
256
+ continue;
257
+ }
258
+ if (depth + 1 > options.maxDepth) {
259
+ state.filesSkipped += 1;
260
+ continue;
261
+ }
262
+ await walk(path.join(absoluteDir, entry.name), rel, depth + 1);
263
+ continue;
264
+ }
265
+ if (!entry.isFile()) {
266
+ // FIFOs, devices, junctions to nowhere: an entry we cannot read.
267
+ state.filesSkipped += 1;
268
+ continue;
269
+ }
270
+
271
+ const extension = path.extname(entry.name).toLowerCase();
272
+ if (!TEXT_EXTENSIONS.has(extension)) {
273
+ state.nonTextFiles += 1;
274
+ continue;
275
+ }
276
+
277
+ if (state.files.length >= options.maxFiles) {
278
+ state.truncated = true;
279
+ return;
280
+ }
281
+ const absoluteFile = path.join(absoluteDir, entry.name);
282
+ let stat;
283
+ try {
284
+ stat = await fsp.lstat(absoluteFile);
285
+ } catch (error) {
286
+ state.filesSkipped += 1;
287
+ continue;
288
+ }
289
+ if (stat.size > options.maxFileBytes) {
290
+ state.bytesSkipped += stat.size;
291
+ state.filesSkipped += 1;
292
+ continue;
293
+ }
294
+ state.files.push({ rel, abs: absoluteFile, size: stat.size });
295
+ }
296
+ };
297
+
298
+ await walk(rootDir, '', 0);
299
+ return state;
300
+ }
301
+
302
+ /** Build a short, non-leaking reason string for unreadable paths. */
303
+ function truncateReason(error) {
304
+ const code = error && typeof error === 'object' && typeof error.code === 'string' ? error.code : '';
305
+ if (code) return code;
306
+ const message = error && typeof error === 'object' && typeof error.message === 'string' ? error.message : String(error);
307
+ return message.length > 160 ? `${message.slice(0, 159)}…` : message;
308
+ }
309
+
310
+ /** Build the summary block for a finding list. */
311
+ function buildSummary(findings) {
312
+ /** @type {Record<string, number>} */
313
+ const byCategory = {};
314
+ for (const category of CATEGORIES) byCategory[category] = 0;
315
+ const summary = { blocker: 0, review: 0, notice: 0, info: 0, total: 0, byCategory };
316
+ for (const finding of findings) {
317
+ if (Object.prototype.hasOwnProperty.call(summary, finding.severity)) {
318
+ summary[finding.severity] += 1;
319
+ }
320
+ summary.total += 1;
321
+ byCategory[finding.category] = (byCategory[finding.category] ?? 0) + 1;
322
+ }
323
+ return summary;
324
+ }
325
+
326
+ /**
327
+ * Materialize raw matcher hits into sorted, deduped, stable-id findings.
328
+ *
329
+ * @param {import('./rules.js').RawFinding[]} rawFindings
330
+ * @param {boolean} includeInfo
331
+ * @returns {Finding[]}
332
+ */
333
+ function finalizeFindings(rawFindings, includeInfo) {
334
+ const materialized = rawFindings
335
+ .map((raw) => materializeFinding(raw))
336
+ .filter((finding) => includeInfo || finding.severity !== 'info');
337
+
338
+ const seen = new Set();
339
+ const unique = [];
340
+ for (const finding of materialized) {
341
+ const key = [finding.ruleId, finding.file, finding.line ?? '', finding.evidence].join('\u0000');
342
+ if (seen.has(key)) continue;
343
+ seen.add(key);
344
+ unique.push(finding);
345
+ }
346
+
347
+ unique.sort(compareFindings);
348
+ const counters = new Map();
349
+ return unique.map((finding) => {
350
+ const next = (counters.get(finding.ruleId) ?? 0) + 1;
351
+ counters.set(finding.ruleId, next);
352
+ return { ...finding, id: `${finding.ruleId}#${next}` };
353
+ });
354
+ }
355
+
356
+ /**
357
+ * Assemble a Report from raw findings and scan metadata.
358
+ */
359
+ function buildReport({ target, startedAt, durationMs, filesScanned, rawFindings, limits, includeInfo }) {
360
+ const findings = finalizeFindings(rawFindings, includeInfo);
361
+ return {
362
+ target,
363
+ scannedAt: startedAt,
364
+ durationMs,
365
+ filesScanned,
366
+ findings,
367
+ summary: buildSummary(findings),
368
+ limits,
369
+ disclaimer: DISCLAIMER,
370
+ };
371
+ }
372
+
373
+ /** Build the blocker report returned when the target itself cannot be read. */
374
+ function buildUnreadableReport(targetDir, reason, startedAt, startedClock) {
375
+ const absoluteDir = safeResolve(targetDir);
376
+ const target = {
377
+ dir: absoluteDir,
378
+ name: path.basename(absoluteDir) || '(未知目标)',
379
+ version: null,
380
+ isDshPlugin: false,
381
+ };
382
+ const raw = [{
383
+ ruleId: 'VG-SCAN-01',
384
+ file: '.',
385
+ line: null,
386
+ evidence: `无法读取目标目录:${reason}`,
387
+ vars: { reason },
388
+ confidence: 'confirmed',
389
+ }];
390
+ return buildReport({
391
+ target,
392
+ startedAt,
393
+ durationMs: elapsedMs(startedClock),
394
+ filesScanned: 0,
395
+ rawFindings: raw,
396
+ limits: { filesSkipped: 0, bytesSkipped: 0, truncated: false },
397
+ includeInfo: true,
398
+ });
399
+ }
400
+
401
+ /** Resolve a path defensively (path.resolve can throw on non-strings). */
402
+ function safeResolve(value) {
403
+ try {
404
+ return path.resolve(String(value ?? ''));
405
+ } catch {
406
+ return String(value ?? '');
407
+ }
408
+ }
409
+
410
+ /** Round elapsed milliseconds from a performance.now() start. */
411
+ function elapsedMs(startedClock) {
412
+ return Math.max(0, Math.round(performance.now() - startedClock));
413
+ }
414
+
415
+ /** Read a text file as UTF-8; resolves to null on any error. */
416
+ async function readTextFile(absolutePath) {
417
+ try {
418
+ const text = stripBom(await fsp.readFile(absolutePath, 'utf8'))
419
+ // A `.js` file full of replacement characters is binary (or a non-UTF-8
420
+ // encoding). Scanner rules would only produce garbage evidence from it.
421
+ if (looksBinary(text)) return { ok: false, reason: '非 UTF-8 文本(疑似二进制)' }
422
+ return { ok: true, text }
423
+ } catch (error) {
424
+ return { ok: false, reason: truncateReason(error) }
425
+ }
426
+ }
427
+
428
+ /** A small ratio of U+FFFD is normal in mixed text; a lot means "not text". */
429
+ function looksBinary(text) {
430
+ if (typeof text !== 'string' || text === '') return false
431
+ const replacement = (text.match(/\uFFFD/g) || []).length
432
+ if (replacement === 0) return false
433
+ return replacement > 8 || replacement / text.length > 0.01
434
+ }
435
+
436
+ /** A UTF-8 BOM must not break JSON.parse / the first-line rules. */
437
+ function stripBom(text) {
438
+ return typeof text === 'string' && text.charCodeAt(0) === 0xfeff ? text.slice(1) : text
439
+ }
440
+
441
+ /**
442
+ * Read a text file with an explicit size ceiling. Used for the two files that
443
+ * declare how a bundle mounts (manifest, patch) so a padded package cannot hide
444
+ * them behind the general file budget.
445
+ * @param {string} absolutePath
446
+ * @param {number} maxBytes
447
+ * @returns {Promise<{ ok: true, text: string } | { ok: false, reason: string }>}
448
+ */
449
+ async function readTextFileCapped(absolutePath, maxBytes) {
450
+ try {
451
+ // The walk never follows symlinks; these direct reads (manifest / declared
452
+ // patch) must uphold the same contract, otherwise a package can point its
453
+ // patch at an arbitrary host file and leak it into the report.
454
+ const stat = await fsp.lstat(absolutePath)
455
+ if (stat.isSymbolicLink()) return { ok: false, reason: '符号链接文件(拒绝跟随)' }
456
+ if (!stat.isFile()) return { ok: false, reason: '不是普通文件' }
457
+ if (stat.size > maxBytes) return { ok: false, reason: `文件超过 ${maxBytes} 字节` }
458
+ return { ok: true, text: stripBom(await fsp.readFile(absolutePath, 'utf8')) }
459
+ } catch (error) {
460
+ return { ok: false, reason: truncateReason(error) }
461
+ }
462
+ }
463
+
464
+ /**
465
+ * Every path-like string a manifest declares as an entry point.
466
+ * @param {any} pkg
467
+ * @returns {string[]}
468
+ */
469
+ function collectEntryPaths(pkg) {
470
+ /** @type {string[]} */
471
+ const out = []
472
+ const visit = value => {
473
+ if (typeof value === 'string') {
474
+ const cleaned = value.replace(/^\.\//, '').trim()
475
+ if (cleaned !== '') out.push(cleaned)
476
+ return
477
+ }
478
+ if (Array.isArray(value)) {
479
+ for (const item of value) visit(item)
480
+ return
481
+ }
482
+ if (value && typeof value === 'object') {
483
+ for (const item of Object.values(value)) visit(item)
484
+ }
485
+ }
486
+ if (!pkg || typeof pkg !== 'object') return out
487
+ visit(pkg.main)
488
+ visit(pkg.module)
489
+ visit(pkg.browser)
490
+ visit(pkg.bin)
491
+ visit(pkg.exports)
492
+ return out
493
+ }
494
+
495
+ /**
496
+ * Patch paths declared by `dsh.bundle.patch` (string or array).
497
+ * @param {any} pkg parsed package.json
498
+ * @returns {string[]}
499
+ */
500
+ function declaredPatchPaths(pkg) {
501
+ try {
502
+ const patch = pkg?.dsh?.bundle?.patch
503
+ if (typeof patch === 'string' && patch.trim() !== '') return [patch.trim()]
504
+ if (Array.isArray(patch)) return patch.filter(item => typeof item === 'string' && item.trim() !== '').map(item => item.trim())
505
+ } catch {
506
+ // malformed manifest: fall back to the conventional file name
507
+ }
508
+ return []
509
+ }
510
+
511
+ /**
512
+ * @param {string} spec
513
+ * @returns {string} relative POSIX path without a leading ./
514
+ */
515
+ function normalizePatchRel(spec) {
516
+ return String(spec).replace(/\\/g, '/').replace(/^\.\//, '')
517
+ }
518
+
519
+ /**
520
+ * @param {string} rootDir
521
+ * @param {string} rel
522
+ * @returns {boolean} whether `rel` stays inside `rootDir`
523
+ */
524
+ function patchInside(rootDir, rel) {
525
+ const base = path.resolve(rootDir)
526
+ const absolute = path.resolve(base, rel)
527
+ const relativePath = path.relative(base, absolute)
528
+ return relativePath !== '' && !relativePath.startsWith('..') && !path.isAbsolute(relativePath)
529
+ }
530
+
531
+ /** Rewrite a relative path to POSIX separators for reports. */
532
+ function relPosix(relativePath) {
533
+ return toPosix(relativePath);
534
+ }
535
+
536
+ /**
537
+ * Statically audit a dsh plugin package directory.
538
+ *
539
+ * The scan is bounded (file count, file size, depth), deterministic, and never
540
+ * executes any scanned code. It never throws: unreadable files become `notice`
541
+ * findings (`VG-SCAN-02`) and a completely unreadable target becomes a
542
+ * `blocker` finding (`VG-SCAN-01`).
543
+ *
544
+ * @param {string} dir Plugin package directory.
545
+ * @param {{ maxFiles?: number, maxFileBytes?: number, includeInfo?: boolean }} [options]
546
+ * @returns {Promise<Report>}
547
+ */
548
+ export async function scanPluginDirectory(dir, options = {}) {
549
+ const startedAt = new Date().toISOString();
550
+ const startedClock = performance.now();
551
+ const targetDir = typeof dir === 'string' ? dir : '';
552
+ const absoluteDir = safeResolve(targetDir);
553
+
554
+ if (!targetDir.trim()) {
555
+ return buildUnreadableReport('', '目标路径为空', startedAt, startedClock);
556
+ }
557
+
558
+ try {
559
+ let stat;
560
+ try {
561
+ stat = await fsp.stat(absoluteDir);
562
+ } catch (error) {
563
+ return buildUnreadableReport(absoluteDir, `无法访问目标路径(${truncateReason(error)})`, startedAt, startedClock);
564
+ }
565
+ if (!stat.isDirectory()) {
566
+ return buildUnreadableReport(absoluteDir, '目标路径不是目录', startedAt, startedClock);
567
+ }
568
+ try {
569
+ await fsp.readdir(absoluteDir);
570
+ } catch (error) {
571
+ return buildUnreadableReport(absoluteDir, `目录不可读取(${truncateReason(error)})`, startedAt, startedClock);
572
+ }
573
+
574
+ const scanOptions = normalizeOptions(options);
575
+ const discovery = await discoverFiles(absoluteDir, scanOptions);
576
+ const rootUnreadable = discovery.unreadableDirs.find((entry) => entry.rel === '.');
577
+ if (rootUnreadable && discovery.files.length === 0) {
578
+ return buildUnreadableReport(absoluteDir, `目录不可读取(${rootUnreadable.reason})`, startedAt, startedClock);
579
+ }
580
+ const rawFindings = [];
581
+ let filesScanned = 0;
582
+ let filesSkipped = discovery.filesSkipped;
583
+
584
+ for (const unreadableDir of discovery.unreadableDirs) {
585
+ rawFindings.push({
586
+ ruleId: 'VG-SCAN-02',
587
+ file: unreadableDir.rel === '.' ? '.' : `${relPosix(unreadableDir.rel)}/`,
588
+ line: null,
589
+ evidence: `目录不可读取(${unreadableDir.reason})`,
590
+ vars: { reason: unreadableDir.reason },
591
+ });
592
+ }
593
+
594
+ // The manifest and every declared patch are read first and directly: a
595
+ // package can pad itself with hundreds of text files, and the alphabetical
596
+ // file budget would otherwise hide exactly the two files that declare how
597
+ // the bundle is mounted and what it overrides.
598
+ const MANIFEST_MAX_BYTES = 2 * 1024 * 1024
599
+ const manifestRel = 'package.json'
600
+ /** Relative paths already read directly; the walk skips them. */
601
+ const readDirectly = new Set()
602
+ let pkg = null
603
+ let manifestText = ''
604
+ const manifestResult = await readTextFileCapped(path.join(absoluteDir, manifestRel), MANIFEST_MAX_BYTES)
605
+ if (manifestResult.ok) {
606
+ manifestText = manifestResult.text
607
+ readDirectly.add(manifestRel)
608
+ filesScanned += 1
609
+ try {
610
+ const parsed = JSON.parse(manifestText)
611
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) pkg = parsed
612
+ } catch {
613
+ pkg = null
614
+ }
615
+ } else if (!/ENOENT/.test(manifestResult.reason)) {
616
+ filesSkipped += 1
617
+ rawFindings.push({
618
+ ruleId: 'VG-SCAN-02',
619
+ file: manifestRel,
620
+ line: null,
621
+ evidence: `无法读取 package.json(${manifestResult.reason})`,
622
+ vars: { reason: manifestResult.reason },
623
+ })
624
+ }
625
+
626
+ // `dsh.bundle.patch` is what dsh actually loads; the file does not have to be
627
+ // named `cordis.patch.yml`. Escaping specs are reported by the manifest
628
+ // rules, so they are not read here.
629
+ const patchPaths = []
630
+ for (const spec of declaredPatchPaths(pkg)) {
631
+ const rel = normalizePatchRel(spec)
632
+ if (!patchInside(absoluteDir, rel)) continue
633
+ if (!patchPaths.includes(rel)) patchPaths.push(rel)
634
+ }
635
+ if (patchPaths.length === 0) patchPaths.push('cordis.patch.yml')
636
+ // Build outputs are skipped for speed, but if the package declares one as
637
+ // its entry point then "0 findings" would be a lie: say that the code that
638
+ // actually runs was never read, and let the install gate ask.
639
+ const entryPaths = collectEntryPaths(pkg)
640
+ const ignoredEntryDirs = [...new Set(entryPaths
641
+ .map(entry => entry.split(/[\\/]/)[0])
642
+ .filter(first => IGNORED_DIRECTORIES.has(first)))]
643
+ if (ignoredEntryDirs.length > 0) {
644
+ const sample = entryPaths
645
+ .filter(entry => ignoredEntryDirs.includes(entry.split(/[\\/]/)[0]))
646
+ .slice(0, 3)
647
+ .join('、')
648
+ rawFindings.push({
649
+ ruleId: 'VG-SCAN-04',
650
+ file: 'package.json',
651
+ line: null,
652
+ evidence: `入口位于未扫描目录:${ignoredEntryDirs.map(name => `${name}/`).join('、')}(${sample})`,
653
+ vars: { dirs: ignoredEntryDirs.map(name => `${name}/`).join('、') },
654
+ })
655
+ }
656
+ /** @type {string[]} */
657
+ const foundPatches = []
658
+ for (const rel of patchPaths) {
659
+ if (readDirectly.has(rel)) continue
660
+ const result = await readTextFileCapped(path.join(absoluteDir, rel), scanOptions.maxFileBytes)
661
+ if (!result.ok) {
662
+ // A declared-but-oversized/unreadable patch is a blind spot, not "no patch".
663
+ if (!/ENOENT/.test(result.reason)) {
664
+ filesSkipped += 1
665
+ rawFindings.push({
666
+ ruleId: 'VG-SCAN-02',
667
+ file: rel,
668
+ line: null,
669
+ evidence: `无法读取补丁文件(${result.reason})`,
670
+ vars: { reason: result.reason },
671
+ })
672
+ }
673
+ continue
674
+ }
675
+ readDirectly.add(rel)
676
+ filesScanned += 1
677
+ foundPatches.push(rel)
678
+ if (/\.ya?ml$/i.test(rel)) rawFindings.push(...scanPatchFile({ file: rel, text: result.text }))
679
+ }
680
+
681
+ const readFile = async (file) => {
682
+ const result = await readTextFile(file.abs);
683
+ if (!result.ok) {
684
+ filesSkipped += 1;
685
+ rawFindings.push({
686
+ ruleId: 'VG-SCAN-02',
687
+ file: relPosix(file.rel),
688
+ line: null,
689
+ evidence: `无法读取文件(${result.reason})`,
690
+ vars: { reason: result.reason },
691
+ });
692
+ return null;
693
+ }
694
+ filesScanned += 1;
695
+ return result.text;
696
+ };
697
+
698
+ let deadlineHit = false
699
+ let processed = 0
700
+ for (const file of discovery.files) {
701
+ if (scanOptions.deadlineAt > 0 && Date.now() > scanOptions.deadlineAt) {
702
+ deadlineHit = true
703
+ break
704
+ }
705
+ processed += 1
706
+ if (processed % 25 === 0) await yieldToEventLoop()
707
+ const relativeFile = relPosix(file.rel);
708
+ if (readDirectly.has(relativeFile)) continue;
709
+ const text = await readFile(file);
710
+ if (text === null) continue;
711
+ const baseName = path.posix.basename(relativeFile);
712
+ const extension = path.posix.extname(relativeFile).toLowerCase();
713
+ if (baseName === 'cordis.patch.yml' || patchPaths.includes(relativeFile)) {
714
+ if (!foundPatches.includes(relativeFile)) foundPatches.push(relativeFile);
715
+ rawFindings.push(...scanPatchFile({ file: relativeFile, text }));
716
+ scanOptions.onProgress?.(relativeFile);
717
+ continue;
718
+ }
719
+ if (CODE_EXTENSIONS.has(extension)) {
720
+ try {
721
+ rawFindings.push(...scanCodeFile({
722
+ file: relativeFile,
723
+ text,
724
+ isClient: isClientFile(relativeFile, pkg),
725
+ ast: scanOptions.ast,
726
+ deadlineAt: scanOptions.deadlineAt,
727
+ }));
728
+ } catch (error) {
729
+ if (error?.code !== 'VG_SCAN_DEADLINE') throw error
730
+ // Keep the findings collected before the deadline and stop cleanly.
731
+ rawFindings.push(...(Array.isArray(error.findings) ? error.findings : []));
732
+ deadlineHit = true;
733
+ break;
734
+ }
735
+ }
736
+ scanOptions.onProgress?.(relativeFile);
737
+ // Other text files (.json/.yml/.md) are read for completeness/limits but
738
+ // deliberately not matched with code rules (documented limitation).
739
+ }
740
+
741
+ const patchExists = foundPatches.length > 0;
742
+ if (manifestText !== '') {
743
+ rawFindings.push(...scanPackageManifest({
744
+ file: manifestRel,
745
+ text: manifestText,
746
+ patchExists,
747
+ }));
748
+ }
749
+
750
+ if (discovery.truncated || deadlineHit || filesSkipped > 0) {
751
+ const reason = deadlineHit ? ',且达到时间上限' : discovery.truncated ? ',且结果因文件数上限被截断' : '';
752
+ const detail = `${filesSkipped} 个文件被跳过${reason}`;
753
+ rawFindings.push({
754
+ ruleId: 'VG-SCAN-03',
755
+ file: '.',
756
+ line: null,
757
+ evidence: detail,
758
+ vars: { detail },
759
+ });
760
+ }
761
+
762
+ const target = {
763
+ dir: absoluteDir,
764
+ name: pkg && typeof pkg.name === 'string' && pkg.name ? pkg.name : (path.basename(absoluteDir) || '(未知目标)'),
765
+ version: pkg && typeof pkg.version === 'string' && pkg.version ? pkg.version : null,
766
+ isDshPlugin: Boolean(pkg && typeof pkg === 'object' && pkg.dsh) || patchExists,
767
+ };
768
+
769
+ return buildReport({
770
+ target,
771
+ startedAt,
772
+ durationMs: elapsedMs(startedClock),
773
+ filesScanned,
774
+ rawFindings,
775
+ limits: {
776
+ filesSkipped,
777
+ bytesSkipped: discovery.bytesSkipped,
778
+ truncated: discovery.truncated || deadlineHit,
779
+ deadline: discovery.deadline || deadlineHit,
780
+ ignoredDirectories: [...discovery.ignoredDirectories],
781
+ unauditedEntry: ignoredEntryDirs.length > 0,
782
+ nonTextFiles: discovery.nonTextFiles,
783
+ },
784
+ includeInfo: scanOptions.includeInfo,
785
+ });
786
+ } catch (error) {
787
+ // Defensive: the scanner must never throw. Report the failure honestly as a
788
+ // blocker instead of pretending the package is clean.
789
+ const absolute = safeResolve(targetDir);
790
+ const reason = truncateReason(error);
791
+ const raw = [{
792
+ ruleId: 'VG-SCAN-01',
793
+ file: '.',
794
+ line: null,
795
+ evidence: `扫描器内部错误:${reason}`,
796
+ vars: { reason },
797
+ confidence: 'confirmed',
798
+ }];
799
+ return buildReport({
800
+ target: {
801
+ dir: absolute,
802
+ name: path.basename(absolute) || '(未知目标)',
803
+ version: null,
804
+ isDshPlugin: false,
805
+ },
806
+ startedAt,
807
+ durationMs: elapsedMs(startedClock),
808
+ filesScanned: 0,
809
+ rawFindings: raw,
810
+ limits: { filesSkipped: 0, bytesSkipped: 0, truncated: false },
811
+ includeInfo: true,
812
+ });
813
+ }
814
+ }
815
+
816
+ /**
817
+ * Render a human-readable Chinese terminal card for a report. No ANSI needed;
818
+ * the card is plain text so it can be pasted into tickets or logs.
819
+ *
820
+ * @param {Report} report
821
+ * @param {{ maxFindings?: number }} [options]
822
+ * @returns {string}
823
+ */
824
+ export function formatReportCard(report, options = {}) {
825
+ const source = report && typeof report === 'object' ? report : {};
826
+ const cardOptions = options && typeof options === 'object' ? options : {};
827
+ const maxFindings = Number.isFinite(cardOptions.maxFindings) && cardOptions.maxFindings > 0
828
+ ? Math.min(Math.floor(cardOptions.maxFindings), 100)
829
+ : 24;
830
+ const target = source.target && typeof source.target === 'object' ? source.target : {};
831
+ const summary = source.summary && typeof source.summary === 'object' ? source.summary : {};
832
+ const limits = source.limits && typeof source.limits === 'object' ? source.limits : {};
833
+ const findings = Array.isArray(source.findings) ? source.findings : [];
834
+ const lines = [];
835
+ const push = (line = '') => lines.push(line);
836
+
837
+ push('dsh-vigil 守夜人 · 安装前静态审计');
838
+ push('============================================================');
839
+ push(`目标:${target.name ?? '(未知)'}${target.version ? `@${target.version}` : ''}`);
840
+ push(`目录:${target.dir ?? '(未知)'}`);
841
+ push(`dsh 插件:${target.isDshPlugin ? '是' : '否/未声明'} · 扫描文件:${source.filesScanned ?? 0} 个 · 用时:${source.durationMs ?? 0} ms`);
842
+ push(`结论:blocker ${summary.blocker ?? 0} · review ${summary.review ?? 0} · notice ${summary.notice ?? 0} · info ${summary.info ?? 0}(共 ${summary.total ?? findings.length} 条)`);
843
+
844
+ const byCategory = summary.byCategory && typeof summary.byCategory === 'object' ? summary.byCategory : {};
845
+ const categoryParts = CATEGORIES
846
+ .filter((category) => Number(byCategory[category]) > 0)
847
+ .map((category) => `${CATEGORY_LABELS[category]} ${byCategory[category]}`);
848
+ if (categoryParts.length > 0) push(`风险面:${categoryParts.join(' / ')}`);
849
+ push('');
850
+
851
+ if (findings.length === 0) {
852
+ push('未发现静态风险信号。');
853
+ push('注意:没有发现不代表安全;静态扫描无法覆盖运行时可变行为(见文末免责声明)。');
854
+ } else {
855
+ push('发现(按严重度排序):');
856
+ const visible = findings.slice(0, maxFindings);
857
+ for (const finding of visible) {
858
+ const severity = String(finding.severity ?? 'notice').toUpperCase();
859
+ push(`[${severity}] ${finding.title ?? finding.ruleId ?? '未命名发现'}`);
860
+ const location = `${finding.file ?? '?'}${Number.isInteger(finding.line) ? `:${finding.line}` : ''}`;
861
+ const confidence = finding.confidence === 'heuristic' ? ' · 推测' : '';
862
+ push(` 位置:${location}(${finding.ruleId ?? '?'}${confidence})`);
863
+ if (finding.evidence) push(` 证据:${redactEvidence(finding.evidence)}`);
864
+ if (finding.means) push(` ${finding.means}`);
865
+ if (finding.mitigation) push(` 缓解:${finding.mitigation}`);
866
+ push('');
867
+ }
868
+ if (findings.length > visible.length) {
869
+ push(`…… 其余 ${findings.length - visible.length} 条发现见 JSON 报告。`);
870
+ push('');
871
+ }
872
+ }
873
+
874
+ push('扫描限制:');
875
+ push(` 跳过文件:${limits.filesSkipped ?? 0} · 跳过字节:${limits.bytesSkipped ?? 0} · 非文本跳过:${limits.nonTextFiles ?? 0} · 结果被截断:${limits.truncated ? '是' : '否'}`);
876
+ push('');
877
+ push('免责声明:');
878
+ push(` ${source.disclaimer ?? DISCLAIMER}`);
879
+ return lines.join('\n');
880
+ }