dsh-git-push 2.9.4 → 2.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -39
- package/lib/app/apply.js +8 -1
- package/lib/app/audit-api.js +4 -1
- package/lib/app/command-registry.js +18 -11
- package/lib/app/handlers/meta.js +38 -0
- package/lib/app/handlers/repo-actions.js +3 -1
- package/lib/app/handlers/repos.js +18 -2
- package/lib/app/handlers/settings.js +0 -0
- package/lib/app/http-handlers.js +3 -1
- package/lib/app/schema.js +0 -0
- package/lib/app/settings-bridge.js +0 -0
- package/lib/app/tool-call.js +32 -23
- package/lib/ast/brace.js +15 -0
- package/lib/ast/control-flow.js +12 -3
- package/lib/ast/size.js +73 -3
- package/lib/audit/audit-file.js +4 -2
- package/lib/audit/collector.js +13 -4
- package/lib/audit/file-context.js +89 -0
- package/lib/audit/finding.js +16 -2
- package/lib/audit/ignore-blind.js +5 -4
- package/lib/audit/index.js +2 -2
- package/lib/audit/orchestrate.js +2 -1
- package/lib/audit-rules/audit-rules-frontend.yml +4 -4
- package/lib/checks/button-bind.js +84 -13
- package/lib/checks/dispatch.js +1 -1
- package/lib/checks/private.js +2 -1
- package/lib/checks/structural.js +10 -3
- package/lib/client-parts/{10-account.js → account.js} +1 -1
- package/lib/client-parts/{41-actions.js → actions.js} +3 -2
- package/lib/client-parts/{99-apply.js → apply.js} +2 -1
- package/lib/client-parts/{21-audit.js → audit.js} +5 -5
- package/lib/client-parts/{11-browser.js → browser.js} +15 -4
- package/lib/client-parts/{01-const.js → const.js} +11 -5
- package/lib/client-parts/{40-controller.js → controller.js} +4 -4
- package/lib/client-parts/{03-icons.js → icons.js} +1 -1
- package/lib/client-parts/{00-loader.js → loader.js} +1 -0
- package/lib/client-parts/{23-npm.js → npm.js} +3 -2
- package/lib/client-parts/{30-page.js → page.js} +1 -1
- package/lib/client-parts/{20-repo.js → repo.js} +2 -2
- package/lib/client-parts/{22-settings.js → settings.js} +1 -1
- package/lib/client-parts/{02-utils.js → utils.js} +1 -1
- package/lib/client.js +51 -30
- package/lib/commit-push.js +20 -2
- package/lib/context/index.js +2 -1
- package/lib/core/atomic-json.js +1 -1
- package/lib/core/exec.js +6 -4
- package/lib/exempt/index.js +7 -2
- package/lib/exempt/tool.js +198 -0
- package/lib/git/clone-history-mode.js +24 -5
- package/lib/git/index-format.js +182 -0
- package/lib/git/index.js +1 -0
- package/lib/git/push.js +28 -13
- package/lib/git/repo-index.js +41 -30
- package/lib/git/scan-runner.js +1 -1
- package/lib/git/transport.js +49 -17
- package/lib/git/visibility.js +93 -9
- package/lib/npm/publish.js +30 -1
- package/lib/npm/registry.js +5 -2
- package/lib/self/index.js +1 -1
- package/package.json +2 -4
- package/scripts/build-client.mjs +19 -14
- package/scripts/picker-repro.mjs +115 -0
- package/skills/dev/dsh-git-push.md +1 -2
- package/skills/dsh-repo-index.md +1 -1
- package/skills/guide/guide-audit.md +77 -3
- package/skills/guide/guide-cli-scripts.md +4 -4
- package/skills/guide/guide-clone-repos.md +2 -2
- package/skills/guide/guide-inject-ui.md +6 -6
- package/skills/workflow/README.md +1 -1
- package/assets/minihost.sh +0 -35
- package/assets/preview.html +0 -36703
- package/lib/fs/edit-after-read.js +0 -142
- package/scripts/frontend-preview-check.mjs +0 -124
- package/scripts/preview-gen.mjs +0 -489
- package/scripts/preview-local-runner.mjs +0 -55
- package/scripts/preview-server-direct.mjs +0 -116
- package/scripts/preview-server.mjs +0 -305
- package/scripts/preview-slot-data.mjs +0 -123
- package/scripts/sync-plugin-install.mjs +0 -286
- package/scripts/sync-plugin.mjs +0 -284
package/lib/ast/brace.js
CHANGED
|
@@ -24,6 +24,21 @@ export function matchBrace(tokens, openIdx) {
|
|
|
24
24
|
return null;
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
+
/** 前向圆括号配对:从 startIdx 的 '(' 找匹配 ')',返回其下标;不匹配返回 -1。 */
|
|
28
|
+
export function matchParenForward(tokens, startIdx) {
|
|
29
|
+
let depth = 0;
|
|
30
|
+
for (let i = startIdx; i < tokens.length; i++) {
|
|
31
|
+
const t = tokens[i];
|
|
32
|
+
if (t.type !== 'punct') continue;
|
|
33
|
+
if (t.value === '(') depth++;
|
|
34
|
+
else if (t.value === ')') {
|
|
35
|
+
depth--;
|
|
36
|
+
if (depth === 0) return i;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return -1;
|
|
40
|
+
}
|
|
41
|
+
|
|
27
42
|
/**
|
|
28
43
|
* 从 closeIdx 处 closePunct 向右→左配对,返回 openPunct 下标;不匹配返回 -1。
|
|
29
44
|
* 抽公共:原 matchingOpen({})/ matchingBracketBack([])/ matchingParenBack(())
|
package/lib/ast/control-flow.js
CHANGED
|
@@ -297,22 +297,31 @@ export function checkNestingDepthAst(text = '', { warn = 4, block = 6 } = {}) {
|
|
|
297
297
|
let depth = 0;
|
|
298
298
|
let maxDepth = 0;
|
|
299
299
|
let maxLine = 1;
|
|
300
|
-
|
|
300
|
+
// 归属判定:用 function 栈(起始行 + 其函数体深度),而不是「深度归零前最后一个 function 关键字」——
|
|
301
|
+
// 后者在模块级代码(不在任何函数里)时会把嵌套归到**已结束的旧函数**,整条规则误报。
|
|
302
|
+
const fnStack = []; // [{ startLine, bodyDepth }]
|
|
303
|
+
let pendingFnLine = 0; // 已见 function 关键字、等其函数体 { 入栈
|
|
301
304
|
for (let i = 0; i < tokens.length; i++) {
|
|
302
305
|
const t = tokens[i];
|
|
303
|
-
if (t.type === 'ident' && t.value === 'function')
|
|
306
|
+
if (t.type === 'ident' && t.value === 'function') pendingFnLine = t.line;
|
|
304
307
|
if (t.type === 'punct' && t.value === '{') {
|
|
305
308
|
if (isBlockBrace.get(i)) {
|
|
306
309
|
depth++;
|
|
310
|
+
if (pendingFnLine) { fnStack.push({ startLine: pendingFnLine, bodyDepth: depth }); pendingFnLine = 0; }
|
|
307
311
|
if (depth > maxDepth) { maxDepth = depth; maxLine = t.line; }
|
|
308
312
|
}
|
|
309
313
|
} else if (t.type === 'punct' && t.value === '}') {
|
|
310
314
|
// 只有块大括号才减(对象字面量的 `}` 不影响)
|
|
311
315
|
if (isBlockBrace.get(matchingOpen(tokens, i))) {
|
|
316
|
+
// 先判归属(栈顶函数此时可能正在结束,仍应归到它),再出栈
|
|
317
|
+
const endingFn = fnStack.length > 0 && fnStack[fnStack.length - 1].bodyDepth === depth;
|
|
312
318
|
depth--;
|
|
313
319
|
if (depth === 0 && maxDepth > warn) {
|
|
314
|
-
|
|
320
|
+
// 归属:有活跃函数(含正在结束的那个)→ 它的起始行;模块级代码 → 嵌套最深行(maxLine)
|
|
321
|
+
const owner = fnStack.length ? fnStack[fnStack.length - 1].startLine : maxLine;
|
|
322
|
+
out.push({ line: owner, depth: maxDepth, level: maxDepth > block ? 'blocker' : 'warning' });
|
|
315
323
|
}
|
|
324
|
+
if (endingFn) fnStack.pop();
|
|
316
325
|
if (depth <= 0) { depth = 0; maxDepth = 0; }
|
|
317
326
|
}
|
|
318
327
|
}
|
package/lib/ast/size.js
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
import { tokenize } from './tokenizer.js';
|
|
9
|
-
import { matchBrace } from './brace.js';
|
|
9
|
+
import { matchBrace, matchParenForward } from './brace.js';
|
|
10
10
|
import { javaKtFuncRanges } from './lang.js';
|
|
11
11
|
import { lineStats } from './line-count.js';
|
|
12
12
|
|
|
@@ -100,6 +100,68 @@ export function maxFunctionLength(text = '') {
|
|
|
100
100
|
return max;
|
|
101
101
|
}
|
|
102
102
|
|
|
103
|
+
/**
|
|
104
|
+
* 不是「方法名」的标识符:控制关键字与语言关键字。
|
|
105
|
+
* 方法简写判定是「ident ( … ) {」形态,必须把这些排除,否则 `if (x) {` / `for (…) {`
|
|
106
|
+
* 会被当成函数体,把整段代码算进「最大函数长度」。
|
|
107
|
+
*/
|
|
108
|
+
const NOT_A_METHOD_NAME = new Set([
|
|
109
|
+
'if', 'for', 'while', 'switch', 'catch', 'with', 'else', 'do', 'try', 'finally',
|
|
110
|
+
'return', 'typeof', 'await', 'yield', 'new', 'delete', 'void', 'instanceof', 'in', 'of',
|
|
111
|
+
'case', 'default', 'function', 'class', 'import', 'export', 'super', 'this',
|
|
112
|
+
]);
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* 箭头函数(块体)与方法简写的函数体范围。
|
|
116
|
+
*
|
|
117
|
+
* 为什么需要(2026-10-24 外部项目实测反馈):原先只认 `function` 关键字,于是
|
|
118
|
+
* `() => {…}`、`async () => {…}`、对象/类的方法简写 `m() {…}` **全部不计数** ⇒
|
|
119
|
+
* maxFunctionLength 返回 0。后果有两个,都是真缺陷:
|
|
120
|
+
* ① max-file-length / file-health 的「聚合型」判定要求「有函数且都合规」,
|
|
121
|
+
* maxFuncLen=0 会落进「臃肿型」,于是纯聚合形态的测试文件被报
|
|
122
|
+
* 「最大函数 0 行(臃肿型:文件大因藏着超大函数)」——文案自相矛盾且 scoreImpact=2;
|
|
123
|
+
* ② 真正很长的箭头函数从不被 max-function-length 报出(漏报)。
|
|
124
|
+
*
|
|
125
|
+
* 边界:
|
|
126
|
+
* · 只认**块体**箭头(`=> {`);表达式体(`=> x + 1`)不构成「长函数」;
|
|
127
|
+
* · 方法简写排除控制关键字与前缀为 `.` 的成员调用;
|
|
128
|
+
* · `function` 声明由 funcRangesAst 原分支处理,这里用 prev 判定跳过,避免重复计数。
|
|
129
|
+
*/
|
|
130
|
+
function arrowAndMethodRanges(tokens) {
|
|
131
|
+
const out = [];
|
|
132
|
+
const push = (range, name) => {
|
|
133
|
+
const startLine = tokens[range[0]].line;
|
|
134
|
+
const endLine = tokens[range[1]].line;
|
|
135
|
+
out.push({ startLine, endLine, len: endLine - startLine + 1, name });
|
|
136
|
+
};
|
|
137
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
138
|
+
const t = tokens[i];
|
|
139
|
+
// ① 箭头函数:`=>` 紧跟 `{`
|
|
140
|
+
if (t.type === 'punct' && t.value === '=>') {
|
|
141
|
+
const nx = tokens[i + 1];
|
|
142
|
+
if (nx && nx.type === 'punct' && nx.value === '{') {
|
|
143
|
+
const r = matchBrace(tokens, i + 1);
|
|
144
|
+
if (r) push(r, '(箭头)');
|
|
145
|
+
}
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
// ② 方法简写:ident '(' … ')' '{'
|
|
149
|
+
if (t.type !== 'ident' || NOT_A_METHOD_NAME.has(t.value)) continue;
|
|
150
|
+
const prev = tokens[i - 1];
|
|
151
|
+
if (prev && prev.type === 'punct' && prev.value === '.') continue; // 成员调用 a.b()
|
|
152
|
+
if (prev && prev.type === 'ident' && prev.value === 'function') continue; // function 声明已由原分支处理
|
|
153
|
+
const np = tokens[i + 1];
|
|
154
|
+
if (!np || np.type !== 'punct' || np.value !== '(') continue;
|
|
155
|
+
const closeParen = matchParenForward(tokens, i + 1);
|
|
156
|
+
if (closeParen < 0) continue;
|
|
157
|
+
const nb = tokens[closeParen + 1];
|
|
158
|
+
if (!nb || nb.type !== 'punct' || nb.value !== '{') continue;
|
|
159
|
+
const r = matchBrace(tokens, closeParen + 1);
|
|
160
|
+
if (r) push(r, t.value);
|
|
161
|
+
}
|
|
162
|
+
return out;
|
|
163
|
+
}
|
|
164
|
+
|
|
103
165
|
export function funcRangesAst(text = '') {
|
|
104
166
|
const tokens = tokenize(text);
|
|
105
167
|
const out = [];
|
|
@@ -114,6 +176,11 @@ export function funcRangesAst(text = '') {
|
|
|
114
176
|
// 与 JS 分支结果去重(极端混合文件里同名起点的保守处理)
|
|
115
177
|
if (!out.some((o) => o.startLine === r.startLine)) out.push(r);
|
|
116
178
|
}
|
|
179
|
+
// 箭头函数与方法简写:与 function 声明并列进同一份范围表
|
|
180
|
+
// (去重按 startLine:同一函数体中嵌套的箭头会被外层覆盖,取外层起点等价)
|
|
181
|
+
for (const r of arrowAndMethodRanges(tokens)) {
|
|
182
|
+
if (!out.some((o) => o.startLine === r.startLine)) out.push(r);
|
|
183
|
+
}
|
|
117
184
|
for (let i = 0; i < tokens.length; i++) {
|
|
118
185
|
const t = tokens[i];
|
|
119
186
|
if (t.type !== 'ident' || t.value !== 'function') continue;
|
|
@@ -339,8 +406,11 @@ export function checkCommentDensityAst(text = '', { warn = COMMENT_DENSITY_WARN_
|
|
|
339
406
|
export function checkRepeatedStringsAst(text = '', { min = 3, ignore = [] } = {}) {
|
|
340
407
|
const tokens = tokenize(text);
|
|
341
408
|
// tokenizer 产出的字面量类型名是 str / tmpl / num(非 string/number);
|
|
342
|
-
// 类型名不匹配会让本检查永不命中,故按实际类型名收集;num
|
|
343
|
-
|
|
409
|
+
// 类型名不匹配会让本检查永不命中,故按实际类型名收集;num 刻意排除(见上)。
|
|
410
|
+
// tmpl(模板字符串)也排除:模板串常用于「生成代码/拼接文本」(如垫片 harness 里
|
|
411
|
+
// 重复出现的 ` };` 缩进),其内部重复是生成内容而非「应配置化的硬编码值」,
|
|
412
|
+
// 统计它会把生成代码的排版误报成重复字面量(2026-10-17 实测误报)。
|
|
413
|
+
const LITERAL_TYPES = new Set(['str']);
|
|
344
414
|
const ignoreSet = new Set(['', ' ', '\n', '-', '/', '0', '1', 'utf8', 'string', 'number', 'boolean', 'object', 'function', ...ignore]);
|
|
345
415
|
const counts = new Map();
|
|
346
416
|
for (const t of tokens) {
|
package/lib/audit/audit-file.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { runChecks } from './checks.js';
|
|
2
2
|
import { exemptForFinding } from '../exempt/index.js';
|
|
3
|
-
import { hasExternalCallTimeout, hasMkdirInSameFunction } from './file-context.js';
|
|
3
|
+
import { hasExternalCallTimeout, hasMkdirInSameFunction, hasForeignWriteTarget } from './file-context.js';
|
|
4
4
|
import { CODE_EXTS } from './finding.js';
|
|
5
5
|
|
|
6
6
|
/**
|
|
@@ -166,10 +166,12 @@ export function auditFile({ file, relPath, text, grouped }, opts = {}) {
|
|
|
166
166
|
// 调用处无需重复设置(纯 regex 规则看不到包装内部)
|
|
167
167
|
if (/githubFetch\s*\(/.test(fileLines[idx] || '')) return false;
|
|
168
168
|
}
|
|
169
|
-
// mkdir
|
|
169
|
+
// mkdir 语义豁免:① 写文件前同函数已建目录(ensureDataDir 模式)
|
|
170
|
+
// ② 写目标来自调用方(形参 / 形参成员 / 由形参派生的临时路径)⇒ 目录不归本函数管
|
|
170
171
|
if (f.rule === 'robustness/mkdir-before-write') {
|
|
171
172
|
const idx = Math.max(0, (Number(f.line) || 1) - 1);
|
|
172
173
|
if (hasMkdirInSameFunction(fileLines, idx)) return false;
|
|
174
|
+
if (hasForeignWriteTarget(fileLines, idx)) return false;
|
|
173
175
|
}
|
|
174
176
|
// loader 契约语义豁免:已按统一 ModuleLoader 契约注册
|
|
175
177
|
if (f.rule === 'dsh/client-module-loader-id' && hasLoaderContract) return false;
|
package/lib/audit/collector.js
CHANGED
|
@@ -12,6 +12,7 @@ import { execFileSync, spawnSync } from 'node:child_process';
|
|
|
12
12
|
import { isTestExemptDir } from '../exempt/index.js';
|
|
13
13
|
import { SKIP_DIRS as HARDCODED_SKIP, getSkipSet } from '../skip-dirs.js';
|
|
14
14
|
import { parseGitignore, isIgnoredByRules } from './gitignore-match.js';
|
|
15
|
+
import { GIT_GLOBAL_ARGS } from '../core/exec.js';
|
|
15
16
|
|
|
16
17
|
/** 跳过目录集合 = 硬编码基线(node_modules/.git) ∪ yml 黑名单关键词(加载一次缓存)。 */
|
|
17
18
|
const SKIP_DIRS = getSkipSet();
|
|
@@ -29,8 +30,16 @@ const TEXT_EXT = new Set([
|
|
|
29
30
|
const GIT_PROBE_TIMEOUT_MS = 10_000;
|
|
30
31
|
const IGNORE_BATCH_TIMEOUT_MS = 60_000;
|
|
31
32
|
const IGNORE_SINGLE_TIMEOUT_MS = 5_000;
|
|
32
|
-
/**
|
|
33
|
-
|
|
33
|
+
/**
|
|
34
|
+
* git 命令统一前缀:直接用 lib/core/exec.js 的权威包装(GIT_GLOBAL_ARGS)。
|
|
35
|
+
*
|
|
36
|
+
* 为什么不再本地定义:此前这里只抄了 `-c core.quotepath=false`(禁路径转义,
|
|
37
|
+
* 中文/空格文件名按原样匹配),与 exec.js 的权威前缀「抄写不一致」——
|
|
38
|
+
* exec.js 那份还带 `safe.directory=*`(防不信任目录误伤工作区)与
|
|
39
|
+
* `core.filemode=false`(忽略权限位抖动,CIFS/NFS/跨机同步后不再刷一堆 M)。
|
|
40
|
+
* 直接复用权威定义 ⇒ 三件一次到位,以后只改一处。
|
|
41
|
+
*/
|
|
42
|
+
const GIT_QUOTEPATH_ARGS = GIT_GLOBAL_ARGS;
|
|
34
43
|
/** 单文件大小上限:超过 1MB 的文件跳过(防止读入大文件拖死扫描进程)。 */
|
|
35
44
|
const MAX_FILE_SIZE = 1024 * 1024;
|
|
36
45
|
|
|
@@ -371,7 +380,7 @@ export function collectChangedFiles(repoPath) {
|
|
|
371
380
|
if (!isGitRepo(repoPath)) return null;
|
|
372
381
|
try {
|
|
373
382
|
// 显式捕获 stderr(execFileSync 未设 stdio 时异常会把 git stderr 直通父进程)
|
|
374
|
-
const out = execFileSync('git', ['-C', repoPath, 'status', '--porcelain'], {
|
|
383
|
+
const out = execFileSync('git', [...GIT_GLOBAL_ARGS, '-C', repoPath, 'status', '--porcelain'], {
|
|
375
384
|
encoding: 'utf8', timeout: GIT_PROBE_TIMEOUT_MS, stdio: ['ignore', 'pipe', 'pipe'],
|
|
376
385
|
});
|
|
377
386
|
const files = [];
|
|
@@ -387,7 +396,7 @@ export function collectChangedFiles(repoPath) {
|
|
|
387
396
|
// 未跟踪目录(?? dir/):git status --porcelain 只显示目录本身,需展开为目录内文件,
|
|
388
397
|
// 否则审计漏掉整目录(对齐 getDiff 用 git ls-files --others 展开的行为)。
|
|
389
398
|
if (status === '??' && rel.endsWith('/')) {
|
|
390
|
-
const inside = execFileSync('git', ['-C', repoPath, 'ls-files', '--others', '--exclude-standard', '--', rel], {
|
|
399
|
+
const inside = execFileSync('git', [...GIT_GLOBAL_ARGS, '-C', repoPath, 'ls-files', '--others', '--exclude-standard', '--', rel], {
|
|
391
400
|
encoding: 'utf8', timeout: GIT_PROBE_TIMEOUT_MS,
|
|
392
401
|
});
|
|
393
402
|
for (const p of inside.split('\n').filter(Boolean)) {
|
|
@@ -33,6 +33,95 @@ export function hasMkdirInSameFunction(lines, lineIdx) {
|
|
|
33
33
|
return false;
|
|
34
34
|
}
|
|
35
35
|
|
|
36
|
+
/**
|
|
37
|
+
* 写目标是否「来自调用方」——若是,则目录创建责任不在本函数,mkdir-before-write 应豁免。
|
|
38
|
+
*
|
|
39
|
+
* 背景(2026-10-17 ZipCalm 反馈:robustness 槽位 4 条里 3 条跨界误报):
|
|
40
|
+
* 上一档 hasMkdirInSameFunction 只看**同函数**,而这些站点把写目标交给调用方准备:
|
|
41
|
+
* · store.js `const tmpPath = `${ctx.historyFile}.tmp`; fs.writeFile(tmpPath, …)`
|
|
42
|
+
* · writer.js `fs.createWriteStream(ctx.tempPath)`
|
|
43
|
+
* · tarFamily.js `fs.createWriteStream(plannedEntry.targetPath)`
|
|
44
|
+
* · zip/index.js `openArchivePipeline(tempPath, level)` ⇒ `fs.createWriteStream(tempPath)`
|
|
45
|
+
* 目标要么是**形参**、要么是形参的成员/由形参派生的临时路径 ⇒ 目录由调用方(或临时目录
|
|
46
|
+
* 提供方)负责建 ⇒ 规则说的「直接 writeFile 而不 mkdir ⇒ ENOENT」在本站点**不成立**
|
|
47
|
+
* (判错事实 = 真误报 ✓,不是"不想改")。
|
|
48
|
+
*
|
|
49
|
+
* 判据(保守,只认能静态确认的归属):
|
|
50
|
+
* ① 取下写调用的首参表达式,取它的**根标识符**;
|
|
51
|
+
* ② 根标识符若在**所属函数的形参列表**里 ⇒ 外来目标 ⇒ 豁免;
|
|
52
|
+
* ③ 根标识符是局部变量时,看它的赋值 RHS 是否**以形参为根**(如 `${ctx.x}.tmp`)⇒ 豁免;
|
|
53
|
+
* ④ 其余(本地字面量 / join(...) 现场拼路径 / 无赋值可查)⇒ **不豁免**,交给同函数档判定 ✓
|
|
54
|
+
* @param {string[]} lines 文件全部行
|
|
55
|
+
* @param {number} lineIdx 命中行索引(0 基)
|
|
56
|
+
* @returns {boolean} true=写目标来自调用方(应豁免)
|
|
57
|
+
*/
|
|
58
|
+
export function hasForeignWriteTarget(lines, lineIdx) {
|
|
59
|
+
const line = String(lines[lineIdx] || '');
|
|
60
|
+
// 取写调用的首参(到第一个逗号/右括号为止;模板串与成员链都吃)
|
|
61
|
+
const m = line.match(/(?:writeFile|writeFileSync|createWriteStream|appendFile|appendFileSync|createWriteStreamSync)\s*\(\s*([^,)]+)/);
|
|
62
|
+
if (!m) return false;
|
|
63
|
+
const target = m[1].trim();
|
|
64
|
+
const rootMatch = target.match(/^[$A-Za-z_][\w$]*/);
|
|
65
|
+
if (!rootMatch) return false;
|
|
66
|
+
const root = rootMatch[0];
|
|
67
|
+
const params = enclosingParams(lines, lineIdx);
|
|
68
|
+
if (params.has(root)) return true;
|
|
69
|
+
// 局部变量:查它的赋值 RHS 是否以形参为根(`${ctx.historyFile}.tmp` 这类临时路径)
|
|
70
|
+
const assignRe = new RegExp(`(?:const|let|var)\\s+${root}\\s*=\\s*([^;]+)`);
|
|
71
|
+
for (let i = lineIdx - 1; i >= Math.max(0, lineIdx - 40); i--) {
|
|
72
|
+
const mm = String(lines[i] || '').match(assignRe);
|
|
73
|
+
if (!mm) continue;
|
|
74
|
+
const rhs = mm[1];
|
|
75
|
+
// ⚠️ 只认「同目录派生」:模板串/字符串拼接(`${ctx.x}.tmp`、x + '.tmp')与成员传递;
|
|
76
|
+
// join(...) / resolve(...) 会**新增路径段**(join(dir,'sub','a.json'))⇒ 目录可能还没建,
|
|
77
|
+
// 仍由本函数负责 ⇒ 不豁免 ✓(否则会把真命中一起修掉 ✗,实测过一轮)
|
|
78
|
+
if (/\bjoin\s*\(|\bresolve\s*\(/.test(rhs)) return false;
|
|
79
|
+
const ids = rhs.match(/[$A-Za-z_][\w$]*/g) || [];
|
|
80
|
+
return ids.some((id) => params.has(id)); // 由形参派生 ⇒ 目录由调用方负责
|
|
81
|
+
}
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* 取「所属函数」的形参名集合(向上找最近的函数签名;找不到返回空集)。
|
|
87
|
+
* 支持 function 声明/表达式、方法简写、箭头函数与 async 变体;
|
|
88
|
+
* 默认值、类型注解、解构都做保守处理(解构里的标识符也算形参 ✓)。
|
|
89
|
+
* @param {string[]} lines 文件全部行
|
|
90
|
+
* @param {number} lineIdx 命中行索引(0 基)
|
|
91
|
+
* @returns {Set<string>} 形参名集合
|
|
92
|
+
*/
|
|
93
|
+
function enclosingParams(lines, lineIdx) {
|
|
94
|
+
const out = new Set();
|
|
95
|
+
// ⚠️ 控制流行不是函数签名:`if (cond) {` / `for (…) {` / `while (…) {` / `catch (e) {` 等
|
|
96
|
+
// 都能被 `(…)\s*{` 匹配上 ⇒ 会把判定用的花括号误当函数体、参数集取成条件里的标识符 ✗
|
|
97
|
+
// (2026-10-17 实测:正是这一条让 hasForeignWriteTarget 对 ZipCalm 三处全部返回 false)
|
|
98
|
+
const CTRL_RE = /^\s*(?:\}\s*)?(?:if|for|while|switch|catch|do|else|return|with)\b/;
|
|
99
|
+
// ⚠️ 第二个实测坑:**行内回调**里的 `=>` 也会被当成函数头 ✗
|
|
100
|
+
// store.js 的 `const body = … ? \`${entries.map((item) => JSON.stringify(item))…` 与
|
|
101
|
+
// writer.js 的 `createThrottledReporter(ctx.onProgress || (() => {}), {`
|
|
102
|
+
// 都被扫成"签名" ⇒ 参数集 {item} / 空 ⇒ ctx 不在其中 ⇒ 判不出来 ✓(已修:箭头必须**以 => 结尾**)
|
|
103
|
+
// ③ 嵌套回调里写的目标,其目录往往由**外层函数**的形参决定(tarFamily 的 planned 来自外层)⇒
|
|
104
|
+
// 向外收集多层作用域的形参并集(上限 4 层,避免过度收集削弱规则)
|
|
105
|
+
const MAX_SCOPE_HEADS = 4;
|
|
106
|
+
for (let i = lineIdx, heads = 0; i >= Math.max(0, lineIdx - FUNC_START_SCAN_BACK) && heads < MAX_SCOPE_HEADS; i--) {
|
|
107
|
+
const text = String(lines[i] || '');
|
|
108
|
+
if (CTRL_RE.test(text)) continue;
|
|
109
|
+
const isDecl = /(?:^|\s)(?:async\s+)?function\b/.test(text);
|
|
110
|
+
const isArrowHead = /(?:\([^()]*\)|[$A-Za-z_][\w$]*)\s*=>\s*\{?\s*$/.test(text);
|
|
111
|
+
const isMethod = !/=>/.test(text) && /^\s*(?:export\s+)?(?:async\s+)?[$A-Za-z_][\w$]*\s*\([^)]*\)\s*\{/.test(text);
|
|
112
|
+
if (!isDecl && !isArrowHead && !isMethod) continue;
|
|
113
|
+
const sig = text.match(/(?:function\s*[$A-Za-z_][\w$]*\s*|(?:async\s+)?)(\([^)]*\))/)
|
|
114
|
+
|| (isArrowHead ? text.match(/(\([^)]*\))\s*=>/) : null);
|
|
115
|
+
if (!sig) continue;
|
|
116
|
+
for (const part of sig[1].replace(/[()]/g, '').split(',')) {
|
|
117
|
+
const name = (part.split(/[=:]/)[0].match(/[$A-Za-z_][\w$]*/g) || []).pop();
|
|
118
|
+
if (name) out.add(name);
|
|
119
|
+
}
|
|
120
|
+
heads += 1;
|
|
121
|
+
}
|
|
122
|
+
return out;
|
|
123
|
+
}
|
|
124
|
+
|
|
36
125
|
/**
|
|
37
126
|
* 外部 API 调用超时语义豁免:
|
|
38
127
|
* robustness/timeout-on-external-api 规则用纯 regex 匹配 `fetch(`/`axios.(` 等调用,
|
package/lib/audit/finding.js
CHANGED
|
@@ -1,6 +1,20 @@
|
|
|
1
1
|
import { exemptHintForFinding, exemptMarkerCovers } from '../exempt/index.js';
|
|
2
2
|
|
|
3
|
-
/**
|
|
3
|
+
/**
|
|
4
|
+
* 是否「拦截级」finding —— **统一定义**(severity 为 blocker 或 error)。
|
|
5
|
+
*
|
|
6
|
+
* 为什么必须有这个函数(2026-10-17 由反馈「summary.blocker(10) vs 枚举(7)」触发):
|
|
7
|
+
* summarize 把 error 计入 blocker(见下方 1.1.0 修复),但各处枚举 blocked[] 只筛
|
|
8
|
+
* `severity === 'blocker'` ⇒ 同一个「拦截级」两套口径 ⇒ 出现 10 vs 7 的差额
|
|
9
|
+
* (差的正是 3 条 error 级:圈复杂度等)。凡需要枚举/判定拦截级的地方一律调本函数 ✓
|
|
10
|
+
*/
|
|
11
|
+
export function isBlockerFinding(f) {
|
|
12
|
+
const sev = (f && f.severity) || 'warning';
|
|
13
|
+
return sev === 'blocker' || sev === 'error';
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* 统一问题对象构造器(所有审计检查的出口)。 */
|
|
4
18
|
export function makeFinding({ file, line, rule, kind, severity = 'warning', message, dimensions = [], exemptHint = '', scoreImpact = 0 }) {
|
|
5
19
|
return { file, line, rule, kind, severity, message, dimensions, exemptHint, scoreImpact };
|
|
6
20
|
}
|
|
@@ -68,7 +82,7 @@ export function summarize(findings = []) {
|
|
|
68
82
|
let blocker = 0, warning = 0, notice = 0;
|
|
69
83
|
for (const f of findings) {
|
|
70
84
|
const sev = f.severity || 'warning';
|
|
71
|
-
if (
|
|
85
|
+
if (isBlockerFinding(f)) blocker++; // error=拦截级(凭据泄露/语法错误等)
|
|
72
86
|
else if (sev === 'notice' || sev === 'info') notice++;
|
|
73
87
|
else warning++;
|
|
74
88
|
}
|
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
import { existsSync, readFileSync } from 'node:fs';
|
|
21
21
|
import { join, isAbsolute } from 'node:path';
|
|
22
22
|
import { spawnSync } from 'node:child_process';
|
|
23
|
+
import { GIT_GLOBAL_ARGS } from '../core/exec.js';
|
|
23
24
|
|
|
24
25
|
/* ───────── 静默失明检测常量 ───────── */
|
|
25
26
|
const GIT_PROBE_TIMEOUT_MS = 5000; // git rev-parse 探测超时
|
|
@@ -36,7 +37,7 @@ const BROAD_PATTERNS = new Set(['*', '/*', '**', '**/*', '.']);
|
|
|
36
37
|
* @returns {string} 路径(可能不存在)
|
|
37
38
|
*/
|
|
38
39
|
function excludePathOf(root) {
|
|
39
|
-
const r = spawnSync('git', ['-C', root, 'rev-parse', '--git-dir'], {
|
|
40
|
+
const r = spawnSync('git', [...GIT_GLOBAL_ARGS, '-C', root, 'rev-parse', '--git-dir'], {
|
|
40
41
|
encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: GIT_PROBE_TIMEOUT_MS,
|
|
41
42
|
});
|
|
42
43
|
if (r.status !== 0) return '';
|
|
@@ -52,7 +53,7 @@ function excludePathOf(root) {
|
|
|
52
53
|
* @returns {{broad: string[], ignoreRatio: number, tracked: number}|null} null = 非 git 或无异常
|
|
53
54
|
*/
|
|
54
55
|
export function detectIgnoreBlindSpot(root) {
|
|
55
|
-
const probe = spawnSync('git', ['-C', root, 'rev-parse', '--is-inside-work-tree'], {
|
|
56
|
+
const probe = spawnSync('git', [...GIT_GLOBAL_ARGS, '-C', root, 'rev-parse', '--is-inside-work-tree'], {
|
|
56
57
|
encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: GIT_PROBE_TIMEOUT_MS,
|
|
57
58
|
});
|
|
58
59
|
if (probe.status !== 0 || String(probe.stdout || '').trim() !== 'true') return null;
|
|
@@ -74,7 +75,7 @@ export function detectIgnoreBlindSpot(root) {
|
|
|
74
75
|
let tracked = 0;
|
|
75
76
|
let ignored = 0;
|
|
76
77
|
try {
|
|
77
|
-
const ls = spawnSync('git', ['-C', root, 'ls-files'], {
|
|
78
|
+
const ls = spawnSync('git', [...GIT_GLOBAL_ARGS, '-C', root, 'ls-files'], {
|
|
78
79
|
encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: GIT_LS_TIMEOUT_MS,
|
|
79
80
|
});
|
|
80
81
|
if (ls.status === 0) {
|
|
@@ -84,7 +85,7 @@ export function detectIgnoreBlindSpot(root) {
|
|
|
84
85
|
// 必须带 --no-index:对**已跟踪**文件,check-ignore 默认不报(它们按定义不被忽略),
|
|
85
86
|
// 而我们要问的正是「这些文件在审计收集时会不会被跳过」。实测不带该参数时
|
|
86
87
|
// 被 `*` 污染的仓库仍返回 0 条,行为判据形同失效。
|
|
87
|
-
const ci = spawnSync('git', ['-C', root, 'check-ignore', '--stdin', '--no-index'], {
|
|
88
|
+
const ci = spawnSync('git', [...GIT_GLOBAL_ARGS, '-C', root, 'check-ignore', '--stdin', '--no-index'], {
|
|
88
89
|
input: files.join('\n'), encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], timeout: GIT_LS_TIMEOUT_MS,
|
|
89
90
|
});
|
|
90
91
|
if (ci.status === 0 || ci.status === 1) {
|
package/lib/audit/index.js
CHANGED
|
@@ -24,10 +24,10 @@
|
|
|
24
24
|
|
|
25
25
|
import '../rule/compilers.js'; // 副作用:注册 13 种编译函数
|
|
26
26
|
|
|
27
|
-
export { makeFinding, decorateTestExemptHint, normalizeExemptHints, summarize, CODE_EXTS } from './finding.js';
|
|
27
|
+
export { makeFinding, decorateTestExemptHint, normalizeExemptHints, isBlockerFinding, summarize, CODE_EXTS } from './finding.js';
|
|
28
28
|
export { slotStatsFromFindings, buildRuleSlotMap, countRulesBySlot } from './slot.js';
|
|
29
29
|
export { repoLevelSemanticRuleIds, pickRepoLevelAnchorFile } from './repo-level.js';
|
|
30
|
-
export { hasMkdirInSameFunction, hasExternalCallTimeout, detectRepoJsYamlImport, isVersionInPathContext } from './file-context.js';
|
|
30
|
+
export { hasMkdirInSameFunction, hasForeignWriteTarget, hasExternalCallTimeout, detectRepoJsYamlImport, isVersionInPathContext } from './file-context.js';
|
|
31
31
|
export { auditFile } from './audit-file.js';
|
|
32
32
|
export { capScanFiles, auditFull, auditChanged, auditWithScope } from './orchestrate.js';
|
|
33
33
|
export { findingsToYaml } from './report-yaml.js';
|
package/lib/audit/orchestrate.js
CHANGED
|
@@ -5,6 +5,7 @@ import { collectTextFiles, readText, isGitRepo, collectChangedFiles, isTextFile
|
|
|
5
5
|
import { computeAnalysisCoverage } from './analysis-coverage.js';
|
|
6
6
|
import { groupByKind, HINT_QUALITY, checkFolderRules, checkPrivateFiles, checkDuplicateCode, checkDuplicateConst, checkMultiFileScanners } from './checks.js';
|
|
7
7
|
import { loadRuleFiles } from '../rule/loader.js';
|
|
8
|
+
import { GIT_GLOBAL_ARGS } from '../core/exec.js';
|
|
8
9
|
import { compileAllRules } from '../rule/registry.js';
|
|
9
10
|
import { auditFile } from './audit-file.js';
|
|
10
11
|
import { grammarForExt, parseText, makeSyncConfirmer } from '../ast/treesitter.js';
|
|
@@ -502,7 +503,7 @@ export async function auditChanged(repoPath, opts = {}) {
|
|
|
502
503
|
// (退出码 1);加 --no-index 强制按路径匹配 ignore 规则,已跟踪文件同样命中。
|
|
503
504
|
// 与全量审计 collector.js 的 check-ignore 调用(--stdin --no-index)对齐,
|
|
504
505
|
// 否则「.auditignore 目录豁免对 changed 扫描生效」只对未跟踪文件成立。
|
|
505
|
-
execFileSync('git', ['-C', repoPath, ...ignoreExtraArgs, 'check-ignore', '-q', '--no-index', '--', rel], {
|
|
506
|
+
execFileSync('git', [...GIT_GLOBAL_ARGS, '-C', repoPath, ...ignoreExtraArgs, 'check-ignore', '-q', '--no-index', '--', rel], {
|
|
506
507
|
encoding: 'utf8', timeout: CHECK_IGNORE_TIMEOUT_MS, stdio: ['ignore', 'pipe', 'pipe'],
|
|
507
508
|
});
|
|
508
509
|
return true; // exit 0 = 命中忽略
|
|
@@ -244,15 +244,15 @@ rules:
|
|
|
244
244
|
severity: "warning"
|
|
245
245
|
description: "HTML 字符串中有按钮,但同文件 JS 中找不到对应绑定证据(addEventListener/onclick=/选择器引用)——若通过事件委托或封装函数绑定请加豁免标记"
|
|
246
246
|
fixable: false
|
|
247
|
-
mitigation: "
|
|
247
|
+
mitigation: "确认是否需要绑定;事件委托/封装函数绑定请加 dsh-skip-quality(文件头)豁免标记"
|
|
248
248
|
|
|
249
249
|
- id: button/create-element-binding
|
|
250
|
-
name: "createElement
|
|
250
|
+
name: "createElement 创建的元素应显式绑定"
|
|
251
251
|
category: "button"
|
|
252
252
|
severity: "warning"
|
|
253
|
-
description: "用 createElement('button'/'input')
|
|
253
|
+
description: "用 createElement('button'/'input') 创建元素但同文件找不到对应事件的绑定痕迹则为未绑定。按元素类型分流判据:button 要求 click 类(addEventListener('click')/onclick=/@click/事件委托);input 接受 change/input/submit/pointerdown/keydown 等表单控件标准事件;<input type=\"file\"> 由原生交互触发(label.click()/input.click() 打开选择框),存在程序化触发即视为已接好,不要求 click 绑定"
|
|
254
254
|
fixable: false
|
|
255
|
-
mitigation: "
|
|
255
|
+
mitigation: "按钮在 appendChild 前调用 addEventListener('click', fn);表单控件绑定 change/input;原生文件选择框无需额外绑定,如判定仍不准可加 dsh-skip-quality 文件头标记"
|
|
256
256
|
|
|
257
257
|
- id: button/event-delegation-detected
|
|
258
258
|
name: "检测到事件委托模式"
|
|
@@ -135,7 +135,7 @@ function stripCommentLines(text) {
|
|
|
135
135
|
* @param {object} opts { file, text, rules }
|
|
136
136
|
* @returns {Array} findings
|
|
137
137
|
*/
|
|
138
|
-
export function checkButtonBindings({ file, text, rules }) {
|
|
138
|
+
export function checkButtonBindings({ file, text, rules, fileScope = '' }) {
|
|
139
139
|
const findings = [];
|
|
140
140
|
if (!text) return findings;
|
|
141
141
|
|
|
@@ -159,6 +159,14 @@ export function checkButtonBindings({ file, text, rules }) {
|
|
|
159
159
|
const btnRe = /<button\b([^>]*)>([\s\S]*?)<\/button\s*>|<input\b[^>]*type\s*=\s*['"](?:button|submit)['"][^>]*>/gi;
|
|
160
160
|
// JSX/React 事件属性(onClick=/onChange= 等驼峰 on[A-Z])→ 声明式绑定,视为已绑定(防 React 代码误报 unbound)
|
|
161
161
|
const jsxEventRe = /\bon[A-Z][\w]*\s*=\s*[\{'"`]/;
|
|
162
|
+
// Vue/声明式模板事件属性:@click / @click.self|stop|prevent|once / v-on:click(含修饰符)/ @[click]
|
|
163
|
+
// 2026-10-17 由 ZipCalm 反馈修复:该项目的 .vue 按钮**全部**写作
|
|
164
|
+
// `<button … data-testid="compress-close" @click="emit('close')">关闭</button>`,
|
|
165
|
+
// 而旧判据只认 React 的 onClick ⇒ 同一元素上的绑定看不见 ⇒ 16 条全部误报
|
|
166
|
+
// (判据说"未找到绑定证据",但绑定就写在按钮元素自己身上 ✗ 属判错事实)。
|
|
167
|
+
// 注意只认 click 类事件:Vue 的 @click 是绑定证据,与 HTML 字符串里的 inline onclick 不同,
|
|
168
|
+
// 不产生 button/inline-binding-in-string 提示(那是 DOM0 内联写法的问题)。
|
|
169
|
+
const vueEventRe = /(?:@click(?:\.\w+)*|v-on:click(?:\.\w+)*|@\[click\])\s*=/;
|
|
162
170
|
for (const chunk of htmlChunks.concat(tplChunks)) {
|
|
163
171
|
let bm;
|
|
164
172
|
while ((bm = btnRe.exec(chunk.html)) !== null) {
|
|
@@ -171,17 +179,27 @@ export function checkButtonBindings({ file, text, rules }) {
|
|
|
171
179
|
text: (bm[2] || '').replace(/<[^>]*>/g, '').trim().slice(0, 30),
|
|
172
180
|
hasInline: /\bonclick\s*=/.test(attrs),
|
|
173
181
|
jsxBound: jsxEventRe.test(attrs), // React 声明式事件(onClick 等驼峰)
|
|
182
|
+
vueBound: vueEventRe.test(attrs), // Vue 声明式事件(@click / v-on:click)
|
|
183
|
+
// 静态 disabled 按钮:永远不会被点击 ⇒ 无需绑定(2026-10-17 ZipCalm 反馈:
|
|
184
|
+
// `<button type="button" disabled title="任务未结束…">删除</button>` 被判 unbound 属
|
|
185
|
+
// 判据不适配 ✓)。只认静态属性:`:disabled="cond"` 是动态的,可能可点 ⇒ 不在此列 ✓
|
|
186
|
+
staticDisabled: /(?:^|\s)disabled(?:\s|$)/.test(attrs),
|
|
174
187
|
});
|
|
175
188
|
}
|
|
176
189
|
}
|
|
177
190
|
// JSX 工厂调用创建的按钮(jsx.jsx('button', {...}))——与 HTML 字符串同等待遇:
|
|
178
191
|
// 属性里有 onClick 等事件属性即已绑定;没有则进 unbound 判定(原先完全不可见)
|
|
179
192
|
const jsxBtns = extractJsxButtons(text);
|
|
180
|
-
// createElement('button')
|
|
193
|
+
// createElement('button'/'input') 创建的元素:需要看是否以**该元素类型应有的方式**接好交互
|
|
181
194
|
const created = [];
|
|
182
195
|
const createRe = /createElement\s*\(\s*['"](button|input)['"]\s*\)/g;
|
|
183
196
|
while ((match = createRe.exec(text)) !== null) {
|
|
184
|
-
|
|
197
|
+
// 文件选择框识别:createElement('input') 之后常见写法是 `input.type = 'file'`
|
|
198
|
+
// 或对象字面量 `{ type: 'file' }`。这类元素由原生交互触发(见下方 createElement 判定),
|
|
199
|
+
// 不适用「必须绑 click」的判据。
|
|
200
|
+
const after = text.slice(match.index, match.index + 800);
|
|
201
|
+
const isFile = match[1] === 'input' && /(?:\.type\s*=\s*['"]file['"]|type\s*[:=]\s*['"]file['"])/i.test(after);
|
|
202
|
+
created.push({ line: text.slice(0, match.index).split('\n').length, tag: match[1], isFile });
|
|
185
203
|
}
|
|
186
204
|
|
|
187
205
|
// ── 2. 提取绑定证据(选择器引用 + 绑定调用 + 事件委托)──
|
|
@@ -195,10 +213,20 @@ export function checkButtonBindings({ file, text, rules }) {
|
|
|
195
213
|
}
|
|
196
214
|
if (match[0].includes('addEventListener') || match[0].includes('.onclick') || match[0].includes('.on(')) binds.add('__has_click_handler__');
|
|
197
215
|
}
|
|
216
|
+
|
|
217
|
+
// ── 非点击类事件证据(2026-10-24 补)──
|
|
218
|
+
// 为什么需要:上面的 bindRe **只认 click**,于是表单控件的正当接法一律被判成「未绑定」。
|
|
219
|
+
// 实测外部项目三处 `<input type="file">`(原生 label.click() 触发文件选择,事件是 change)
|
|
220
|
+
// 全被报「创建了按钮但没绑 click」——但它根本不需要 click。
|
|
221
|
+
// 语义边界:这些事件对 button/a **不算**绑定证据(按钮的正当交互仍是 click 类),
|
|
222
|
+
// 只在「创建的是 input」时才作为已绑定的依据(表单控件的 change/input/submit 是标准用法)。
|
|
223
|
+
const altEventRe = /\.addEventListener\s*\(\s*['"](?:change|input|submit|pointerdown|pointerup|keydown|keyup|touchstart|focus)['"]|\.on\s*\(\s*['"](?:change|input|submit|pointerdown|pointerup|keydown|keyup|touchstart|focus)['"]|\bon(?:change|input|submit|pointerdown|keydown)\s*=/g;
|
|
224
|
+
const hasAltHandler = altEventRe.test(text);
|
|
225
|
+
// 程序化触发(label.click() / input.click()):文件选择框的常规接法,靠原生行为打开选择框
|
|
226
|
+
const hasProgrammaticClick = /\.click\s*\(\s*\)/.test(text);
|
|
198
227
|
// 事件委托识别(更宽):父级 .addEventListener('click' + e.target.closest('选择器') 任一出现即视为委托面
|
|
199
228
|
// 覆盖:document.body.addEventListener('click' / container.addEventListener('click' / ev.target.closest('.btn') 分发
|
|
200
|
-
const delegationRe = /\.addEventListener\s*\(\s*['"]click['"]|\.closest\s*\(\s*['"][^'"]+['"]\)/g;
|
|
201
|
-
if (delegationRe.test(text)) hasDelegation = true;
|
|
229
|
+
const delegationRe = /\.addEventListener\s*\(\s*['"]click['"]|\.closest\s*\(\s*['"][^'"]+['"]\)/g; if (delegationRe.test(text)) hasDelegation = true;
|
|
202
230
|
// 委托分发选择器(ev.target.closest('.mm-retry-btn'))也入 binds——按 class 匹配绑定面
|
|
203
231
|
const closestRe = /\.closest\s*\(\s*['"]([^'"]+)['"]\)/g;
|
|
204
232
|
while ((match = closestRe.exec(text)) !== null) {
|
|
@@ -228,7 +256,9 @@ export function checkButtonBindings({ file, text, rules }) {
|
|
|
228
256
|
// 3b. HTML 字符串里的按钮
|
|
229
257
|
for (const btn of btns) {
|
|
230
258
|
// JSX/React 声明式事件:onClick 等驼峰属性 = 已绑定(React 虚拟 DOM 内声明式,非油猴场景)
|
|
231
|
-
|
|
259
|
+
// Vue 同理:@click / v-on:click 写在按钮元素上 = 已绑定(2026-10-17 修复,见 vueEventRe 注释)
|
|
260
|
+
if (btn.jsxBound || btn.vueBound) continue;
|
|
261
|
+
if (btn.staticDisabled) continue; // 静态禁用按钮:不可点 ⇒ 无绑定诉求 ✓
|
|
232
262
|
// inline onclick:有绑定但建议改(info)
|
|
233
263
|
if (btn.hasInline) {
|
|
234
264
|
findings.push(makeFinding({
|
|
@@ -264,13 +294,54 @@ export function checkButtonBindings({ file, text, rules }) {
|
|
|
264
294
|
// createElement('button'/'input') 创建的按钮:文件无任何点击绑定痕迹 → 未绑定
|
|
265
295
|
// (jsx 工厂按钮已由 3a 单独判定,不参与此处兜底,避免互相掩盖)
|
|
266
296
|
if (created.length && !binds.has('__has_click_handler__')) {
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
297
|
+
// 按创建的元素类型分流判定「是否真的缺交互绑定」:
|
|
298
|
+
// · 含 button ⇒ 必须有 click 类绑定(alt 事件不足以证明按钮可点)
|
|
299
|
+
// · 只创建 input ⇒ change/input/submit 等是标准绑定方式,有就算已绑
|
|
300
|
+
// · 全部是 <input type="file"> ⇒ 原生交互(label.click()/input.click() 打开选择框),
|
|
301
|
+
// 本身不需要点击处理器;存在程序化触发即视为按原生方式接好
|
|
302
|
+
const hasButton = created.some((c) => c.tag === 'button');
|
|
303
|
+
const allFileInputs = created.every((c) => c.tag === 'input' && c.isFile);
|
|
304
|
+
const coveredByAltEvent = !hasButton && hasAltHandler;
|
|
305
|
+
const coveredByNativeFile = allFileInputs && hasProgrammaticClick;
|
|
306
|
+
if (!coveredByAltEvent && !coveredByNativeFile) {
|
|
307
|
+
const lineNos = [...new Set(created.map((c) => c.line))].sort((a, b) => a - b);
|
|
308
|
+
const kindWord = created[0].tag === 'input' ? '表单控件' : '按钮';
|
|
309
|
+
findings.push(makeFinding({
|
|
310
|
+
file, line: lineNos[0], rule: 'button/create-element-binding', kind: 'button-bind',
|
|
311
|
+
severity: 'warning',
|
|
312
|
+
message: `createElement('${created[0].tag}') 创建了${kindWord}(行 ${lineNos.join('/')})但同文件未找到对应事件绑定`
|
|
313
|
+
+ (created[0].tag === 'input'
|
|
314
|
+
? '——请绑定 change/input(表单控件)或补一个可豁免标记'
|
|
315
|
+
: '——请在 appendChild 前绑定 click'),
|
|
316
|
+
dimensions: ['可维护性'], exemptHint: HINT_QUALITY, scoreImpact: 1,
|
|
317
|
+
}));
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
// 去重:同一按钮可能被多路提取命中(innerHTML 片段 + 反引号模板 + JSX 工厂)⇒ 同一行只留一条
|
|
321
|
+
// (2026-10-17 实测:`el.innerHTML = \`<button…>\`` 会同时进 htmlChunks 与 tplChunks ⇒ 重复报 2 条 ✗)
|
|
322
|
+
const seenKey = new Set();
|
|
323
|
+
const deduped = findings.filter((f) => {
|
|
324
|
+
const k = `${f.rule}|${f.line}`;
|
|
325
|
+
if (seenKey.has(k)) return false;
|
|
326
|
+
seenKey.add(k);
|
|
327
|
+
return true;
|
|
328
|
+
});
|
|
329
|
+
// 分片架构适配(2026-10-24):DSH 插件的客户端源码可以是**分片**(`lib/client-parts/**`),
|
|
330
|
+
// 注意:标准 `client-parts/` 布局由规则包的 exclude_dirs 全局跳过(片段语义,完整判定交给产物),
|
|
331
|
+
// 本分支覆盖的是**自定义分片目录**(package.json 的 dsh.client.fragments 指向别处)的情形。
|
|
332
|
+
// 由构建脚本拼成运行态单文件(`lib/client.js`)。分片是**片段**:单个分片语法都不成立,
|
|
333
|
+
// 「创建元素」与「绑定事件」完全可能落在不同分片(视图分片建 DOM、控制器分片绑事件),
|
|
334
|
+
// 于是「同文件找不到绑定证据」这个判据在分片架构里**前提就不成立**。
|
|
335
|
+
// 处理:分片文件降级为 info(仍出现在报告里、不扣分),完整性由产物 client.js 承担判定
|
|
336
|
+
// ——产物是所有分片的拼接,证据自然齐全。
|
|
337
|
+
// 不用 exempt 静默排除:让「分片里某按钮确实没绑」这个事实仍可被看到。
|
|
338
|
+
if (fileScope === 'dsh-client-fragment') {
|
|
339
|
+
return deduped.map((f) => makeFinding({
|
|
340
|
+
...f,
|
|
341
|
+
severity: 'info',
|
|
342
|
+
scoreImpact: 0,
|
|
343
|
+
message: `${f.message}(本文件是客户端分片,绑定可能写在其它分片;完整性以拼接产物 client.js 的判定为准)`,
|
|
273
344
|
}));
|
|
274
345
|
}
|
|
275
|
-
return
|
|
346
|
+
return deduped;
|
|
276
347
|
}
|
package/lib/checks/dispatch.js
CHANGED
|
@@ -97,7 +97,7 @@ export function runChecks({ file, relPath, text, grouped }, opts = {}) {
|
|
|
97
97
|
// patch insert 语义检查(yml 文件 insert/覆盖 id 冲突才报)
|
|
98
98
|
if (grouped['patch-insert']) findings = findings.concat(checkPatchInsert({ file, text, rules: grouped['patch-insert'] }));
|
|
99
99
|
// 1.0.5:按钮事件绑定交叉比对(油猴脚本/扩展——HTML 在 JS 字符串,事件在 JS 绑定)
|
|
100
|
-
if (grouped['button-bind']) findings = findings.concat(checkButtonBindings({ file, text, rules: grouped['button-bind'] }));
|
|
100
|
+
if (grouped['button-bind']) findings = findings.concat(checkButtonBindings({ file, text, rules: grouped['button-bind'], fileScope: resolveFileScope({ repoPath: opts?.repoPath, relPath: relPath || file }) }));
|
|
101
101
|
// 1.0.7:硬编码魔数检测(版本号豁免版——版本号/日期/HTTP 状态码/常见合法常量/状态枚举自动豁免)
|
|
102
102
|
if (grouped['magic-number-smart']) findings = findings.concat(checkMagicNumberSmart({ file, text, rules: grouped['magic-number-smart'] }));
|
|
103
103
|
// 三层审计 L2——数据流检查(kind=dataflow,如 clear-then-access 同函数清空后访问)
|