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.
- package/LICENSE +201 -0
- package/README.md +188 -0
- package/client.js +4652 -0
- package/cordis.patch.yml +7 -0
- package/docs/DETAIL.md +66 -0
- package/icon.png +0 -0
- package/illustrations/notice.png +0 -0
- package/illustrations/warning.png +0 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +75 -0
- package/rules/audit.yaml +130 -0
- package/rules/manifest.json +7 -0
- package/rules/sentinel.yaml +289 -0
- package/src/alert-route.js +194 -0
- package/src/approval.js +398 -0
- package/src/artwork-route.js +87 -0
- package/src/audit/ast.js +213 -0
- package/src/audit/install-scan.js +127 -0
- package/src/audit/lexer.js +307 -0
- package/src/audit/narrative.js +320 -0
- package/src/audit/rules.js +1440 -0
- package/src/audit/scan.js +880 -0
- package/src/audit-clear-route.js +89 -0
- package/src/audit-feed.js +265 -0
- package/src/audit-log.js +887 -0
- package/src/config-schema.js +194 -0
- package/src/config.js +580 -0
- package/src/delete/command-kinds.js +46 -0
- package/src/delete/lex.js +46 -0
- package/src/delete/parser-posix.js +1427 -0
- package/src/delete/parser-pwsh.js +1729 -0
- package/src/delete/parser.js +2082 -0
- package/src/delete/policy.js +680 -0
- package/src/delete/quarantine.js +417 -0
- package/src/index.js +1134 -0
- package/src/install-scan-route.js +58 -0
- package/src/install-watch.js +389 -0
- package/src/integrity.js +509 -0
- package/src/live-config.js +88 -0
- package/src/quarantine-route.js +74 -0
- package/src/quarantine-view.js +44 -0
- package/src/rules/pack.js +423 -0
- package/src/rules/update.js +341 -0
- package/src/rules/yaml.js +186 -0
- package/src/sage-action-route.js +63 -0
- package/src/sage-provision.js +716 -0
- package/src/sentinel/guard.js +392 -0
- package/src/sentinel/hook.js +546 -0
- package/src/sentinel/rules.js +488 -0
- package/src/sentinel/sage-load.js +79 -0
- package/src/sentinel/sage.js +550 -0
- package/src/tools.js +727 -0
- package/src/update-check.js +339 -0
- package/src/util.js +400 -0
- package/threats/README.md +25 -0
|
@@ -0,0 +1,1440 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module dsh-vigil/audit/rules
|
|
3
|
+
*
|
|
4
|
+
* Built-in static audit rule catalog and matchers for dsh plugin packages.
|
|
5
|
+
*
|
|
6
|
+
* The rules are text/regex based and NEVER import, evaluate, or otherwise
|
|
7
|
+
* execute the scanned code. JavaScript/TypeScript sources are analyzed through
|
|
8
|
+
* the comment/string-aware masks from `lexer.js`; `package.json` is parsed as
|
|
9
|
+
* JSON data only; `cordis.patch.yml` goes through a small bounded line-based
|
|
10
|
+
* parser (no YAML dependency, no code evaluation of `!!js`).
|
|
11
|
+
*
|
|
12
|
+
* Rule ids are stable and grouped by prefix:
|
|
13
|
+
* VG-CRED-* credential access
|
|
14
|
+
* VG-NET-* network egress
|
|
15
|
+
* VG-DYN-* dynamic code execution
|
|
16
|
+
* VG-CFG-* config tampering
|
|
17
|
+
* VG-SUP-* supply chain
|
|
18
|
+
* VG-INJ-* dsh plugin-tree / patch injection
|
|
19
|
+
* VG-DSH-* dsh-specific attack surface
|
|
20
|
+
* VG-SCAN-* scanner-level findings (target/file unreadable, limits)
|
|
21
|
+
*
|
|
22
|
+
* @typedef {Object} RawFinding
|
|
23
|
+
* @property {string} ruleId
|
|
24
|
+
* @property {string} file POSIX path relative to the scanned directory.
|
|
25
|
+
* @property {number|null} line 1-based source line, or null for file-level.
|
|
26
|
+
* @property {string} evidence Trimmed source line / JSON snippet.
|
|
27
|
+
* @property {Record<string, unknown>} [vars] Narrative placeholder values.
|
|
28
|
+
* @property {'confirmed'|'heuristic'} [confidence]
|
|
29
|
+
* @property {'blocker'|'review'|'notice'|'info'} [severity] Severity override.
|
|
30
|
+
* @property {string} [extraMeans] Extra sentence appended to "这意味着".
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
import { maskSource } from './lexer.js';
|
|
34
|
+
import {
|
|
35
|
+
buildNarrative,
|
|
36
|
+
escalationSentence,
|
|
37
|
+
RULE_ATTRIBUTION,
|
|
38
|
+
truncateEvidence,
|
|
39
|
+
} from './narrative.js';
|
|
40
|
+
import { getRulePack } from '../rules/pack.js';
|
|
41
|
+
import { analyzeAliases } from './ast.js';
|
|
42
|
+
|
|
43
|
+
/** @typedef {'credential'|'network'|'dynamic-code'|'config-tamper'|'supply-chain'|'dsh-attack'|'unknown'} RuleCategory */
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Rule metadata catalog (id, category, severity, title, attribution).
|
|
47
|
+
* Narrative templates live in `narrative.js` so the text stays in one place.
|
|
48
|
+
*
|
|
49
|
+
* @type {{ id: string, category: RuleCategory, severity: 'blocker'|'review'|'notice'|'info', title: string, attribution: string }[]}
|
|
50
|
+
*/
|
|
51
|
+
const RULE_DEFS = [
|
|
52
|
+
['VG-CRED-01', 'credential', 'blocker', '源码中硬编码了疑似密钥/令牌'],
|
|
53
|
+
['VG-CRED-02', 'credential', 'blocker', '包内包含私钥 PEM 内容'],
|
|
54
|
+
['VG-CRED-03', 'credential', 'review', '插件引用了本机敏感凭证路径'],
|
|
55
|
+
['VG-CRED-04', 'credential', 'notice', '插件读取凭证类环境变量'],
|
|
56
|
+
['VG-NET-01', 'network', 'review', '插件向非白名单主机发起网络请求'],
|
|
57
|
+
['VG-NET-02', 'network', 'blocker', '插件向已知回传/一次性端点外发数据'],
|
|
58
|
+
['VG-NET-03', 'network', 'blocker', '插件向裸 IP 地址发起连接'],
|
|
59
|
+
['VG-NET-04', 'network', 'notice', '网络外发目标无法静态确定'],
|
|
60
|
+
['VG-DYN-01', 'dynamic-code', 'review', '插件使用 eval 等动态代码执行能力'],
|
|
61
|
+
['VG-DYN-02', 'dynamic-code', 'review', '插件具备子进程/系统命令执行能力'],
|
|
62
|
+
['VG-DYN-03', 'dynamic-code', 'blocker', '插件包含下载后立即执行的模式'],
|
|
63
|
+
['VG-DYN-04', 'dynamic-code', 'review', '插件在运行时动态加载模块'],
|
|
64
|
+
['VG-DYN-05', 'dynamic-code', 'review', '插件使用 vm 模块执行动态代码'],
|
|
65
|
+
['VG-DYN-06', 'dynamic-code', 'review', '编码载荷(base64/hex)解码后含可疑内容'],
|
|
66
|
+
['VG-CFG-01', 'config-tamper', 'review', '插件会写入 dsh 配置文件/目录'],
|
|
67
|
+
['VG-CFG-02', 'config-tamper', 'notice', '插件会读取 dsh 配置文件/目录'],
|
|
68
|
+
['VG-CFG-03', 'config-tamper', 'blocker', '插件改写或声明高风险权限策略'],
|
|
69
|
+
['VG-CFG-04', 'config-tamper', 'review', '插件写入 DSH_* 环境变量'],
|
|
70
|
+
['VG-SUP-01', 'supply-chain', 'blocker', '安装脚本包含网络下载或 shell 执行'],
|
|
71
|
+
['VG-SUP-02', 'supply-chain', 'review', '安装包带有安装生命周期脚本'],
|
|
72
|
+
['VG-SUP-03', 'supply-chain', 'notice', '依赖版本未锁定或来源不可复现'],
|
|
73
|
+
['VG-SUP-04', 'supply-chain', 'blocker', '依赖通过明文 HTTP 拉取'],
|
|
74
|
+
['VG-SUP-05', 'supply-chain', 'review', '存在补丁文件但清单未正确声明加载方式'],
|
|
75
|
+
['VG-SUP-06', 'supply-chain', 'notice', '存在 cordis.patch.yml 但清单无 dsh 声明'],
|
|
76
|
+
['VG-SUP-07', 'supply-chain', 'notice', 'package.json 缺少 name/version'],
|
|
77
|
+
['VG-SUP-08', 'supply-chain', 'notice', 'package.json 含构建/测试之外的脚本'],
|
|
78
|
+
['VG-SUP-09', 'supply-chain', 'notice', 'package.json 无法解析'],
|
|
79
|
+
['VG-INJ-01', 'dsh-attack', 'blocker', '补丁注入高权限服务或配置'],
|
|
80
|
+
['VG-INJ-02', 'dsh-attack', 'review', '补丁覆盖既有配置行'],
|
|
81
|
+
['VG-INJ-03', 'dsh-attack', 'review', '补丁在分组内深层 insert'],
|
|
82
|
+
['VG-INJ-04', 'dsh-attack', 'review', '补丁配置包含 !!js 表达式'],
|
|
83
|
+
['VG-INJ-05', 'dsh-attack', 'notice', '补丁行无法被可靠识别'],
|
|
84
|
+
['VG-INJ-06', 'dsh-attack', 'notice', 'cordis.patch.yml 无法静态解析'],
|
|
85
|
+
['VG-DSH-01', 'dsh-attack', 'review', '插件浏览器端代码具备网络外发能力'],
|
|
86
|
+
['VG-DSH-02', 'dsh-attack', 'review', '插件浏览器端代码访问本地存储/cookie'],
|
|
87
|
+
['VG-DSH-03', 'dsh-attack', 'review', '插件浏览器端同时出现存储访问与网络请求(疑似外传)'],
|
|
88
|
+
['VG-DSH-04', 'dsh-attack', 'review', '插件浏览器端代码直接操作 DOM/注入 iframe'],
|
|
89
|
+
['VG-DSH-05', 'dsh-attack', 'blocker', '插件声明以高权限模式运行'],
|
|
90
|
+
['VG-DSH-06', 'dsh-attack', 'blocker', 'bundle patch 指向包外路径'],
|
|
91
|
+
['VG-SCAN-01', 'unknown', 'blocker', '目标目录不可读取'],
|
|
92
|
+
['VG-SCAN-02', 'unknown', 'notice', '文件或目录不可读取'],
|
|
93
|
+
['VG-SCAN-03', 'unknown', 'info', '扫描因限制跳过了部分内容'],
|
|
94
|
+
['VG-SCAN-04', 'unknown', 'review', '入口位于未扫描的构建目录'],
|
|
95
|
+
['VG-SCAN-05', 'unknown', 'notice', 'AST 别名分析不可用,已跳过'],
|
|
96
|
+
];
|
|
97
|
+
|
|
98
|
+
/** Public rule catalog (id, category, severity, title, attribution). */
|
|
99
|
+
export const RULE_CATALOG = RULE_DEFS.map(([id, category, severity, title]) => ({
|
|
100
|
+
id,
|
|
101
|
+
category,
|
|
102
|
+
severity,
|
|
103
|
+
title,
|
|
104
|
+
attribution: RULE_ATTRIBUTION,
|
|
105
|
+
}));
|
|
106
|
+
|
|
107
|
+
/** @type {Map<string, (typeof RULE_CATALOG)[number]>} */
|
|
108
|
+
export const RULE_BY_ID = new Map(RULE_CATALOG.map((rule) => [rule.id, rule]));
|
|
109
|
+
|
|
110
|
+
/** Rules whose matches are direct, high-confidence detections. */
|
|
111
|
+
const CONFIRMED_RULES = new Set([
|
|
112
|
+
'VG-CRED-01',
|
|
113
|
+
'VG-CRED-02',
|
|
114
|
+
'VG-NET-02',
|
|
115
|
+
'VG-NET-03',
|
|
116
|
+
'VG-DYN-03',
|
|
117
|
+
'VG-SUP-01',
|
|
118
|
+
'VG-SUP-04',
|
|
119
|
+
'VG-SUP-09',
|
|
120
|
+
'VG-DSH-06',
|
|
121
|
+
'VG-SCAN-01',
|
|
122
|
+
'VG-SCAN-02',
|
|
123
|
+
'VG-INJ-06',
|
|
124
|
+
]);
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Turn a raw matcher hit into a full Finding-shaped object (id assigned later
|
|
128
|
+
* by the scanner to keep ids deterministic after sorting/deduping).
|
|
129
|
+
*
|
|
130
|
+
* @param {RawFinding} raw
|
|
131
|
+
* @returns {Omit<import('./scan.js').Finding, 'id'> & { id: string }}
|
|
132
|
+
*/
|
|
133
|
+
export function materializeFinding(raw) {
|
|
134
|
+
const rule = RULE_BY_ID.get(raw.ruleId);
|
|
135
|
+
const narrative = buildNarrative(raw.ruleId, raw.vars ?? {});
|
|
136
|
+
const severity = raw.severity ?? rule?.severity ?? 'notice';
|
|
137
|
+
const means = raw.extraMeans ? `${narrative.means}${raw.extraMeans}` : narrative.means;
|
|
138
|
+
return {
|
|
139
|
+
id: typeof raw.id === 'string' ? raw.id : '',
|
|
140
|
+
ruleId: raw.ruleId,
|
|
141
|
+
category: rule?.category ?? 'unknown',
|
|
142
|
+
severity,
|
|
143
|
+
title: rule?.title ?? '未知规则命中',
|
|
144
|
+
file: raw.file,
|
|
145
|
+
line: Number.isInteger(raw.line) && raw.line > 0 ? raw.line : null,
|
|
146
|
+
evidence: truncateEvidence(raw.evidence),
|
|
147
|
+
means,
|
|
148
|
+
mitigation: narrative.mitigation,
|
|
149
|
+
confidence: raw.confidence ?? (CONFIRMED_RULES.has(raw.ruleId) ? 'confirmed' : 'heuristic'),
|
|
150
|
+
ruleAttribution: rule?.attribution ?? RULE_ATTRIBUTION,
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/* ------------------------------------------------------------------------- *
|
|
155
|
+
* Shared matching helpers
|
|
156
|
+
* ------------------------------------------------------------------------- */
|
|
157
|
+
|
|
158
|
+
/** Escape a string for use inside a RegExp. */
|
|
159
|
+
function escapeRegExp(value) {
|
|
160
|
+
return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Return the 1-based line matching `pattern`, or null. */
|
|
164
|
+
function findLineNumber(text, pattern) {
|
|
165
|
+
const lines = String(text ?? '').split('\n');
|
|
166
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
167
|
+
if (pattern.test(lines[i])) return i + 1;
|
|
168
|
+
}
|
|
169
|
+
return null;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Return the raw text of a 1-based line (without trailing CR). */
|
|
173
|
+
/** Small line cache: rules call lineTextAt once per finding, not per line. */
|
|
174
|
+
const lineCache = new Map()
|
|
175
|
+
function lineTextAt(text, line) {
|
|
176
|
+
if (!Number.isInteger(line) || line < 1) return '';
|
|
177
|
+
const source = String(text ?? '');
|
|
178
|
+
let lines = lineCache.get(source);
|
|
179
|
+
if (!lines) {
|
|
180
|
+
lines = source.split('\n');
|
|
181
|
+
lineCache.set(source, lines);
|
|
182
|
+
if (lineCache.size > 4) lineCache.delete(lineCache.keys().next().value);
|
|
183
|
+
}
|
|
184
|
+
const raw = lines[line - 1] ?? '';
|
|
185
|
+
return raw.endsWith('\r') ? raw.slice(0, -1) : raw;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/* ------------------------------------------------------------------------- *
|
|
189
|
+
* package.json analysis
|
|
190
|
+
* ------------------------------------------------------------------------- */
|
|
191
|
+
|
|
192
|
+
const LIFECYCLE_SCRIPTS = new Set([
|
|
193
|
+
'preinstall',
|
|
194
|
+
'install',
|
|
195
|
+
'postinstall',
|
|
196
|
+
'prepare',
|
|
197
|
+
'postprepare',
|
|
198
|
+
'prepublish',
|
|
199
|
+
'prepublishOnly',
|
|
200
|
+
'prepack',
|
|
201
|
+
]);
|
|
202
|
+
|
|
203
|
+
/** Script names that are ordinary development tooling (not reported). */
|
|
204
|
+
const SAFE_SCRIPT_RE = /^(?:pre|post)?(?:build|test|lint|check|typecheck|format|clean|dev)(?::|$)/;
|
|
205
|
+
|
|
206
|
+
/** Commands that indicate network access or shell execution inside a script. */
|
|
207
|
+
const RISKY_SCRIPT_RE = /(?:\bcurl\b|\bwget\b|\bInvoke-WebRequest\b|\biwr\b|\bInvoke-RestMethod\b|\birm\b|https?:\/\/|\bnpm\s+(?:install|i)\b|\bpnpm\s+(?:install|add)\b|\byarn\s+(?:add|install)\b|\bnode\s+(?:-e|--eval)\b|\b(?:bash|sh|zsh|powershell|pwsh|cmd(?:\.exe)?)\b|\bchild_process\b|\bexec(?:Sync)?\s*\(|\bspawn(?:Sync)?\s*\(|\beval\s*\(|\bpython\s+-c\b|\bpip\s+install\b)/i;
|
|
208
|
+
|
|
209
|
+
const DANGEROUS_VALUE_RE = /\b(?:danger-full-access|dangerously-skip-permissions|bypassPermissions|bypass[-_]permissions)\b/i;
|
|
210
|
+
const DSH_PRIVILEGE_LINE_RE = /"(?:danger-full-access|dangerously-skip-permissions|bypassPermissions|approval|sandbox|permissionPresets|permission-presets)"\s*:/;
|
|
211
|
+
|
|
212
|
+
/** Recursively collect all strings in an exports-like value. */
|
|
213
|
+
function collectStrings(value, out = []) {
|
|
214
|
+
if (typeof value === 'string') out.push(value);
|
|
215
|
+
else if (Array.isArray(value)) value.forEach((entry) => collectStrings(entry, out));
|
|
216
|
+
else if (value && typeof value === 'object') Object.values(value).forEach((entry) => collectStrings(entry, out));
|
|
217
|
+
return out;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** True when package exports declare ./cordis.patch.yml in any supported shape. */
|
|
221
|
+
function hasCordisPatchExport(exportsField) {
|
|
222
|
+
if (typeof exportsField === 'string') return exportsField.includes('cordis.patch.yml');
|
|
223
|
+
if (exportsField && typeof exportsField === 'object' && !Array.isArray(exportsField)) {
|
|
224
|
+
if (Object.prototype.hasOwnProperty.call(exportsField, './cordis.patch.yml')) return true;
|
|
225
|
+
return collectStrings(exportsField).some((value) => /(?:^|\/)cordis\.patch\.yml$/.test(value));
|
|
226
|
+
}
|
|
227
|
+
return false;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** `dsh.bundle.patch` accepts a string or an array of strings. */
|
|
231
|
+
function patchSpecs(bundlePatch) {
|
|
232
|
+
if (typeof bundlePatch === 'string') return bundlePatch.trim() === '' ? [] : [bundlePatch];
|
|
233
|
+
if (Array.isArray(bundlePatch)) return bundlePatch.filter((item) => typeof item === 'string' && item.trim() !== '');
|
|
234
|
+
return [];
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** True when the manifest declares at least one patch path. */
|
|
238
|
+
function declaresPatch(bundlePatch) {
|
|
239
|
+
return patchSpecs(bundlePatch).length > 0;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** True when a dsh.bundle.patch path escapes the package root. */
|
|
243
|
+
function escapesPackage(patchPath) {
|
|
244
|
+
const normalized = String(patchPath).replace(/\\/g, '/').trim();
|
|
245
|
+
if (!normalized) return false;
|
|
246
|
+
if (/^(?:[a-zA-Z]:)?\//.test(normalized)) return true;
|
|
247
|
+
const withoutDot = normalized.replace(/^\.\//, '');
|
|
248
|
+
return withoutDot === '..' || withoutDot.startsWith('../') || normalized.includes('/../');
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** Find the line that declares a dependency inside a given dependency section. */
|
|
252
|
+
function findDependencyLine(text, section, dependency) {
|
|
253
|
+
const lines = String(text ?? '').split('\n');
|
|
254
|
+
const sectionRe = new RegExp(`"${escapeRegExp(section)}"\\s*:\\s*\\{`);
|
|
255
|
+
let start = -1;
|
|
256
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
257
|
+
if (sectionRe.test(lines[i])) {
|
|
258
|
+
start = i;
|
|
259
|
+
break;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
if (start < 0) return null;
|
|
263
|
+
const entryRe = new RegExp(`^\\s*"${escapeRegExp(dependency)}"\\s*:`);
|
|
264
|
+
for (let i = start + 1; i < lines.length; i += 1) {
|
|
265
|
+
if (/^\s*}\s*,?\s*$/.test(lines[i])) break;
|
|
266
|
+
if (entryRe.test(lines[i])) return i + 1;
|
|
267
|
+
}
|
|
268
|
+
return null;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** Loose version specifiers that are not reproducible. */
|
|
272
|
+
function isLooseDependencySpec(spec) {
|
|
273
|
+
const value = String(spec).trim();
|
|
274
|
+
if (!value) return true;
|
|
275
|
+
if (/^(?:\^|~|\*|latest$|>=|<=|>|<|=)/i.test(value)) return true;
|
|
276
|
+
if (/^(?:file:|link:|git\+|git:|github:|gitlab:|bitbucket:|workspace:)/i.test(value)) return true;
|
|
277
|
+
if (/^\d+\.(?:x|\*)/i.test(value)) return true;
|
|
278
|
+
if (value.includes('||')) return true;
|
|
279
|
+
return false;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** Walk the dsh manifest subtree for dangerous privilege declarations. */
|
|
283
|
+
function findDangerousDshDeclaration(dsh) {
|
|
284
|
+
if (!dsh || typeof dsh !== 'object') return null;
|
|
285
|
+
const stack = [{ value: dsh, path: 'dsh' }];
|
|
286
|
+
while (stack.length > 0) {
|
|
287
|
+
const { value, path } = stack.pop();
|
|
288
|
+
if (typeof value === 'string') {
|
|
289
|
+
if (DANGEROUS_VALUE_RE.test(value)) return { path, value };
|
|
290
|
+
continue;
|
|
291
|
+
}
|
|
292
|
+
if (Array.isArray(value)) {
|
|
293
|
+
value.forEach((entry, index) => stack.push({ value: entry, path: `${path}[${index}]` }));
|
|
294
|
+
continue;
|
|
295
|
+
}
|
|
296
|
+
if (value && typeof value === 'object') {
|
|
297
|
+
for (const [key, child] of Object.entries(value)) {
|
|
298
|
+
const childPath = `${path}.${key}`;
|
|
299
|
+
if (/^(?:approval|sandbox)$/i.test(key) && child === false) return { path: childPath, value: 'false' };
|
|
300
|
+
if (/^(?:approval|sandbox|permission[-_]?presets?)$/i.test(key) && typeof child === 'string'
|
|
301
|
+
&& /^(?:never|off|false|none|disabled|danger-full-access)$/i.test(child.trim())) {
|
|
302
|
+
return { path: childPath, value: child };
|
|
303
|
+
}
|
|
304
|
+
stack.push({ value: child, path: childPath });
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
return null;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* Audit a package.json manifest (parsed as data, never executed).
|
|
313
|
+
*
|
|
314
|
+
* @param {{ file: string, text: string, patchExists: boolean }} context
|
|
315
|
+
* @returns {RawFinding[]}
|
|
316
|
+
*/
|
|
317
|
+
export function scanPackageManifest(context) {
|
|
318
|
+
const { file, text, patchExists } = context ?? {};
|
|
319
|
+
const raw = [];
|
|
320
|
+
const push = (ruleId, line, evidence, extra = {}) => {
|
|
321
|
+
raw.push({
|
|
322
|
+
ruleId,
|
|
323
|
+
file,
|
|
324
|
+
line: Number.isInteger(line) && line > 0 ? line : null,
|
|
325
|
+
evidence: evidence || lineTextAt(text, line),
|
|
326
|
+
...extra,
|
|
327
|
+
});
|
|
328
|
+
};
|
|
329
|
+
|
|
330
|
+
let pkg;
|
|
331
|
+
try {
|
|
332
|
+
pkg = JSON.parse(String(text ?? ''));
|
|
333
|
+
} catch (error) {
|
|
334
|
+
push('VG-SUP-09', null, `package.json 解析失败:${truncateEvidence(error?.message ?? error, 160)}`, {
|
|
335
|
+
vars: { reason: truncateEvidence(error?.message ?? 'JSON 解析错误', 120) },
|
|
336
|
+
});
|
|
337
|
+
return raw;
|
|
338
|
+
}
|
|
339
|
+
if (!pkg || typeof pkg !== 'object' || Array.isArray(pkg)) {
|
|
340
|
+
push('VG-SUP-09', null, 'package.json 顶层不是对象', { vars: { reason: '顶层不是对象' } });
|
|
341
|
+
return raw;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
if (!pkg.name || !pkg.version) {
|
|
345
|
+
const missing = [!pkg.name ? 'name' : null, !pkg.version ? 'version' : null].filter(Boolean);
|
|
346
|
+
// Point at the *missing* field's line when it exists, and never quote an
|
|
347
|
+
// unrelated line as evidence for "缺少 name/version".
|
|
348
|
+
const line = findLineNumber(text, new RegExp(`"${missing[0]}"\\s*:`));
|
|
349
|
+
push('VG-SUP-07', line, lineTextAt(text, line) || `package.json 缺少 ${missing.join(' 与 ')}`, {
|
|
350
|
+
vars: { fields: missing.join('、') },
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
const scripts = pkg.scripts && typeof pkg.scripts === 'object' && !Array.isArray(pkg.scripts) ? pkg.scripts : {};
|
|
355
|
+
for (const [name, command] of Object.entries(scripts)) {
|
|
356
|
+
if (typeof command !== 'string') continue;
|
|
357
|
+
const line = findLineNumber(text, new RegExp(`"${escapeRegExp(name)}"\\s*:`));
|
|
358
|
+
if (LIFECYCLE_SCRIPTS.has(name)) {
|
|
359
|
+
const evidence = lineTextAt(text, line) || `"${name}": "${truncateEvidence(command, 180)}"`;
|
|
360
|
+
if (RISKY_SCRIPT_RE.test(command)) {
|
|
361
|
+
push('VG-SUP-01', line, evidence, { vars: { name } });
|
|
362
|
+
} else {
|
|
363
|
+
push('VG-SUP-02', line, evidence, { vars: { name } });
|
|
364
|
+
}
|
|
365
|
+
continue;
|
|
366
|
+
}
|
|
367
|
+
if (!SAFE_SCRIPT_RE.test(name)) {
|
|
368
|
+
push('VG-SUP-08', line, lineTextAt(text, line), { vars: { name, cmd: truncateEvidence(command, 120) } });
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
for (const section of ['dependencies', 'devDependencies', 'optionalDependencies']) {
|
|
373
|
+
const deps = pkg[section];
|
|
374
|
+
if (!deps || typeof deps !== 'object' || Array.isArray(deps)) continue;
|
|
375
|
+
for (const [dependency, spec] of Object.entries(deps)) {
|
|
376
|
+
if (typeof spec !== 'string') continue;
|
|
377
|
+
const line = findDependencyLine(text, section, dependency);
|
|
378
|
+
const evidence = lineTextAt(text, line) || `"${dependency}": "${spec}"`;
|
|
379
|
+
if (/^http:\/\//i.test(spec)) {
|
|
380
|
+
push('VG-SUP-04', line, evidence, { vars: { name: dependency, spec } });
|
|
381
|
+
} else if (/^https:\/\//i.test(spec) || isLooseDependencySpec(spec)) {
|
|
382
|
+
push('VG-SUP-03', line, evidence, { vars: { name: dependency, spec } });
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
const bundlePatch = pkg.dsh && typeof pkg.dsh === 'object' && pkg.dsh.bundle && typeof pkg.dsh.bundle === 'object'
|
|
388
|
+
? pkg.dsh.bundle.patch
|
|
389
|
+
: undefined;
|
|
390
|
+
const dshLine = findLineNumber(text, /"dsh"\s*:/);
|
|
391
|
+
const patchLine = findLineNumber(text, /"patch"\s*:/) ?? dshLine;
|
|
392
|
+
|
|
393
|
+
if (patchExists) {
|
|
394
|
+
if (!pkg.dsh) {
|
|
395
|
+
push('VG-SUP-06', dshLine, lineTextAt(text, dshLine) || 'package.json 未声明 dsh 字段', {});
|
|
396
|
+
} else if (!declaresPatch(bundlePatch)) {
|
|
397
|
+
// `dsh.bundle.patch` is the path dsh actually loads (string or array);
|
|
398
|
+
// requiring an `exports` entry as well was a false positive.
|
|
399
|
+
push('VG-SUP-05', dshLine, lineTextAt(text, dshLine) || 'dsh 清单缺少 dsh.bundle.patch', {
|
|
400
|
+
vars: { detail: '缺少 dsh.bundle.patch' },
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
for (const spec of patchSpecs(bundlePatch)) {
|
|
406
|
+
if (!escapesPackage(spec)) continue
|
|
407
|
+
push('VG-DSH-06', patchLine, lineTextAt(text, patchLine) || `"patch": "${spec}"`, {
|
|
408
|
+
vars: { path: spec },
|
|
409
|
+
})
|
|
410
|
+
break
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
const dangerous = findDangerousDshDeclaration(pkg.dsh);
|
|
414
|
+
if (dangerous) {
|
|
415
|
+
const line = findLineNumber(text, DSH_PRIVILEGE_LINE_RE) ?? findLineNumber(text, DANGEROUS_VALUE_RE);
|
|
416
|
+
push('VG-DSH-05', line, lineTextAt(text, line) || dangerous.path, { vars: { detail: dangerous.path } });
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
return raw;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/* ------------------------------------------------------------------------- *
|
|
423
|
+
* JavaScript / TypeScript source analysis
|
|
424
|
+
* ------------------------------------------------------------------------- */
|
|
425
|
+
|
|
426
|
+
/**
|
|
427
|
+
* Rule data is read on every scan, not captured at import: reloading a rule pack
|
|
428
|
+
* (settings save / plugin rebuild) must take effect without a process restart.
|
|
429
|
+
*/
|
|
430
|
+
const egressPatterns = () => getRulePack().audit.egressPatterns;
|
|
431
|
+
const credentialPathPatterns = () => getRulePack().audit.credentialPaths;
|
|
432
|
+
const secretTokenPatterns = () => getRulePack().audit.secretTokens;
|
|
433
|
+
const privilegePatterns = () => getRulePack().audit.privilegePatterns;
|
|
434
|
+
|
|
435
|
+
const URL_RE = /(?:https?|wss?):\/\/[^\s'"`<>()\],;]+/g;
|
|
436
|
+
const SUSPICIOUS_ENDPOINT_RE = /(?:ngrok(?:-free)?\.(?:io|app|dev)|pastebin(?:\.com)?|paste\.ee|transfer\.sh|webhook\.site|requestbin|pipedream\.net|beeceptor\.com|interact\.sh|oast\.(?:pro|fun|me|live|site)|burpcollaborator|discord(?:app)?\.com\/api\/webhooks|api\.telegram\.org\/bot|0x0\.st|file\.io|gofile\.io|termbin\.com|hastebin\.com|ghostbin\.io|anonfiles\.com|sendspace\.com)/i;
|
|
437
|
+
const ALLOWED_HOST_RE = /^(?:localhost|127(?:\.\d{1,3}){3}|0\.0\.0\.0|\[::1\]|::1|(?:[a-z0-9-]+\.)*deepseek\.(?:com|ai|tech))$/i;
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
const SECRET_ASSIGN_RE = /\b(api[_-]?key|apikey|secret|client[_-]?secret|access[_-]?key|secret[_-]?key|private[_-]?key|auth[_-]?token|access[_-]?token|refresh[_-]?token|password|passwd|pwd|token)\b\s*[:=]\s*(['"`])([^'"`\n]{16,})\2/i;
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
const PEM_RE = /-----BEGIN (?:[A-Z0-9 ]+ )?PRIVATE KEY-----/;
|
|
444
|
+
const PLACEHOLDER_RE = /^(?:x{3,}|\*{3,}|\.{3,}|<[^>]*>|\$\{[^}]*\}|your[_-]?|example|sample|dummy|fake|test|placeholder|change[_-]?me|none|null|undefined|todo|redacted|secret|password)$/i;
|
|
445
|
+
|
|
446
|
+
/** Reject obvious placeholder values so documentation snippets don't match. */
|
|
447
|
+
function isPlaceholderSecret(value) {
|
|
448
|
+
const text = String(value).trim();
|
|
449
|
+
if (text.length < 16) return true;
|
|
450
|
+
if (PLACEHOLDER_RE.test(text)) return true;
|
|
451
|
+
if (/^(?:process|import\.meta|globalThis|window|os|env)\b/i.test(text)) return true;
|
|
452
|
+
if (!/[A-Za-z]/.test(text)) return true;
|
|
453
|
+
if (!/[0-9]/.test(text) && !/[A-Z]/.test(text)) return true;
|
|
454
|
+
return false;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/**
|
|
458
|
+
* The canonical example credentials documentation ships with (AWS's
|
|
459
|
+
* `AKIAIOSFODNN7EXAMPLE`, Stripe/GitHub doc tokens, …) are not secrets. Leaving
|
|
460
|
+
* them at `blocker` turns every README and test fixture into a false alarm.
|
|
461
|
+
*/
|
|
462
|
+
const KNOWN_EXAMPLE_SECRETS = new Set([
|
|
463
|
+
'AKIAIOSFODNN7EXAMPLE',
|
|
464
|
+
'AKIAI44QH8DHBEXAMPLE',
|
|
465
|
+
'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
|
|
466
|
+
]);
|
|
467
|
+
|
|
468
|
+
/** @param {string} value */
|
|
469
|
+
function isExampleSecret(value) {
|
|
470
|
+
const text = String(value).trim();
|
|
471
|
+
if (text === '') return true;
|
|
472
|
+
if (KNOWN_EXAMPLE_SECRETS.has(text)) return true;
|
|
473
|
+
return /EXAMPLE|PLACEHOLDER|CHANGEME|REDACTED/i.test(text)
|
|
474
|
+
&& /^(?:AKIA|ASIA|sk-|ghp_|gho_|xox|glpat-)/i.test(text);
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
const CFG_PATH_PATTERNS = [
|
|
478
|
+
{ kind: '.dsh 目录', re: /(?:^|[\s'"`=(])(?:~|\$HOME|%USERPROFILE%|\$\{?HOME\}?)?[\\/]?\.dsh(?![A-Za-z0-9_-])(?:[\\/][^\s'"`)]*)?/ },
|
|
479
|
+
{ kind: 'dsh profiles 目录', re: /(?:^|[\s'"`=(])[\\/]?profiles[\\/][^\s'"`)]*/ },
|
|
480
|
+
{ kind: 'cordis.patch.yml', re: /['"`][^'"`\n]*cordis\.patch\.yml['"`]|\bcordis\.patch\.yml\b/ },
|
|
481
|
+
{ kind: 'settings.json', re: /['"`][^'"`\n]*settings\.json['"`]|\bsettings\.json\b/ },
|
|
482
|
+
{ kind: 'package.json', re: /['"`](?:\.\/)?package\.json['"`]|\bpath\s*\.\s*(?:join|resolve)\([^)\n]*['"]package\.json['"]/ },
|
|
483
|
+
];
|
|
484
|
+
|
|
485
|
+
const WRITE_API_RE = /\b(?:writeFile|writeFileSync|appendFile|appendFileSync|createWriteStream|rename|renameSync|copyFile|copyFileSync|cp|cpSync|unlink|unlinkSync|rm|rmSync|rmdir|rmdirSync|mkdir|mkdirSync|truncate|truncateSync|writeSync)\s*\(|\bfs\s*\.\s*promises\s*\.\s*(?:writeFile|appendFile|rename|rm|mkdir|copyFile|unlink)\s*\(/;
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
const DSH_ENV_WRITE_RE = /process\s*\.\s*env(?:\.\s*([A-Za-z0-9_]+)|\[\s*['"]([A-Za-z0-9_]+)['"]\s*\])\s*=(?!=)/g;
|
|
489
|
+
|
|
490
|
+
const CHILD_PROCESS_IMPORT_RE = /(?:from\s*['"]node:child_process['"]|from\s*['"]child_process['"]|require\s*\(\s*['"](?:node:)?child_process['"]\s*\)|import\s*\(\s*['"](?:node:)?child_process['"]\s*\))/;
|
|
491
|
+
const CHILD_PROCESS_NAMED_CALL_RE = /\b(?:execSync|execFileSync|spawnSync)\s*\(|\bchild_process\s*\.\s*(?:exec|execFile|spawn|fork)\s*\(/;
|
|
492
|
+
// Bare calls only: `/regex/.exec(...)` is not a child_process call. Namespace
|
|
493
|
+
// members such as `cp.exec(...)` are covered by the alias pass below.
|
|
494
|
+
const CHILD_PROCESS_IMPORTED_CALL_RE = /(?<![\w$.])(?:exec|execFile|spawn|fork)\s*\(/;
|
|
495
|
+
const CHILD_PROCESS_MEMBER_RE = /(?:exec|execFile|execSync|spawn|spawnSync|fork)\s*\(/;
|
|
496
|
+
const REMOTE_PIPE_RE = /(?:curl|wget)\b[^\n|]{0,400}\|\s*(?:sudo\s+)?(?:sh|bash|zsh|dash|ksh|fish|iex|Invoke-Expression|powershell|pwsh|cmd(?:\.exe)?)\b/i;
|
|
497
|
+
const REMOTE_PIPE_PS_RE = /(?:iwr|irm|Invoke-WebRequest|Invoke-RestMethod)\b[^\n|]{0,400}\|\s*(?:iex|Invoke-Expression|powershell|pwsh|cmd(?:\.exe)?|sh|bash)\b/i;
|
|
498
|
+
const ENCODED_PS_RE = /\bpowershell(?:\.exe)?\s+(?:-|--)?(?:enc|encodedcommand)\b/i;
|
|
499
|
+
const DOM_PATTERNS = [
|
|
500
|
+
/\bdocument\s*\.\s*(?:body|head|documentElement)\s*\.\s*(?:innerHTML|outerHTML|appendChild|insertAdjacentHTML|replaceChildren|append)\b/,
|
|
501
|
+
/\binnerHTML\s*=/,
|
|
502
|
+
/\bouterHTML\s*=/,
|
|
503
|
+
/\binsertAdjacentHTML\s*\(/,
|
|
504
|
+
/\bdocument\s*\.\s*write\s*\(/,
|
|
505
|
+
/\bcreateElement\s*\(\s*['"](?:iframe|script)['"]/,
|
|
506
|
+
/\bsrcdoc\s*=/,
|
|
507
|
+
];
|
|
508
|
+
const STORAGE_RE = /\b(?:localStorage|sessionStorage)\b|\bindexedDB\b|document\s*\.\s*cookie/i;
|
|
509
|
+
|
|
510
|
+
/** Extract a hostname from a URL/host literal (lower-case, port removed). */
|
|
511
|
+
function hostFromUrl(url) {
|
|
512
|
+
const text = String(url).trim();
|
|
513
|
+
const withoutScheme = text.replace(/^(?:https?|wss?):\/\//i, '');
|
|
514
|
+
const authority = withoutScheme.split(/[/?#]/, 1)[0] ?? '';
|
|
515
|
+
const withoutUser = authority.includes('@') ? authority.slice(authority.lastIndexOf('@') + 1) : authority;
|
|
516
|
+
if (!withoutUser) return '';
|
|
517
|
+
if (withoutUser.startsWith('[')) return withoutUser.slice(0, withoutUser.indexOf(']') + 1).toLowerCase();
|
|
518
|
+
return withoutUser.replace(/:\d+$/, '').toLowerCase();
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/** True for a bare IPv4 host that is not loopback/unspecified (i.e. suspicious). */
|
|
522
|
+
function isRawIp(host) {
|
|
523
|
+
const text = String(host ?? '');
|
|
524
|
+
if (!/^\d{1,3}(?:\.\d{1,3}){3}$/.test(text)) return false;
|
|
525
|
+
if (/^(?:127\.|0\.)/.test(text)) return false;
|
|
526
|
+
return true;
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
/** Trim trailing punctuation that regexes often capture from prose. */
|
|
530
|
+
function trimUrl(url) {
|
|
531
|
+
return String(url).replace(/[.,;:!?]+$/, '');
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/** True when a URL host is explicitly trusted for this scan. */
|
|
535
|
+
function isAllowedHost(host) {
|
|
536
|
+
return ALLOWED_HOST_RE.test(String(host ?? ''));
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/** Find the URL/host literal nearest to a given line (deterministic, <= 40 lines). */
|
|
540
|
+
function nearestUrlRef(urlRefs, line) {
|
|
541
|
+
let best = null;
|
|
542
|
+
let bestDistance = Number.POSITIVE_INFINITY;
|
|
543
|
+
for (const ref of urlRefs) {
|
|
544
|
+
const distance = Math.abs(ref.line - line);
|
|
545
|
+
if (distance < bestDistance || (distance === bestDistance && best && ref.line < best.line)) {
|
|
546
|
+
best = ref;
|
|
547
|
+
bestDistance = distance;
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
return bestDistance <= 40 ? best : null;
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
/** First non-allowlisted host in the file, for escalation narratives. */
|
|
554
|
+
function firstExternalHost(urlRefs) {
|
|
555
|
+
const ref = urlRefs.find((entry) => entry.host && !isAllowedHost(entry.host));
|
|
556
|
+
return ref ? ref.host : '';
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/** True when the surrounding literal lines contain a relative URL (fetch('/api')). */
|
|
560
|
+
function hasNearbyRelativeUrl(literalLines, line) {
|
|
561
|
+
const start = Math.max(0, line - 4);
|
|
562
|
+
const end = Math.min(literalLines.length - 1, line + 2);
|
|
563
|
+
for (let i = start; i <= end; i += 1) {
|
|
564
|
+
if (/['"`]\/(?!\/)/.test(literalLines[i] ?? '')) return true;
|
|
565
|
+
}
|
|
566
|
+
return false;
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
/** Decode a base64 literal if it looks like readable payload text. */
|
|
570
|
+
function decodeBase64Text(raw) {
|
|
571
|
+
try {
|
|
572
|
+
const compact = String(raw).replace(/\s+/g, '');
|
|
573
|
+
if (compact.length < 16 || compact.length % 4 !== 0) return '';
|
|
574
|
+
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(compact)) return '';
|
|
575
|
+
const buffer = Buffer.from(compact, 'base64');
|
|
576
|
+
if (buffer.length < 8) return '';
|
|
577
|
+
const text = buffer.toString('utf8');
|
|
578
|
+
const printable = text.replace(/[^\x20-\x7E\u4e00-\u9fff]/g, '');
|
|
579
|
+
return printable.length >= text.length * 0.8 ? text : '';
|
|
580
|
+
} catch {
|
|
581
|
+
return '';
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/** Decode a run of `\xNN` escapes. */
|
|
586
|
+
function decodeHexEscapes(raw) {
|
|
587
|
+
try {
|
|
588
|
+
const bytes = [];
|
|
589
|
+
for (const match of String(raw).matchAll(/\\x([0-9a-fA-F]{2})/g)) bytes.push(parseInt(match[1], 16));
|
|
590
|
+
return bytes.length >= 4 ? Buffer.from(bytes).toString('utf8') : '';
|
|
591
|
+
} catch {
|
|
592
|
+
return '';
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/** Judge a decoded payload: suspicious API, network URL, or `| sh`. */
|
|
597
|
+
function classifyDecodedPayload(decoded) {
|
|
598
|
+
const text = String(decoded).replace(/\s+/g, ' ').trim();
|
|
599
|
+
const suspicious = /\b(?:eval|exec|execSync|spawn|spawnSync|child_process|Invoke-Expression|iex|FromBase64String)\b/i.test(text);
|
|
600
|
+
const network = /https?:\/\//i.test(text) || /\b(?:curl|wget|Invoke-WebRequest|Invoke-RestMethod|iwr|irm)\b/i.test(text);
|
|
601
|
+
const pipeShell = /\|\s*(?:sh|bash|powershell|pwsh)\b/i.test(text);
|
|
602
|
+
if (!suspicious && !network && !pipeShell) return null;
|
|
603
|
+
return {
|
|
604
|
+
severe: (network && (suspicious || pipeShell)),
|
|
605
|
+
detail: truncateEvidence(text, 70),
|
|
606
|
+
};
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
/** True when a write API is used on this line or one of the two previous lines. */
|
|
610
|
+
function isWriteContext(codeLines, index) {
|
|
611
|
+
for (let i = Math.max(0, index - 2); i <= index; i += 1) {
|
|
612
|
+
if (WRITE_API_RE.test(codeLines[i] ?? '')) return true;
|
|
613
|
+
}
|
|
614
|
+
return false;
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/** Severity for an AST hit, driven by `scan.ast.level` (low/medium/high). */
|
|
618
|
+
function astSeverity(level) {
|
|
619
|
+
if (level === 'high') return 'blocker';
|
|
620
|
+
if (level === 'low') return 'notice';
|
|
621
|
+
return 'review';
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
/** Effective severity of a raw finding (catalog fallback before materialize). */
|
|
625
|
+
function effectiveSeverity(finding) {
|
|
626
|
+
if (typeof finding.severity === 'string') return finding.severity;
|
|
627
|
+
const catalog = RULE_BY_ID.get(finding.ruleId);
|
|
628
|
+
return catalog ? catalog.severity : 'review';
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
const SEVERITY_RANK = { info: 1, notice: 2, review: 3, blocker: 4 };
|
|
632
|
+
|
|
633
|
+
/**
|
|
634
|
+
* Audit a JS/TS source file through comment/string-aware masks.
|
|
635
|
+
*
|
|
636
|
+
* @param {{ file: string, text: string, isClient?: boolean, ast?: { enabled?: boolean, level?: string } }} context
|
|
637
|
+
* @returns {RawFinding[]}
|
|
638
|
+
*/
|
|
639
|
+
export function scanCodeFile(context) {
|
|
640
|
+
const { file, text, isClient = false } = context ?? {};
|
|
641
|
+
if (typeof text !== 'string') return [];
|
|
642
|
+
const lex = maskSource(text);
|
|
643
|
+
const { original, code, literals } = lex.lines;
|
|
644
|
+
const findings = [];
|
|
645
|
+
const seen = new Set();
|
|
646
|
+
const ruleHits = new Map();
|
|
647
|
+
const suppressed = new Map();
|
|
648
|
+
const MAX_FINDINGS_PER_RULE = 40;
|
|
649
|
+
const deadlineAt = Number(context?.deadlineAt) > 0 ? Number(context.deadlineAt) : 0;
|
|
650
|
+
|
|
651
|
+
const add = (ruleId, line, extra = {}) => {
|
|
652
|
+
if (deadlineAt > 0 && Date.now() > deadlineAt) {
|
|
653
|
+
const error = new Error('static scan deadline reached');
|
|
654
|
+
error.code = 'VG_SCAN_DEADLINE';
|
|
655
|
+
error.findings = findings;
|
|
656
|
+
throw error;
|
|
657
|
+
}
|
|
658
|
+
if ((ruleHits.get(ruleId) ?? 0) >= MAX_FINDINGS_PER_RULE) {
|
|
659
|
+
suppressed.set(ruleId, (suppressed.get(ruleId) ?? 0) + 1);
|
|
660
|
+
return;
|
|
661
|
+
}
|
|
662
|
+
ruleHits.set(ruleId, (ruleHits.get(ruleId) ?? 0) + 1);
|
|
663
|
+
const lineNo = Number.isInteger(line) && line > 0 ? line : null;
|
|
664
|
+
const key = `${ruleId}|${lineNo}`;
|
|
665
|
+
if (seen.has(key)) return;
|
|
666
|
+
seen.add(key);
|
|
667
|
+
const finding = {
|
|
668
|
+
ruleId,
|
|
669
|
+
file,
|
|
670
|
+
line: lineNo,
|
|
671
|
+
evidence: extra.evidence ?? (lineNo ? lineTextAt(text, lineNo) : ''),
|
|
672
|
+
};
|
|
673
|
+
if (extra.vars) finding.vars = extra.vars;
|
|
674
|
+
if (extra.confidence) finding.confidence = extra.confidence;
|
|
675
|
+
if (extra.severity) finding.severity = extra.severity;
|
|
676
|
+
if (extra.extraMeans) finding.extraMeans = extra.extraMeans;
|
|
677
|
+
findings.push(finding);
|
|
678
|
+
};
|
|
679
|
+
|
|
680
|
+
// Pre-pass: URL/host literals and network egress call sites.
|
|
681
|
+
const urlRefs = [];
|
|
682
|
+
const egressByLine = new Map();
|
|
683
|
+
for (let i = 0; i < literals.length; i += 1) {
|
|
684
|
+
const literalLine = literals[i] ?? '';
|
|
685
|
+
for (const match of literalLine.matchAll(URL_RE)) {
|
|
686
|
+
const url = trimUrl(match[0]);
|
|
687
|
+
const host = hostFromUrl(url);
|
|
688
|
+
if (!host) continue;
|
|
689
|
+
urlRefs.push({
|
|
690
|
+
line: i + 1,
|
|
691
|
+
url,
|
|
692
|
+
host,
|
|
693
|
+
suspicious: SUSPICIOUS_ENDPOINT_RE.test(host),
|
|
694
|
+
rawIp: isRawIp(host),
|
|
695
|
+
});
|
|
696
|
+
}
|
|
697
|
+
const hostMatch = /(?:hostname|host)\s*:\s*(['"])([^'"]+)\1/.exec(literalLine);
|
|
698
|
+
if (hostMatch) {
|
|
699
|
+
const host = hostMatch[2].trim().toLowerCase();
|
|
700
|
+
urlRefs.push({
|
|
701
|
+
line: i + 1,
|
|
702
|
+
url: host,
|
|
703
|
+
host,
|
|
704
|
+
suspicious: SUSPICIOUS_ENDPOINT_RE.test(host),
|
|
705
|
+
rawIp: isRawIp(host),
|
|
706
|
+
literalHost: true,
|
|
707
|
+
});
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
for (let i = 0; i < code.length; i += 1) {
|
|
711
|
+
const codeLine = code[i] ?? '';
|
|
712
|
+
for (const pattern of egressPatterns()) {
|
|
713
|
+
if (!pattern.re.test(codeLine)) continue;
|
|
714
|
+
// Same-origin relative requests (`fetch('/api/...')`) are not egress.
|
|
715
|
+
if (isClient && hasNearbyRelativeUrl(literals, i + 1)) break;
|
|
716
|
+
egressByLine.set(i + 1, pattern.api);
|
|
717
|
+
break;
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
// Destination-specific findings (reported at the URL literal line).
|
|
722
|
+
for (const ref of urlRefs) {
|
|
723
|
+
if (ref.suspicious) {
|
|
724
|
+
add('VG-NET-02', ref.line, { vars: { host: ref.host }, confidence: 'confirmed' });
|
|
725
|
+
} else if (ref.rawIp) {
|
|
726
|
+
add('VG-NET-03', ref.line, { vars: { host: ref.host }, confidence: 'confirmed' });
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
const childProcessImported = literals.some((line) => CHILD_PROCESS_IMPORT_RE.test(line));
|
|
731
|
+
// Locally bound names of child_process APIs (`spawn as launch`, `const cp = require(...)`).
|
|
732
|
+
const childProcessNames = new Set();
|
|
733
|
+
for (const line of literals) {
|
|
734
|
+
if (!CHILD_PROCESS_IMPORT_RE.test(line)) continue;
|
|
735
|
+
const named = /import\s*\{([^}]+)\}\s*from\s*['"](?:node:)?child_process['"]/.exec(line);
|
|
736
|
+
if (named) {
|
|
737
|
+
for (const part of named[1].split(',')) {
|
|
738
|
+
const [original, alias] = part.trim().split(/\s+as\s+/);
|
|
739
|
+
const bound = (alias ?? original ?? '').trim();
|
|
740
|
+
if (bound) childProcessNames.add(bound);
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
const required = /(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*require\s*\(\s*['"](?:node:)?child_process['"]\s*\)/.exec(line);
|
|
744
|
+
if (required) childProcessNames.add(required[1]);
|
|
745
|
+
}
|
|
746
|
+
const aliasedChildProcessCall = codeLine => {
|
|
747
|
+
for (const name of childProcessNames) {
|
|
748
|
+
// Exclude `.exec(` (a regex method) from the alias match as well.
|
|
749
|
+
if (new RegExp(`(?<![\\w$.])${escapeRegExp(name)}\\s*\\(`).test(codeLine)) return name;
|
|
750
|
+
// Namespace binding: `const cp = require('child_process'); cp.exec(...)`.
|
|
751
|
+
if (new RegExp(`\\b${escapeRegExp(name)}\\s*\\.\\s*(?:exec|execFile|execSync|spawn|spawnSync|fork)\\s*\\(`).test(codeLine)) return name;
|
|
752
|
+
}
|
|
753
|
+
return null;
|
|
754
|
+
};
|
|
755
|
+
|
|
756
|
+
for (let i = 0; i < original.length; i += 1) {
|
|
757
|
+
const lineNo = i + 1;
|
|
758
|
+
const codeLine = code[i] ?? '';
|
|
759
|
+
const literalLine = literals[i] ?? '';
|
|
760
|
+
|
|
761
|
+
// ---- dynamic code execution -----------------------------------------
|
|
762
|
+
if (/(?<![\w$.])eval\s*\(|\bnew\s+Function\s*\(|\bFunction\s*\(\s*['"`]|\.\s*constructor\s*\(\s*['"`]|\(\s*0\s*,\s*eval\s*\)|(?:globalThis|window|self)\s*\[\s*['"`]eval['"`]\s*\]/.test(codeLine)) {
|
|
763
|
+
add('VG-DYN-01', lineNo, { vars: { detail: 'eval/new Function' }, confidence: 'heuristic' });
|
|
764
|
+
}
|
|
765
|
+
if (/\bInvoke-Expression\b|\biex\s+[^|\s]/i.test(literalLine)) {
|
|
766
|
+
add('VG-DYN-01', lineNo, { vars: { detail: 'PowerShell Invoke-Expression / iex' }, confidence: 'heuristic' });
|
|
767
|
+
}
|
|
768
|
+
if (childProcessImported && (CHILD_PROCESS_IMPORTED_CALL_RE.test(codeLine) || aliasedChildProcessCall(codeLine))) {
|
|
769
|
+
add('VG-DYN-02', lineNo, { vars: { api: 'child_process 调用' }, confidence: 'heuristic' });
|
|
770
|
+
} else if (CHILD_PROCESS_NAMED_CALL_RE.test(codeLine)) {
|
|
771
|
+
add('VG-DYN-02', lineNo, { vars: { api: 'child_process 调用' }, confidence: 'heuristic' });
|
|
772
|
+
}
|
|
773
|
+
if (REMOTE_PIPE_RE.test(literalLine) || REMOTE_PIPE_PS_RE.test(literalLine)) {
|
|
774
|
+
add('VG-DYN-03', lineNo, { vars: { detail: '下载并通过 shell/PowerShell 管道执行' }, confidence: 'confirmed' });
|
|
775
|
+
} else if (ENCODED_PS_RE.test(literalLine)) {
|
|
776
|
+
add('VG-DYN-03', lineNo, { vars: { detail: 'PowerShell -EncodedCommand' }, confidence: 'confirmed' });
|
|
777
|
+
}
|
|
778
|
+
if (/\bimport\s*\(/.test(codeLine)) {
|
|
779
|
+
const importTarget = /import\s*\(\s*(['"])([^'"]+)\1/.exec(literalLine);
|
|
780
|
+
const target = importTarget ? importTarget[2] : '';
|
|
781
|
+
const remoteImport = /^(?:https?|wss?):\/\//i.test(target);
|
|
782
|
+
const localImport = target.startsWith('node:') || target.startsWith('.') || target.startsWith('/');
|
|
783
|
+
add('VG-DYN-04', lineNo, {
|
|
784
|
+
vars: {
|
|
785
|
+
detail: remoteImport
|
|
786
|
+
? `从远程 URL 动态导入模块(${truncateEvidence(target, 80)})`
|
|
787
|
+
: (target ? `动态导入模块 ${truncateEvidence(target, 80)}` : 'import(...) 动态加载'),
|
|
788
|
+
},
|
|
789
|
+
confidence: 'heuristic',
|
|
790
|
+
// A literal specifier (package name or relative path) is normal lazy
|
|
791
|
+
// loading; only a computed/remote target is worth a review.
|
|
792
|
+
severity: remoteImport ? 'blocker' : (importTarget ? 'notice' : undefined),
|
|
793
|
+
});
|
|
794
|
+
}
|
|
795
|
+
if (/\bvm\s*\.\s*(?:runIn\w*|Script|compileFunction|createContext)\b/.test(codeLine)) {
|
|
796
|
+
add('VG-DYN-05', lineNo, { vars: { detail: 'vm.runIn*/vm.Script' }, confidence: 'heuristic' });
|
|
797
|
+
}
|
|
798
|
+
// ---- encoded payloads (base64 / hex literals) ------------------------
|
|
799
|
+
// Decoding a literal is deterministic; general dataflow between variables is
|
|
800
|
+
// out of scope (documented limitation).
|
|
801
|
+
let encodedAdded = false;
|
|
802
|
+
for (const match of literalLine.matchAll(/(?:Buffer\.from|atob|FromBase64String)\s*\(\s*['"`]([A-Za-z0-9+/=\s]{16,})['"`]/gi)) {
|
|
803
|
+
const decoded = decodeBase64Text(match[1]);
|
|
804
|
+
if (decoded === '') continue;
|
|
805
|
+
const report = classifyDecodedPayload(decoded);
|
|
806
|
+
if (!report) continue;
|
|
807
|
+
add('VG-DYN-06', lineNo, {
|
|
808
|
+
vars: { detail: report.detail },
|
|
809
|
+
confidence: 'heuristic',
|
|
810
|
+
severity: report.severe ? 'blocker' : undefined,
|
|
811
|
+
});
|
|
812
|
+
encodedAdded = true;
|
|
813
|
+
break;
|
|
814
|
+
}
|
|
815
|
+
if (!encodedAdded) {
|
|
816
|
+
const hexRun = /(?:\\x[0-9a-fA-F]{2}){4,}/.exec(literalLine);
|
|
817
|
+
if (hexRun) {
|
|
818
|
+
const decoded = decodeHexEscapes(hexRun[0]);
|
|
819
|
+
const report = decoded === '' ? null : classifyDecodedPayload(decoded);
|
|
820
|
+
if (report) add('VG-DYN-06', lineNo, { vars: { detail: report.detail }, confidence: 'heuristic' });
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
// ---- credential access ----------------------------------------------
|
|
825
|
+
if (PEM_RE.test(literalLine)) {
|
|
826
|
+
add('VG-CRED-02', lineNo, { confidence: 'confirmed' });
|
|
827
|
+
}
|
|
828
|
+
const assignMatch = SECRET_ASSIGN_RE.exec(literalLine);
|
|
829
|
+
if (assignMatch && !isPlaceholderSecret(assignMatch[3]) && !isExampleSecret(assignMatch[3])) {
|
|
830
|
+
add('VG-CRED-01', lineNo, {
|
|
831
|
+
vars: { secretKind: assignMatch[1] },
|
|
832
|
+
confidence: 'confirmed',
|
|
833
|
+
});
|
|
834
|
+
}
|
|
835
|
+
for (const tokenPattern of secretTokenPatterns()) {
|
|
836
|
+
const tokenMatch = tokenPattern.re.exec(literalLine);
|
|
837
|
+
if (tokenMatch && !isExampleSecret(tokenMatch[0])) {
|
|
838
|
+
add('VG-CRED-01', lineNo, { vars: { secretKind: tokenPattern.kind }, confidence: 'confirmed' });
|
|
839
|
+
break;
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
for (const pattern of credentialPathPatterns()) {
|
|
843
|
+
const match = pattern.re.exec(literalLine);
|
|
844
|
+
if (match) {
|
|
845
|
+
add('VG-CRED-03', lineNo, { vars: { path: truncateEvidence(match[0], 80) }, confidence: 'heuristic' });
|
|
846
|
+
break;
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
const envReadRe = /process\s*\.\s*env(?:\.\s*([A-Za-z0-9_]+)|\[\s*['"]([A-Za-z0-9_]+)['"]\s*\])/g;
|
|
850
|
+
for (const match of literalLine.matchAll(envReadRe)) {
|
|
851
|
+
const name = match[1] ?? match[2] ?? '';
|
|
852
|
+
// `GITHUB_TOKEN`, `AWS_SECRET_ACCESS_KEY` and friends: a leading word
|
|
853
|
+
// boundary never matches after `_`, so match at `^` or a separator.
|
|
854
|
+
if (/(?:^|_)(?:TOKEN|SECRET|KEY|PASSWORD|PASSWD|CREDENTIAL|AUTH)(?:$|_)/i.test(name)
|
|
855
|
+
&& !/\bPUBLIC\b/i.test(name)) {
|
|
856
|
+
add('VG-CRED-04', lineNo, { vars: { name }, confidence: 'heuristic' });
|
|
857
|
+
break;
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
// `const { GITHUB_TOKEN } = process.env` bypasses the dotted form above.
|
|
861
|
+
const destructuredEnv = /(?:const|let|var)\s*\{([^}]+)\}\s*=\s*process\s*\.\s*env/.exec(literalLine);
|
|
862
|
+
if (destructuredEnv) {
|
|
863
|
+
for (const part of destructuredEnv[1].split(',')) {
|
|
864
|
+
const name = part.split(':')[0].trim().replace(/^['"]|['"]$/g, '');
|
|
865
|
+
if (name === '' || /\bPUBLIC\b/i.test(name)) continue;
|
|
866
|
+
if (/(?:^|_)(?:TOKEN|SECRET|KEY|PASSWORD|PASSWD|CREDENTIAL|AUTH)(?:$|_)/i.test(name)) {
|
|
867
|
+
add('VG-CRED-04', lineNo, { vars: { name }, confidence: 'heuristic' });
|
|
868
|
+
break;
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
// ---- network egress --------------------------------------------------
|
|
874
|
+
const api = egressByLine.get(lineNo);
|
|
875
|
+
if (api) {
|
|
876
|
+
if (isClient) {
|
|
877
|
+
add('VG-DSH-01', lineNo, { vars: { api }, confidence: 'heuristic' });
|
|
878
|
+
}
|
|
879
|
+
const nearest = nearestUrlRef(urlRefs, lineNo);
|
|
880
|
+
if (nearest) {
|
|
881
|
+
if (!nearest.suspicious && !nearest.rawIp && !isAllowedHost(nearest.host)) {
|
|
882
|
+
add('VG-NET-01', lineNo, {
|
|
883
|
+
vars: { host: nearest.host, api },
|
|
884
|
+
confidence: 'heuristic',
|
|
885
|
+
});
|
|
886
|
+
}
|
|
887
|
+
} else if (!isClient && !hasNearbyRelativeUrl(literals, lineNo)) {
|
|
888
|
+
add('VG-NET-04', lineNo, { vars: { api }, confidence: 'heuristic' });
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
// ---- dsh config tampering -------------------------------------------
|
|
893
|
+
for (const pattern of CFG_PATH_PATTERNS) {
|
|
894
|
+
const match = pattern.re.exec(literalLine);
|
|
895
|
+
if (!match) continue;
|
|
896
|
+
const detail = truncateEvidence(match[0], 70);
|
|
897
|
+
const vars = { path: detail && detail !== pattern.kind ? `${pattern.kind}:${detail}` : pattern.kind };
|
|
898
|
+
const hostConfig = pattern.kind === '.dsh 目录'
|
|
899
|
+
|| pattern.kind === 'dsh profiles 目录'
|
|
900
|
+
|| /[\\/]\.dsh\b|[\\/]profiles[\\/]/i.test(detail);
|
|
901
|
+
if (isWriteContext(code, i)) {
|
|
902
|
+
// Only dsh's own profile/config is a tampering target: a plugin writing
|
|
903
|
+
// its own settings.json or a project's package.json is normal work.
|
|
904
|
+
if (hostConfig) add('VG-CFG-01', lineNo, { vars, confidence: 'heuristic' });
|
|
905
|
+
break;
|
|
906
|
+
}
|
|
907
|
+
// A doc/UI string that merely mentions `~/.dsh` is not a config read.
|
|
908
|
+
const readApi = /\b(?:readFile|readFileSync|readdir|readdirSync|existsSync|createReadStream|require\s*\(|import\s*\()/i.test(codeLine);
|
|
909
|
+
const specificPath = /\.dsh[\\/]|[\\/]profiles[\\/][^\s'"`)]+/i.test(detail);
|
|
910
|
+
if (hostConfig && (readApi || specificPath)) add('VG-CFG-02', lineNo, { vars, confidence: 'heuristic' });
|
|
911
|
+
break;
|
|
912
|
+
}
|
|
913
|
+
for (const pattern of privilegePatterns()) {
|
|
914
|
+
if (pattern.re.test(literalLine)) {
|
|
915
|
+
add('VG-CFG-03', lineNo, { vars: { detail: pattern.detail }, confidence: 'heuristic' });
|
|
916
|
+
break;
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
for (const match of literalLine.matchAll(DSH_ENV_WRITE_RE)) {
|
|
920
|
+
const name = match[1] ?? match[2] ?? '';
|
|
921
|
+
if (name.startsWith('DSH_')) {
|
|
922
|
+
add('VG-CFG-04', lineNo, { vars: { name }, confidence: 'heuristic' });
|
|
923
|
+
break;
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
// ---- client half attack surface -------------------------------------
|
|
928
|
+
if (isClient) {
|
|
929
|
+
const storageMatch = STORAGE_RE.exec(codeLine) ?? STORAGE_RE.exec(literalLine);
|
|
930
|
+
if (storageMatch) {
|
|
931
|
+
add('VG-DSH-02', lineNo, { vars: { detail: storageMatch[0] }, confidence: 'heuristic' });
|
|
932
|
+
}
|
|
933
|
+
let domMatch = null;
|
|
934
|
+
for (const pattern of DOM_PATTERNS) {
|
|
935
|
+
domMatch = pattern.exec(codeLine);
|
|
936
|
+
if (domMatch) break;
|
|
937
|
+
}
|
|
938
|
+
if (!domMatch) domMatch = /<\s*iframe\b/i.exec(literalLine);
|
|
939
|
+
if (domMatch) {
|
|
940
|
+
add('VG-DSH-04', lineNo, { vars: { detail: truncateEvidence(domMatch[0], 80) }, confidence: 'heuristic' });
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
// ---- cross-signal escalation ------------------------------------------
|
|
946
|
+
const hasEgress = egressByLine.size > 0;
|
|
947
|
+
// A client bundle that only talks to same-origin/relative routes has no
|
|
948
|
+
// remote egress; an absolute URL anywhere in the file is what makes the
|
|
949
|
+
// storage+network co-occurrence worth a review.
|
|
950
|
+
const hasRemoteUrlLiteral = literals.some(line => /(?:https?|wss?):\/\//i.test(line));
|
|
951
|
+
const externalHost = firstExternalHost(urlRefs);
|
|
952
|
+
const credentialPathFinding = findings.find((finding) => finding.ruleId === 'VG-CRED-03');
|
|
953
|
+
if (hasEgress && credentialPathFinding) {
|
|
954
|
+
credentialPathFinding.severity = 'blocker';
|
|
955
|
+
credentialPathFinding.vars = { ...(credentialPathFinding.vars ?? {}), host: externalHost || '目标不确定' };
|
|
956
|
+
credentialPathFinding.extraMeans = escalationSentence('credential-network', { host: externalHost });
|
|
957
|
+
}
|
|
958
|
+
const envReadFinding = findings.find((finding) => finding.ruleId === 'VG-CRED-04');
|
|
959
|
+
if (hasEgress && envReadFinding) {
|
|
960
|
+
// Reading a credential-shaped environment variable *and* talking to the
|
|
961
|
+
// network is an exfiltration shape, not a notice.
|
|
962
|
+
envReadFinding.severity = 'blocker';
|
|
963
|
+
envReadFinding.extraMeans = escalationSentence('env-network', { host: externalHost });
|
|
964
|
+
}
|
|
965
|
+
const dynamicFinding = findings.find((finding) => finding.ruleId === 'VG-DYN-01');
|
|
966
|
+
if ((hasEgress || findings.some((finding) => finding.ruleId === 'VG-DYN-03')) && dynamicFinding) {
|
|
967
|
+
dynamicFinding.severity = 'blocker';
|
|
968
|
+
dynamicFinding.extraMeans = escalationSentence('dynamic-network', { host: externalHost });
|
|
969
|
+
}
|
|
970
|
+
const storageFinding = findings.find((finding) => finding.ruleId === 'VG-DSH-02');
|
|
971
|
+
const clientEgress = findings.find((finding) => finding.ruleId === 'VG-DSH-01');
|
|
972
|
+
const clientSameOrigin = isClient && !hasRemoteUrlLiteral;
|
|
973
|
+
if (storageFinding && clientEgress) {
|
|
974
|
+
add('VG-DSH-03', storageFinding.line, {
|
|
975
|
+
vars: {
|
|
976
|
+
detail: `${storageFinding.vars?.detail ?? '存储访问'} + ${clientEgress.vars?.api ?? '网络请求'}`,
|
|
977
|
+
storage: storageFinding.vars?.detail ?? '存储访问',
|
|
978
|
+
egress: clientEgress.vars?.api ?? '网络请求',
|
|
979
|
+
},
|
|
980
|
+
confidence: 'heuristic',
|
|
981
|
+
...(clientSameOrigin ? { severity: 'notice' } : {}),
|
|
982
|
+
extraMeans: clientSameOrigin
|
|
983
|
+
? '该客户端代码里的网络调用都是同源/相对路径,未发现绝对远程地址,因此按提示处理。'
|
|
984
|
+
: escalationSentence('client-exfil', {
|
|
985
|
+
storage: storageFinding.vars?.detail ?? '存储访问',
|
|
986
|
+
egress: clientEgress.vars?.api ?? '网络请求',
|
|
987
|
+
}),
|
|
988
|
+
});
|
|
989
|
+
} else {
|
|
990
|
+
// sendBeacon is an explicit exfiltration primitive on its own.
|
|
991
|
+
const beacon = [...egressByLine.entries()].find(([, value]) => value === 'navigator.sendBeacon');
|
|
992
|
+
if (beacon) add('VG-DSH-03', beacon[0], { vars: { detail: 'navigator.sendBeacon' }, confidence: 'heuristic' });
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
// A pattern that only occurs inside a string literal is data, not behaviour:
|
|
996
|
+
// the scanner must not turn its own rule table or UI copy into blockers. When
|
|
997
|
+
// the masked code line still shows an execution API, the original severity is
|
|
998
|
+
// kept (the literal is then a payload handed to something that runs it).
|
|
999
|
+
const EXECUTION_CONTEXT_RE = /\b(?:spawn|spawnSync|exec|execFile|execSync|fork|eval|Function|require\s*\(|import\s*\(|fetch|axios|WebSocket|child_process|invoke-expression|iwr|iex|start-process|powershell|pwsh|bash)\b|vm\s*\./i;
|
|
1000
|
+
for (const finding of findings) {
|
|
1001
|
+
if (finding.ruleId !== 'VG-DYN-01' && finding.ruleId !== 'VG-DYN-03') continue;
|
|
1002
|
+
const codeLine = Number.isInteger(finding.line) ? (code[finding.line - 1] ?? '') : '';
|
|
1003
|
+
if (codeLine === '' || EXECUTION_CONTEXT_RE.test(codeLine)) continue;
|
|
1004
|
+
finding.severity = 'notice';
|
|
1005
|
+
finding.extraMeans = [finding.extraMeans, '该模式只出现在字符串/文案里,未出现在可执行代码中,因此按提示处理。']
|
|
1006
|
+
.filter(Boolean)
|
|
1007
|
+
.join(' ');
|
|
1008
|
+
}
|
|
1009
|
+
// A privilege keyword that only occurs in a string (rule table, UI copy,
|
|
1010
|
+
// documentation) is not a declared policy — unless the literal is directly
|
|
1011
|
+
// returned/assigned, which is how a plugin declares the mode it wants.
|
|
1012
|
+
// Keep the latter at blocker so a real declaration still gates installs.
|
|
1013
|
+
for (const finding of findings) {
|
|
1014
|
+
if (finding.ruleId !== 'VG-CFG-03') continue;
|
|
1015
|
+
const codeLine = Number.isInteger(finding.line) ? (code[finding.line - 1] ?? '') : '';
|
|
1016
|
+
if (codeLine === '') continue;
|
|
1017
|
+
if (privilegePatterns().some(pattern => pattern.re.test(codeLine))) continue;
|
|
1018
|
+
if (/\breturn\s*['"`]|(?<![=!<>])=(?!=)\s*['"`]/.test(codeLine)) continue;
|
|
1019
|
+
if (finding.severity !== 'notice') {
|
|
1020
|
+
finding.severity = 'notice';
|
|
1021
|
+
finding.extraMeans = [finding.extraMeans, '该关键词只出现在字符串/文案里,未在可执行代码中声明权限,因此按提示处理。']
|
|
1022
|
+
.filter(Boolean)
|
|
1023
|
+
.join(' ');
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
// Same-origin client code: `fetch(FEED_PATH)` and friends are requests to the
|
|
1027
|
+
// host's own authenticated routes, not exfiltration. Only demote when the file
|
|
1028
|
+
// carries no absolute URL literal at all.
|
|
1029
|
+
if (isClient && !hasRemoteUrlLiteral) {
|
|
1030
|
+
for (const finding of findings) {
|
|
1031
|
+
if (finding.ruleId !== 'VG-DSH-01') continue;
|
|
1032
|
+
if (finding.severity === 'notice') continue;
|
|
1033
|
+
finding.severity = 'notice';
|
|
1034
|
+
finding.extraMeans = [finding.extraMeans, '该客户端文件里没有绝对远程地址,网络调用按同源/相对路径处理,因此降为提示。']
|
|
1035
|
+
.filter(Boolean)
|
|
1036
|
+
.join(' ');
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
// Credential *paths* that only appear as literals (a scanner's own rule table,
|
|
1040
|
+
// UI copy, docs) are not credential reads. A read API on the same line keeps
|
|
1041
|
+
// the review; the network cross-signal escalation (`vars.host`) is never undone.
|
|
1042
|
+
const READ_CONTEXT_RE = /\b(?:readFile|readFileSync|readdir|readdirSync|createReadStream|openSync|readSync|get-content|get-item|select-string|type\s+|cat\s+|require\s*\()/i;
|
|
1043
|
+
for (const finding of findings) {
|
|
1044
|
+
if (finding.ruleId !== 'VG-CRED-03') continue;
|
|
1045
|
+
if (finding.vars?.host) continue;
|
|
1046
|
+
const codeLine = Number.isInteger(finding.line) ? (code[finding.line - 1] ?? '') : '';
|
|
1047
|
+
if (codeLine === '' || READ_CONTEXT_RE.test(codeLine)) continue;
|
|
1048
|
+
if (finding.severity === 'notice') continue;
|
|
1049
|
+
finding.severity = 'notice';
|
|
1050
|
+
finding.extraMeans = [finding.extraMeans, '该凭证路径只出现在字符串/规则表/文案里,同一行没有文件读取调用,因此按提示处理。']
|
|
1051
|
+
.filter(Boolean)
|
|
1052
|
+
.join(' ');
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
// ---- AST pass: aliased capability calls (best effort) ------------------- // Line-based rules miss `const cp = require(...); const run = cp.exec; run(x)`.
|
|
1056
|
+
// This pass parses the file once; any parse failure simply skips it.
|
|
1057
|
+
const astOptions = context?.ast && typeof context.ast === 'object' ? context.ast : {};
|
|
1058
|
+
if (astOptions.enabled !== false && /\.(?:[cm]?js)$/i.test(String(file ?? ''))) {
|
|
1059
|
+
const ast = analyzeAliases(text);
|
|
1060
|
+
const severity = astSeverity(astOptions.level);
|
|
1061
|
+
if (!ast.ok) {
|
|
1062
|
+
// Never let an unavailable/degraded AST silently turn into "no findings":
|
|
1063
|
+
// the report must say the alias analysis was skipped.
|
|
1064
|
+
add('VG-SCAN-05', 1, {
|
|
1065
|
+
evidence: String(ast.error ?? 'AST 不可用'),
|
|
1066
|
+
vars: { detail: String(ast.error ?? 'AST 不可用') },
|
|
1067
|
+
confidence: 'notice',
|
|
1068
|
+
severity: 'notice',
|
|
1069
|
+
});
|
|
1070
|
+
} else {
|
|
1071
|
+
for (const call of ast.calls) {
|
|
1072
|
+
if (!Number.isInteger(call.line) || call.line < 1) continue;
|
|
1073
|
+
const evidence = lineTextAt(text, call.line);
|
|
1074
|
+
const ruleId = call.kind === 'child_process'
|
|
1075
|
+
? 'VG-DYN-02'
|
|
1076
|
+
: call.kind === 'fetch'
|
|
1077
|
+
? 'VG-NET-04'
|
|
1078
|
+
: call.kind === 'eval'
|
|
1079
|
+
? 'VG-DYN-01'
|
|
1080
|
+
: null;
|
|
1081
|
+
if (ruleId === null) continue;
|
|
1082
|
+
const existing = findings.find(item => item.ruleId === ruleId && item.line === call.line);
|
|
1083
|
+
if (existing) {
|
|
1084
|
+
// A direct call may already have been caught by a regex rule; the
|
|
1085
|
+
// configured level can only raise severity, never lower it.
|
|
1086
|
+
if (SEVERITY_RANK[severity] > SEVERITY_RANK[effectiveSeverity(existing)]) existing.severity = severity;
|
|
1087
|
+
continue;
|
|
1088
|
+
}
|
|
1089
|
+
const vars = call.kind === 'fetch' || call.kind === 'child_process'
|
|
1090
|
+
? { api: call.name }
|
|
1091
|
+
: { detail: `别名 ${call.name}` };
|
|
1092
|
+
add(ruleId, call.line, {
|
|
1093
|
+
vars,
|
|
1094
|
+
confidence: 'ast',
|
|
1095
|
+
evidence,
|
|
1096
|
+
severity,
|
|
1097
|
+
});
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
for (const [ruleId, count] of suppressed) {
|
|
1103
|
+
findings.push({
|
|
1104
|
+
ruleId,
|
|
1105
|
+
file,
|
|
1106
|
+
line: null,
|
|
1107
|
+
evidence: `另有 ${count} 处同类命中未逐条列出`,
|
|
1108
|
+
vars: { detail: `${count} 处` },
|
|
1109
|
+
});
|
|
1110
|
+
}
|
|
1111
|
+
return findings;
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
/* ------------------------------------------------------------------------- *
|
|
1115
|
+
* cordis.patch.yml analysis (bounded line parser, no YAML dependency)
|
|
1116
|
+
* ------------------------------------------------------------------------- */
|
|
1117
|
+
|
|
1118
|
+
const HIGH_PRIVILEGE_KEY_RE = /^(?:credentials?|credential[-_]?store|sandbox|approval|permission[-_]?presets?|plugin[-_]?manager|config[-_]?editor)$/i;
|
|
1119
|
+
|
|
1120
|
+
/** Remove a YAML comment (`#` outside quotes). */
|
|
1121
|
+
function stripYamlComment(line) {
|
|
1122
|
+
let quote = null;
|
|
1123
|
+
for (let i = 0; i < line.length; i += 1) {
|
|
1124
|
+
const ch = line[i];
|
|
1125
|
+
if (quote) {
|
|
1126
|
+
if (ch === '\\' && quote === '"') i += 1;
|
|
1127
|
+
else if (ch === quote) quote = null;
|
|
1128
|
+
continue;
|
|
1129
|
+
}
|
|
1130
|
+
if (ch === "'" || ch === '"') quote = ch;
|
|
1131
|
+
else if (ch === '#') return line.slice(0, i);
|
|
1132
|
+
}
|
|
1133
|
+
return line;
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
/** Strip optional single/double quotes from a scalar value. */
|
|
1137
|
+
function stripYamlScalar(value) {
|
|
1138
|
+
let text = String(value ?? '').trim();
|
|
1139
|
+
if ((text.startsWith("'") && text.endsWith("'")) || (text.startsWith('"') && text.endsWith('"'))) {
|
|
1140
|
+
text = text.slice(1, -1);
|
|
1141
|
+
}
|
|
1142
|
+
return text;
|
|
1143
|
+
}
|
|
1144
|
+
|
|
1145
|
+
/** Extract `key: value` properties (with indentation and line numbers). */
|
|
1146
|
+
function extractYamlProps(lines, start, end) {
|
|
1147
|
+
const props = [];
|
|
1148
|
+
for (let i = start; i < end; i += 1) {
|
|
1149
|
+
const withoutComment = stripYamlComment(lines[i]);
|
|
1150
|
+
if (!withoutComment.trim()) continue;
|
|
1151
|
+
const match = /^(\s*)(?:-\s+)?([A-Za-z0-9_$@./-]+)\s*:\s*(.*)$/.exec(withoutComment);
|
|
1152
|
+
if (!match) continue;
|
|
1153
|
+
props.push({
|
|
1154
|
+
line: i + 1,
|
|
1155
|
+
indent: match[1].length,
|
|
1156
|
+
key: match[2],
|
|
1157
|
+
value: match[3].trim(),
|
|
1158
|
+
text: lines[i],
|
|
1159
|
+
});
|
|
1160
|
+
}
|
|
1161
|
+
return props;
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
/** Decode YAML escape sequences that could hide a keyword from the matcher. */
|
|
1165
|
+
function decodeYamlEscapes(value) {
|
|
1166
|
+
return String(value ?? '')
|
|
1167
|
+
.replace(/\\u([0-9A-Fa-f]{4})/g, (_match, hex) => String.fromCharCode(parseInt(hex, 16)))
|
|
1168
|
+
.replace(/\\U([0-9A-Fa-f]{8})/g, (_match, hex) => String.fromCodePoint(parseInt(hex, 16)))
|
|
1169
|
+
.replace(/\\x([0-9A-Fa-f]{2})/g, (_match, hex) => String.fromCharCode(parseInt(hex, 16)));
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
/** Find a high-privilege service keyword inside an id/name/string value. */
|
|
1173
|
+
function highPrivilegeKeyword(value) {
|
|
1174
|
+
const decoded = decodeYamlEscapes(value);
|
|
1175
|
+
const match = /(?:^|[\s'"@/._:-])(credentials?|sandbox|approval|permission[-_]?presets?|plugin[-_]?manager|config[-_]?editor)(?:$|[\s'"@/._:-])/i.exec(decoded);
|
|
1176
|
+
return match ? match[1] : null;
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
/** Look for high-privilege config keys below a `config:` property. */
|
|
1180
|
+
function highPrivilegeConfigKey(props, configProp) {
|
|
1181
|
+
if (!configProp) return null;
|
|
1182
|
+
for (const prop of props) {
|
|
1183
|
+
if (prop.line <= configProp.line || prop.indent <= configProp.indent) continue;
|
|
1184
|
+
if (HIGH_PRIVILEGE_KEY_RE.test(prop.key)) {
|
|
1185
|
+
return { line: prop.line, service: prop.key, text: prop.text };
|
|
1186
|
+
}
|
|
1187
|
+
}
|
|
1188
|
+
return null;
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
/**
|
|
1192
|
+
* Bounded line-based parser for `cordis.patch.yml`.
|
|
1193
|
+
*
|
|
1194
|
+
* Extracts top-level rows, `insert` groups, row ids/names, config keys,
|
|
1195
|
+
* `!!js` occurrences and unparseable constructs — with line numbers. It never
|
|
1196
|
+
* evaluates YAML, never evaluates `!!js`, and never throws.
|
|
1197
|
+
*
|
|
1198
|
+
* @param {string} text
|
|
1199
|
+
* @returns {{
|
|
1200
|
+
* ok: boolean,
|
|
1201
|
+
* reason: string|null,
|
|
1202
|
+
* line: number|null,
|
|
1203
|
+
* entries: Array<Record<string, any>>,
|
|
1204
|
+
* jsLines: { line: number, text: string }[],
|
|
1205
|
+
* empty?: boolean
|
|
1206
|
+
* }}
|
|
1207
|
+
*/
|
|
1208
|
+
export function parsePatchYaml(text) {
|
|
1209
|
+
const source = typeof text === 'string' ? text : '';
|
|
1210
|
+
const lines = source.split('\n').map((line) => (line.endsWith('\r') ? line.slice(0, -1) : line));
|
|
1211
|
+
const jsLines = [];
|
|
1212
|
+
let ok = true;
|
|
1213
|
+
let reason = null;
|
|
1214
|
+
let reasonLine = null;
|
|
1215
|
+
const fail = (why, lineNo = null) => {
|
|
1216
|
+
if (!ok) return;
|
|
1217
|
+
ok = false;
|
|
1218
|
+
reason = why;
|
|
1219
|
+
reasonLine = lineNo;
|
|
1220
|
+
};
|
|
1221
|
+
|
|
1222
|
+
const topStarts = [];
|
|
1223
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
1224
|
+
const rawLine = lines[i];
|
|
1225
|
+
const withoutComment = stripYamlComment(rawLine);
|
|
1226
|
+
const trimmed = withoutComment.trim();
|
|
1227
|
+
if (!trimmed) continue;
|
|
1228
|
+
if (/^\s*\t/.test(withoutComment) || /^\t/.test(withoutComment)) {
|
|
1229
|
+
fail(`第 ${i + 1} 行使用制表符缩进,无法安全解析`, i + 1);
|
|
1230
|
+
}
|
|
1231
|
+
if (/!!js\b/.test(withoutComment)) jsLines.push({ line: i + 1, text: rawLine });
|
|
1232
|
+
if (/^-\s+/.test(withoutComment)) topStarts.push(i);
|
|
1233
|
+
if (/:\s*[\[{]\s*[^}\]\s]/.test(withoutComment) || /^-\s*[\[{]/.test(trimmed)) {
|
|
1234
|
+
fail(`第 ${i + 1} 行使用了流式 YAML,无法安全静态解析`, i + 1);
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
if (!ok) return { ok: false, reason, line: reasonLine, entries: [], jsLines };
|
|
1238
|
+
|
|
1239
|
+
const meaningful = lines.filter((line) => stripYamlComment(line).trim());
|
|
1240
|
+
if (meaningful.length === 0 || (meaningful.length === 1 && meaningful[0].replace(/^-\s+/, '').trim() === '[]')) {
|
|
1241
|
+
return { ok: true, reason: null, line: null, entries: [], jsLines, empty: true };
|
|
1242
|
+
}
|
|
1243
|
+
if (topStarts.length === 0) {
|
|
1244
|
+
return { ok: false, reason: '未找到以 "- " 开头的顶层补丁行', line: null, entries: [], jsLines };
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
const entries = [];
|
|
1248
|
+
for (let t = 0; t < topStarts.length; t += 1) {
|
|
1249
|
+
const start = topStarts[t];
|
|
1250
|
+
const end = t + 1 < topStarts.length ? topStarts[t + 1] : lines.length;
|
|
1251
|
+
const first = stripYamlComment(lines[start]).replace(/^-\s+/, '').trim();
|
|
1252
|
+
const firstMatch = /^([A-Za-z0-9_$@./-]+)\s*:\s*(.*)$/.exec(first);
|
|
1253
|
+
if (!firstMatch) {
|
|
1254
|
+
entries.push({ kind: 'unknown', line: start + 1, reason: '顶层行不是 YAML 映射' });
|
|
1255
|
+
continue;
|
|
1256
|
+
}
|
|
1257
|
+
const firstKey = firstMatch[1];
|
|
1258
|
+
|
|
1259
|
+
if (firstKey === 'insert') {
|
|
1260
|
+
const itemStarts = [];
|
|
1261
|
+
let itemIndent = null;
|
|
1262
|
+
for (let i = start + 1; i < end; i += 1) {
|
|
1263
|
+
const withoutComment = stripYamlComment(lines[i]);
|
|
1264
|
+
const match = /^(\s+)-\s+/.exec(withoutComment);
|
|
1265
|
+
if (!match) continue;
|
|
1266
|
+
if (itemIndent === null) itemIndent = match[1].length;
|
|
1267
|
+
if (match[1].length === itemIndent) itemStarts.push(i);
|
|
1268
|
+
}
|
|
1269
|
+
const rows = [];
|
|
1270
|
+
for (let k = 0; k < itemStarts.length; k += 1) {
|
|
1271
|
+
const itemStart = itemStarts[k];
|
|
1272
|
+
const itemEnd = k + 1 < itemStarts.length ? itemStarts[k + 1] : end;
|
|
1273
|
+
const props = extractYamlProps(lines, itemStart, itemEnd);
|
|
1274
|
+
const idProp = props.find((prop) => prop.key === 'id' && prop.indent > (itemIndent ?? 0));
|
|
1275
|
+
const nameProp = props.find((prop) => prop.key === 'name' && prop.indent > (itemIndent ?? 0));
|
|
1276
|
+
const configProp = props.find((prop) => prop.key === 'config' && prop.indent > (itemIndent ?? 0));
|
|
1277
|
+
const nestedInsertProp = props.find((prop) => prop.key === 'insert' && prop.indent > (itemIndent ?? 0));
|
|
1278
|
+
let highPrivilege = null;
|
|
1279
|
+
for (const prop of [idProp, nameProp]) {
|
|
1280
|
+
if (!prop) continue;
|
|
1281
|
+
const keyword = highPrivilegeKeyword(prop.value);
|
|
1282
|
+
if (keyword) {
|
|
1283
|
+
highPrivilege = { line: prop.line, service: keyword, text: prop.text };
|
|
1284
|
+
break;
|
|
1285
|
+
}
|
|
1286
|
+
}
|
|
1287
|
+
if (!highPrivilege) highPrivilege = highPrivilegeConfigKey(props, configProp);
|
|
1288
|
+
rows.push({
|
|
1289
|
+
line: itemStart + 1,
|
|
1290
|
+
id: idProp ? stripYamlScalar(idProp.value) : null,
|
|
1291
|
+
name: nameProp ? stripYamlScalar(nameProp.value) : null,
|
|
1292
|
+
hasConfig: Boolean(configProp),
|
|
1293
|
+
nestedInsert: Boolean(nestedInsertProp),
|
|
1294
|
+
highPrivilege,
|
|
1295
|
+
});
|
|
1296
|
+
}
|
|
1297
|
+
if (rows.length === 0) {
|
|
1298
|
+
fail(`第 ${start + 1} 行的 insert 没有任何插入项`, start + 1);
|
|
1299
|
+
return { ok: false, reason, line: reasonLine, entries: [], jsLines };
|
|
1300
|
+
}
|
|
1301
|
+
entries.push({ kind: 'insert', line: start + 1, rows });
|
|
1302
|
+
continue;
|
|
1303
|
+
}
|
|
1304
|
+
|
|
1305
|
+
if (firstKey === 'id') {
|
|
1306
|
+
const props = extractYamlProps(lines, start, end);
|
|
1307
|
+
const idProp = props.find((prop) => prop.key === 'id');
|
|
1308
|
+
const nameProp = props.find((prop) => prop.key === 'name');
|
|
1309
|
+
const configProp = props.find((prop) => prop.key === 'config');
|
|
1310
|
+
const disabledProp = props.find((prop) => prop.key === 'disabled');
|
|
1311
|
+
let highPrivilege = null;
|
|
1312
|
+
// An override can target a high-privilege row by id alone (no `name:`).
|
|
1313
|
+
for (const prop of [idProp, nameProp]) {
|
|
1314
|
+
if (!prop) continue;
|
|
1315
|
+
const keyword = highPrivilegeKeyword(prop.value);
|
|
1316
|
+
if (keyword) {
|
|
1317
|
+
highPrivilege = { line: prop.line, service: keyword, text: prop.text };
|
|
1318
|
+
break;
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
if (!highPrivilege) highPrivilege = highPrivilegeConfigKey(props, configProp);
|
|
1322
|
+
entries.push({
|
|
1323
|
+
kind: 'override',
|
|
1324
|
+
line: start + 1,
|
|
1325
|
+
id: idProp ? stripYamlScalar(idProp.value) : null,
|
|
1326
|
+
hasName: Boolean(nameProp),
|
|
1327
|
+
hasConfig: Boolean(configProp),
|
|
1328
|
+
disabled: disabledProp ? stripYamlScalar(disabledProp.value) === 'true' : false,
|
|
1329
|
+
highPrivilege,
|
|
1330
|
+
});
|
|
1331
|
+
continue;
|
|
1332
|
+
}
|
|
1333
|
+
|
|
1334
|
+
entries.push({
|
|
1335
|
+
kind: 'unknown',
|
|
1336
|
+
line: start + 1,
|
|
1337
|
+
reason: `顶层键 "${firstKey}" 不是 id 或 insert`,
|
|
1338
|
+
});
|
|
1339
|
+
}
|
|
1340
|
+
|
|
1341
|
+
return { ok: true, reason: null, line: null, entries, jsLines };
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
/**
|
|
1345
|
+
* Audit a `cordis.patch.yml` file.
|
|
1346
|
+
*
|
|
1347
|
+
* @param {{ file: string, text: string }} context
|
|
1348
|
+
* @returns {RawFinding[]}
|
|
1349
|
+
*/
|
|
1350
|
+
export function scanPatchFile(context) {
|
|
1351
|
+
const { file, text } = context ?? {};
|
|
1352
|
+
const parsed = parsePatchYaml(text);
|
|
1353
|
+
const findings = [];
|
|
1354
|
+
const seen = new Set();
|
|
1355
|
+
const add = (ruleId, line, extra = {}) => {
|
|
1356
|
+
const lineNo = Number.isInteger(line) && line > 0 ? line : null;
|
|
1357
|
+
const key = `${ruleId}|${lineNo}`;
|
|
1358
|
+
if (seen.has(key)) return;
|
|
1359
|
+
seen.add(key);
|
|
1360
|
+
const finding = {
|
|
1361
|
+
ruleId,
|
|
1362
|
+
file,
|
|
1363
|
+
line: lineNo,
|
|
1364
|
+
evidence: extra.evidence ?? (lineNo ? lineTextAt(text, lineNo) : ''),
|
|
1365
|
+
};
|
|
1366
|
+
if (extra.vars) finding.vars = extra.vars;
|
|
1367
|
+
if (extra.confidence) finding.confidence = extra.confidence;
|
|
1368
|
+
findings.push(finding);
|
|
1369
|
+
};
|
|
1370
|
+
|
|
1371
|
+
if (!parsed.ok) {
|
|
1372
|
+
add('VG-INJ-06', parsed.line, {
|
|
1373
|
+
vars: { reason: parsed.reason ?? '补丁无法解析' },
|
|
1374
|
+
evidence: parsed.line
|
|
1375
|
+
? lineTextAt(text, parsed.line)
|
|
1376
|
+
: `cordis.patch.yml 解析失败:${parsed.reason ?? '未知原因'}`,
|
|
1377
|
+
});
|
|
1378
|
+
// Do not return here: an unparseable patch can still hide high-privilege
|
|
1379
|
+
// keywords or !!js in plain lines, and skipping them would reward the
|
|
1380
|
+
// malformed input.
|
|
1381
|
+
}
|
|
1382
|
+
if (parsed.ok && parsed.empty) return findings;
|
|
1383
|
+
|
|
1384
|
+
for (const entry of parsed.entries) {
|
|
1385
|
+
if (entry.kind === 'insert') {
|
|
1386
|
+
for (const row of entry.rows ?? []) {
|
|
1387
|
+
if (row.highPrivilege) {
|
|
1388
|
+
add('VG-INJ-01', row.highPrivilege.line, {
|
|
1389
|
+
vars: { service: row.highPrivilege.service },
|
|
1390
|
+
evidence: row.highPrivilege.text,
|
|
1391
|
+
});
|
|
1392
|
+
}
|
|
1393
|
+
if (row.nestedInsert) {
|
|
1394
|
+
add('VG-INJ-03', row.line, { vars: { rowId: row.id ?? '未命名插入行' } });
|
|
1395
|
+
}
|
|
1396
|
+
if (!row.id && !row.name) {
|
|
1397
|
+
add('VG-INJ-05', row.line, { vars: { rowId: '缺少 id/name 的插入行' } });
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
1400
|
+
continue;
|
|
1401
|
+
}
|
|
1402
|
+
if (entry.kind === 'override') {
|
|
1403
|
+
if (entry.id) {
|
|
1404
|
+
if (entry.hasName || entry.hasConfig || entry.disabled) {
|
|
1405
|
+
add('VG-INJ-02', entry.line, { vars: { rowId: entry.id } });
|
|
1406
|
+
} else {
|
|
1407
|
+
add('VG-INJ-05', entry.line, { vars: { rowId: entry.id } });
|
|
1408
|
+
}
|
|
1409
|
+
} else {
|
|
1410
|
+
add('VG-INJ-05', entry.line, { vars: { rowId: '缺少 id 的覆盖行' } });
|
|
1411
|
+
}
|
|
1412
|
+
if (entry.highPrivilege) {
|
|
1413
|
+
add('VG-INJ-01', entry.highPrivilege.line, {
|
|
1414
|
+
vars: { service: entry.highPrivilege.service },
|
|
1415
|
+
evidence: entry.highPrivilege.text,
|
|
1416
|
+
});
|
|
1417
|
+
}
|
|
1418
|
+
continue;
|
|
1419
|
+
}
|
|
1420
|
+
add('VG-INJ-05', entry.line, { vars: { rowId: entry.reason ?? '无法识别的补丁行' } });
|
|
1421
|
+
}
|
|
1422
|
+
|
|
1423
|
+
for (const jsLine of parsed.jsLines) {
|
|
1424
|
+
add('VG-INJ-04', jsLine.line, { vars: { detail: '!!js' } });
|
|
1425
|
+
}
|
|
1426
|
+
|
|
1427
|
+
const lines = String(text ?? '').split('\n');
|
|
1428
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
1429
|
+
const withoutComment = stripYamlComment(lines[i]);
|
|
1430
|
+
if (!withoutComment.trim()) continue;
|
|
1431
|
+
for (const pattern of getRulePack().audit.patchPrivilegePatterns) {
|
|
1432
|
+
if (pattern.re.test(withoutComment)) {
|
|
1433
|
+
add('VG-DSH-05', i + 1, { vars: { detail: pattern.detail } });
|
|
1434
|
+
break;
|
|
1435
|
+
}
|
|
1436
|
+
}
|
|
1437
|
+
}
|
|
1438
|
+
|
|
1439
|
+
return findings;
|
|
1440
|
+
}
|