dsh-vigil 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,127 +1,127 @@
1
- /**
2
- * Static audit helper shared by the `plugin_manager` tool pre-check and the
3
- * install watcher: turn one `scanPluginDirectory()` report into a compact,
4
- * JSON-safe summary for audit records, feeds and notices.
5
- *
6
- * @module dsh-vigil/audit/install-scan
7
- */
8
-
9
- import { existsSync, statSync } from 'node:fs'
10
- import { homedir } from 'node:os'
11
- import { isAbsolute, join, resolve } from 'node:path'
12
- import { truncate } from '../util.js'
13
- import { RULE_BY_ID } from './rules.js'
14
-
15
- /**
16
- * Resolve a tool argument that names a local plugin directory to install.
17
- * Registry/git/tarball specs return null: they cannot be scanned before the
18
- * package manager downloads them (the install watcher audits the installed copy).
19
- * @param {Record<string, unknown>} args
20
- * @param {{ cwd?: string }} [options]
21
- * @returns {{ spec: string, dir: string } | null}
22
- */
23
- export function resolveLocalInstallTarget(args, options = {}) {
24
- const cwd = options.cwd ?? process.cwd()
25
- const spec = ['spec', 'target', 'path', 'source', 'bundle', 'name']
26
- .map(key => args?.[key])
27
- .find(value => typeof value === 'string' && value.trim() !== '')
28
- if (!spec) return null
29
- const looksLocal = spec.startsWith('.') || spec.startsWith('~') || spec.startsWith('/') || /^[A-Za-z]:[\\/]/.test(spec) || spec.startsWith('\\\\') || spec.includes('\\') || spec.includes('/')
30
- if (!looksLocal) return null
31
- const absolute = spec.startsWith('~')
32
- ? resolve(homedir(), spec.replace(/^~[\\/]?/, ''))
33
- : isAbsolute(spec)
34
- ? spec
35
- : resolve(cwd, spec)
36
- try {
37
- if (!statSync(absolute).isDirectory()) return null
38
- } catch {
39
- return null
40
- }
41
- const candidates = [absolute, join(absolute, 'package')]
42
- for (const candidate of candidates) {
43
- if (existsSync(join(candidate, 'package.json'))) return { spec, dir: candidate }
44
- }
45
- return null
46
- }
47
-
48
- /**
49
- * @param {any} report report from `scanPluginDirectory()`
50
- * @param {{ target?: string, dir?: string }} [meta]
51
- * @returns {{ target: string, dir: string, blockers: number, review: number, notice: number, ruleIds: string[], top: Array<object>, text: string }}
52
- */
53
- export function summarizeInstallScan(report, meta = {}) {
54
- const findings = Array.isArray(report?.findings) ? report.findings : []
55
- const summary = report?.summary && typeof report.summary === 'object' ? report.summary : {}
56
- const blockers = Number(summary.blocker) || 0
57
- const review = Number(summary.review) || 0
58
- const notice = Number(summary.notice) || 0
59
- const ruleIds = [...new Set(findings.map(finding => (typeof finding?.ruleId === 'string' ? finding.ruleId : null)).filter(Boolean))]
60
- // Keep a bounded sample for the audit panel but cover every severity, so a
61
- // package with many blockers does not hide its review/notice findings.
62
- const PER_SEVERITY_LIMIT = 50
63
- const sampled = []
64
- for (const severity of ['blocker', 'review', 'notice', 'info']) {
65
- sampled.push(...findings.filter(finding => (finding?.severity ?? 'unknown') === severity).slice(0, PER_SEVERITY_LIMIT))
66
- }
67
- sampled.push(...findings.filter(finding => !['blocker', 'review', 'notice', 'info'].includes(finding?.severity)).slice(0, PER_SEVERITY_LIMIT))
68
- const top = sampled.map(finding => {
69
- const ruleId = typeof finding?.ruleId === 'string' ? finding.ruleId : null
70
- return {
71
- ruleId,
72
- title: ruleId ? (RULE_BY_ID.get(ruleId)?.title ?? null) : null,
73
- severity: typeof finding?.severity === 'string' ? finding.severity : null,
74
- file: typeof finding?.file === 'string' ? finding.file : null,
75
- line: Number.isFinite(finding?.line) ? finding.line : null,
76
- evidence: truncate(String(finding?.evidence ?? ''), 160),
77
- means: truncate(String(finding?.means ?? ''), 300),
78
- mitigation: truncate(String(finding?.mitigation ?? ''), 300),
79
- }
80
- })
81
- const reasons = top
82
- .filter(item => item.severity === 'blocker' || item.severity === 'review')
83
- .map(item => {
84
- const where = item.file ? `(${item.file}${item.line ? `:${item.line}` : ''})` : ''
85
- return `${item.title ?? item.ruleId ?? '未知规则'}${where}`
86
- })
87
- // The install prompt says "N 个高危命中"; only blockers may be listed there.
88
- const blockerReasons = top
89
- .filter(item => item.severity === 'blocker')
90
- .map(item => {
91
- const where = item.file ? `(${item.file}${item.line ? `:${item.line}` : ''})` : ''
92
- return `${item.title ?? item.ruleId ?? '未知规则'}${where}`
93
- })
94
- // Coverage is part of the verdict: "0 blockers" only means something when the
95
- // scan actually read the files. A padded package must not be able to turn a
96
- // skipped file into a clean result.
97
- const filesSkipped = Number(report?.limits?.filesSkipped) || 0
98
- const bytesSkipped = Number(report?.limits?.bytesSkipped) || 0
99
- const scanTruncated = report?.limits?.truncated === true
100
- const unauditedEntry = report?.limits?.unauditedEntry === true
101
- const nonTextFiles = Number(report?.limits?.nonTextFiles) || 0
102
- const incomplete = scanTruncated || filesSkipped > 0 || bytesSkipped > 0 || unauditedEntry
103
- const coverageNote = incomplete
104
- ? `扫描未覆盖全部内容(跳过 ${filesSkipped} 个文件 / ${bytesSkipped} 字节${scanTruncated ? ',结果被截断' : ''}${unauditedEntry ? ';入口位于未扫描的构建目录' : ''})`
105
- : null
106
- return {
107
- target: String(meta.target ?? ''),
108
- dir: String(meta.dir ?? ''),
109
- blockers,
110
- review,
111
- notice,
112
- ruleIds,
113
- top,
114
- total: findings.length,
115
- truncated: sampled.length < findings.length,
116
- filesSkipped,
117
- bytesSkipped,
118
- scanTruncated,
119
- unauditedEntry,
120
- nonTextFiles,
121
- incomplete,
122
- coverageNote,
123
- reasons,
124
- blockerReasons,
125
- text: `安装前静态审计:${blockers} 个高危,${review} 个可疑,${notice} 个提示${coverageNote ? `;${coverageNote}` : ''}`,
126
- }
127
- }
1
+ /**
2
+ * Static audit helper shared by the `plugin_manager` tool pre-check and the
3
+ * install watcher: turn one `scanPluginDirectory()` report into a compact,
4
+ * JSON-safe summary for audit records, feeds and notices.
5
+ *
6
+ * @module dsh-vigil/audit/install-scan
7
+ */
8
+
9
+ import { existsSync, statSync } from 'node:fs'
10
+ import { homedir } from 'node:os'
11
+ import { isAbsolute, join, resolve } from 'node:path'
12
+ import { truncate } from '../util.js'
13
+ import { RULE_BY_ID } from './rules.js'
14
+
15
+ /**
16
+ * Resolve a tool argument that names a local plugin directory to install.
17
+ * Registry/git/tarball specs return null: they cannot be scanned before the
18
+ * package manager downloads them (the install watcher audits the installed copy).
19
+ * @param {Record<string, unknown>} args
20
+ * @param {{ cwd?: string }} [options]
21
+ * @returns {{ spec: string, dir: string } | null}
22
+ */
23
+ export function resolveLocalInstallTarget(args, options = {}) {
24
+ const cwd = options.cwd ?? process.cwd()
25
+ const spec = ['spec', 'target', 'path', 'source', 'bundle', 'name']
26
+ .map(key => args?.[key])
27
+ .find(value => typeof value === 'string' && value.trim() !== '')
28
+ if (!spec) return null
29
+ const looksLocal = spec.startsWith('.') || spec.startsWith('~') || spec.startsWith('/') || /^[A-Za-z]:[\\/]/.test(spec) || spec.startsWith('\\\\') || spec.includes('\\') || spec.includes('/')
30
+ if (!looksLocal) return null
31
+ const absolute = spec.startsWith('~')
32
+ ? resolve(homedir(), spec.replace(/^~[\\/]?/, ''))
33
+ : isAbsolute(spec)
34
+ ? spec
35
+ : resolve(cwd, spec)
36
+ try {
37
+ if (!statSync(absolute).isDirectory()) return null
38
+ } catch {
39
+ return null
40
+ }
41
+ const candidates = [absolute, join(absolute, 'package')]
42
+ for (const candidate of candidates) {
43
+ if (existsSync(join(candidate, 'package.json'))) return { spec, dir: candidate }
44
+ }
45
+ return null
46
+ }
47
+
48
+ /**
49
+ * @param {any} report report from `scanPluginDirectory()`
50
+ * @param {{ target?: string, dir?: string }} [meta]
51
+ * @returns {{ target: string, dir: string, blockers: number, review: number, notice: number, ruleIds: string[], top: Array<object>, text: string }}
52
+ */
53
+ export function summarizeInstallScan(report, meta = {}) {
54
+ const findings = Array.isArray(report?.findings) ? report.findings : []
55
+ const summary = report?.summary && typeof report.summary === 'object' ? report.summary : {}
56
+ const blockers = Number(summary.blocker) || 0
57
+ const review = Number(summary.review) || 0
58
+ const notice = Number(summary.notice) || 0
59
+ const ruleIds = [...new Set(findings.map(finding => (typeof finding?.ruleId === 'string' ? finding.ruleId : null)).filter(Boolean))]
60
+ // Keep a bounded sample for the audit panel but cover every severity, so a
61
+ // package with many blockers does not hide its review/notice findings.
62
+ const PER_SEVERITY_LIMIT = 50
63
+ const sampled = []
64
+ for (const severity of ['blocker', 'review', 'notice', 'info']) {
65
+ sampled.push(...findings.filter(finding => (finding?.severity ?? 'unknown') === severity).slice(0, PER_SEVERITY_LIMIT))
66
+ }
67
+ sampled.push(...findings.filter(finding => !['blocker', 'review', 'notice', 'info'].includes(finding?.severity)).slice(0, PER_SEVERITY_LIMIT))
68
+ const top = sampled.map(finding => {
69
+ const ruleId = typeof finding?.ruleId === 'string' ? finding.ruleId : null
70
+ return {
71
+ ruleId,
72
+ title: ruleId ? (RULE_BY_ID.get(ruleId)?.title ?? null) : null,
73
+ severity: typeof finding?.severity === 'string' ? finding.severity : null,
74
+ file: typeof finding?.file === 'string' ? finding.file : null,
75
+ line: Number.isFinite(finding?.line) ? finding.line : null,
76
+ evidence: truncate(String(finding?.evidence ?? ''), 160),
77
+ means: truncate(String(finding?.means ?? ''), 300),
78
+ mitigation: truncate(String(finding?.mitigation ?? ''), 300),
79
+ }
80
+ })
81
+ const reasons = top
82
+ .filter(item => item.severity === 'blocker' || item.severity === 'review')
83
+ .map(item => {
84
+ const where = item.file ? `(${item.file}${item.line ? `:${item.line}` : ''})` : ''
85
+ return `${item.title ?? item.ruleId ?? '未知规则'}${where}`
86
+ })
87
+ // The install prompt says "N 个高危命中"; only blockers may be listed there.
88
+ const blockerReasons = top
89
+ .filter(item => item.severity === 'blocker')
90
+ .map(item => {
91
+ const where = item.file ? `(${item.file}${item.line ? `:${item.line}` : ''})` : ''
92
+ return `${item.title ?? item.ruleId ?? '未知规则'}${where}`
93
+ })
94
+ // Coverage is part of the verdict: "0 blockers" only means something when the
95
+ // scan actually read the files. A padded package must not be able to turn a
96
+ // skipped file into a clean result.
97
+ const filesSkipped = Number(report?.limits?.filesSkipped) || 0
98
+ const bytesSkipped = Number(report?.limits?.bytesSkipped) || 0
99
+ const scanTruncated = report?.limits?.truncated === true
100
+ const unauditedEntry = report?.limits?.unauditedEntry === true
101
+ const nonTextFiles = Number(report?.limits?.nonTextFiles) || 0
102
+ const incomplete = scanTruncated || filesSkipped > 0 || bytesSkipped > 0 || unauditedEntry
103
+ const coverageNote = incomplete
104
+ ? `扫描未覆盖全部内容(跳过 ${filesSkipped} 个文件 / ${bytesSkipped} 字节${scanTruncated ? ',结果被截断' : ''}${unauditedEntry ? ';入口位于未扫描的构建目录' : ''})`
105
+ : null
106
+ return {
107
+ target: String(meta.target ?? ''),
108
+ dir: String(meta.dir ?? ''),
109
+ blockers,
110
+ review,
111
+ notice,
112
+ ruleIds,
113
+ top,
114
+ total: findings.length,
115
+ truncated: sampled.length < findings.length,
116
+ filesSkipped,
117
+ bytesSkipped,
118
+ scanTruncated,
119
+ unauditedEntry,
120
+ nonTextFiles,
121
+ incomplete,
122
+ coverageNote,
123
+ reasons,
124
+ blockerReasons,
125
+ text: `安装前静态审计:${blockers} 个高危,${review} 个可疑,${notice} 个提示${coverageNote ? `;${coverageNote}` : ''}`,
126
+ }
127
+ }