dsh-git-push 2.20.19 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (196) hide show
  1. package/README.md +3 -2
  2. package/cli-tool.mjs +2 -4
  3. package/cli.mjs +7 -1
  4. package/lib/app/apply.js +4 -4
  5. package/lib/app/command-registry.js +22 -17
  6. package/lib/app/handlers/meta.js +2 -2
  7. package/lib/app/handlers/preprocess.js +107 -0
  8. package/lib/app/handlers/repo-actions.js +2 -2
  9. package/lib/app/http-handlers.js +13 -42
  10. package/lib/app/index.js +2 -1
  11. package/lib/app/inject-text.js +3 -3
  12. package/lib/app/preprocess-client.js +136 -0
  13. package/lib/app/repo-ownership.js +1 -1
  14. package/lib/app/schema.js +3 -3
  15. package/lib/app/severity.js +14 -0
  16. package/lib/app/slash-commands.js +5 -164
  17. package/lib/app/tool-call.js +73 -144
  18. package/lib/cli/commands-preprocess.mjs +74 -0
  19. package/lib/cli/commands-tool.mjs +3 -2
  20. package/lib/cli/commands-vcs.mjs +4 -4
  21. package/lib/cli/shared.mjs +35 -9
  22. package/lib/commit-push/pre-commit-engine.js +57 -10
  23. package/lib/commit-push.js +71 -27
  24. package/lib/{exempt/index.js → git/exempt-markers.js} +8 -1
  25. package/lib/git/ignore.js +1 -1
  26. package/lib/git/repos.js +2 -2
  27. package/lib/git/sensitive.js +1 -1
  28. package/lib/npm/publish.js +20 -5
  29. package/lib/plugin/auto-push.js +2 -2
  30. package/lib/preprocess/providers.js +191 -0
  31. package/lib/self/index.js +1 -1
  32. package/lib/skip-dirs.js +14 -55
  33. package/package.json +29 -37
  34. package/scripts/build-client.mjs +2 -0
  35. package/scripts/check.mjs +4 -2
  36. package/scripts/local-registry.mjs +2 -1
  37. package/cli-audit.mjs +0 -141
  38. package/lib/app/audit-api.js +0 -173
  39. package/lib/app/handlers/audit.js +0 -150
  40. package/lib/app/host-doc-checks.js +0 -25
  41. package/lib/app/scope-check.js +0 -69
  42. package/lib/ast/brace.js +0 -120
  43. package/lib/ast/callgraph.js +0 -135
  44. package/lib/ast/code-lines.js +0 -175
  45. package/lib/ast/consts.js +0 -12
  46. package/lib/ast/control-flow.js +0 -470
  47. package/lib/ast/credential.js +0 -315
  48. package/lib/ast/dataflow.js +0 -391
  49. package/lib/ast/dup-code.js +0 -165
  50. package/lib/ast/fs-hotspots.js +0 -154
  51. package/lib/ast/index.js +0 -38
  52. package/lib/ast/io-risk-const.js +0 -95
  53. package/lib/ast/io-risk-fn.js +0 -208
  54. package/lib/ast/io-risk-loop.js +0 -308
  55. package/lib/ast/io-risk.js +0 -314
  56. package/lib/ast/lang.js +0 -156
  57. package/lib/ast/line-count.js +0 -52
  58. package/lib/ast/magic-number.js +0 -272
  59. package/lib/ast/naming.js +0 -292
  60. package/lib/ast/perf.js +0 -488
  61. package/lib/ast/scope-collisions.js +0 -228
  62. package/lib/ast/scope.js +0 -241
  63. package/lib/ast/shell.js +0 -131
  64. package/lib/ast/size.js +0 -448
  65. package/lib/ast/symbol-index.js +0 -399
  66. package/lib/ast/tokenizer.js +0 -421
  67. package/lib/ast/treesitter.js +0 -413
  68. package/lib/audit/analysis-coverage.js +0 -98
  69. package/lib/audit/audit-file.js +0 -205
  70. package/lib/audit/auditignore-rules.js +0 -148
  71. package/lib/audit/checks.js +0 -17
  72. package/lib/audit/client-entry.js +0 -93
  73. package/lib/audit/collector.js +0 -610
  74. package/lib/audit/ext-runner.js +0 -80
  75. package/lib/audit/file-context.js +0 -391
  76. package/lib/audit/finding.js +0 -101
  77. package/lib/audit/gitignore-match.js +0 -113
  78. package/lib/audit/glob.js +0 -63
  79. package/lib/audit/history-report.js +0 -100
  80. package/lib/audit/history.js +0 -126
  81. package/lib/audit/ignore-blind.js +0 -102
  82. package/lib/audit/index.js +0 -33
  83. package/lib/audit/orchestrate.js +0 -672
  84. package/lib/audit/public.js +0 -24
  85. package/lib/audit/repo-level.js +0 -30
  86. package/lib/audit/report-yaml.js +0 -90
  87. package/lib/audit/scope-policy.js +0 -110
  88. package/lib/audit/slot.js +0 -66
  89. package/lib/audit-rules/audit-rules-comment.yml +0 -199
  90. package/lib/audit-rules/audit-rules-cpp.yml +0 -114
  91. package/lib/audit-rules/audit-rules-csharp.yml +0 -82
  92. package/lib/audit-rules/audit-rules-docs.yml +0 -32
  93. package/lib/audit-rules/audit-rules-dsh.yml +0 -177
  94. package/lib/audit-rules/audit-rules-filehealth.yml +0 -42
  95. package/lib/audit-rules/audit-rules-folder.yml +0 -99
  96. package/lib/audit-rules/audit-rules-frontend.yml +0 -335
  97. package/lib/audit-rules/audit-rules-go.yml +0 -103
  98. package/lib/audit-rules/audit-rules-i18n.yml +0 -45
  99. package/lib/audit-rules/audit-rules-java.yml +0 -105
  100. package/lib/audit-rules/audit-rules-nodejs.yml +0 -662
  101. package/lib/audit-rules/audit-rules-npm.yml +0 -187
  102. package/lib/audit-rules/audit-rules-paths.yml +0 -98
  103. package/lib/audit-rules/audit-rules-performance.yml +0 -245
  104. package/lib/audit-rules/audit-rules-php.yml +0 -101
  105. package/lib/audit-rules/audit-rules-private.yml +0 -24
  106. package/lib/audit-rules/audit-rules-python.yml +0 -106
  107. package/lib/audit-rules/audit-rules-robustness.yml +0 -31
  108. package/lib/audit-rules/audit-rules-rust.yml +0 -109
  109. package/lib/audit-rules/audit-rules-structure.yml +0 -158
  110. package/lib/audit-rules/audit-rules-swift.yml +0 -99
  111. package/lib/audit-rules/audit-rules-template.yml +0 -108
  112. package/lib/audit-ui-sdk/contract.js +0 -117
  113. package/lib/audit-ui-sdk/index.js +0 -17
  114. package/lib/checks/button-bind.js +0 -347
  115. package/lib/checks/common.js +0 -170
  116. package/lib/checks/credential-file.js +0 -43
  117. package/lib/checks/dataflow.js +0 -40
  118. package/lib/checks/dispatch.js +0 -117
  119. package/lib/checks/dup-code.js +0 -69
  120. package/lib/checks/dup-const.js +0 -232
  121. package/lib/checks/file-health.js +0 -150
  122. package/lib/checks/filter.js +0 -137
  123. package/lib/checks/folder.js +0 -173
  124. package/lib/checks/fs-scanner.js +0 -57
  125. package/lib/checks/hardcoded-path.js +0 -98
  126. package/lib/checks/index.js +0 -49
  127. package/lib/checks/io.js +0 -66
  128. package/lib/checks/magic-number.js +0 -42
  129. package/lib/checks/npm-json.js +0 -273
  130. package/lib/checks/private.js +0 -64
  131. package/lib/checks/regex.js +0 -298
  132. package/lib/checks/scope-collision.js +0 -68
  133. package/lib/checks/semantic.js +0 -134
  134. package/lib/checks/structural.js +0 -281
  135. package/lib/cli/commands-audit.mjs +0 -142
  136. package/lib/cli/commands-doc.mjs +0 -127
  137. package/lib/client-parts/audit/audit.js +0 -301
  138. package/lib/exempt/tool.js +0 -198
  139. package/lib/git/module-splitter.js +0 -47
  140. package/lib/link-check/index.js +0 -187
  141. package/lib/lint-adapter/detect.js +0 -161
  142. package/lib/lint-adapter/index.js +0 -50
  143. package/lib/lint-adapter/runner.js +0 -133
  144. package/lib/preprocess/audit.js +0 -98
  145. package/lib/preprocess/index.js +0 -78
  146. package/lib/rule/compilers/credential.js +0 -62
  147. package/lib/rule/compilers/dataflow.js +0 -38
  148. package/lib/rule/compilers/file-health.js +0 -75
  149. package/lib/rule/compilers/frontend.js +0 -86
  150. package/lib/rule/compilers/func.js +0 -35
  151. package/lib/rule/compilers/helpers.js +0 -71
  152. package/lib/rule/compilers/index.js +0 -29
  153. package/lib/rule/compilers/link-semantic.js +0 -45
  154. package/lib/rule/compilers/list-kinds.js +0 -12
  155. package/lib/rule/compilers/numeric-kinds.js +0 -73
  156. package/lib/rule/compilers/regex.js +0 -78
  157. package/lib/rule/compilers/structure.js +0 -107
  158. package/lib/rule/compilers.js +0 -17
  159. package/lib/rule/homoglyph.js +0 -45
  160. package/lib/rule/loader.js +0 -274
  161. package/lib/rule/registry.js +0 -122
  162. package/lib/rule/scope.js +0 -67
  163. package/lib/score/docs-score.js +0 -166
  164. package/lib/score/index.js +0 -234
  165. package/scripts/__pycache__/module-splitter.cpython-38.pyc +0 -0
  166. package/scripts/audit-ext/_example-readme-present.mjs +0 -34
  167. package/scripts/audit-ext/dsh-inject-declarations.mjs +0 -209
  168. package/scripts/audit-ext/variable-min-length.mjs +0 -102
  169. package/scripts/audit-gate.mjs +0 -235
  170. package/scripts/audit-runner.mjs +0 -35
  171. package/scripts/audit-runtime-check.mjs +0 -129
  172. package/scripts/browser-page-probe.mjs +0 -271
  173. package/scripts/check-js-scope.mjs +0 -87
  174. package/scripts/clean-date-comments.py +0 -102
  175. package/scripts/cpu-sample.mjs +0 -188
  176. package/scripts/doc-drift.mjs +0 -200
  177. package/scripts/hot-path-probe-cjs.cjs +0 -71
  178. package/scripts/hot-path-probe-fs-shim.mjs +0 -28
  179. package/scripts/hot-path-probe-fsp-shim.mjs +0 -31
  180. package/scripts/hot-path-probe.mjs +0 -153
  181. package/scripts/module-splitter.py +0 -800
  182. package/scripts/picker-repro.mjs +0 -115
  183. package/scripts/platform-scan.mjs +0 -168
  184. package/scripts/probe-recheck.mjs +0 -47
  185. package/scripts/rename-locator.mjs +0 -97
  186. package/scripts/rule-switch.mjs +0 -97
  187. package/scripts/rules-solo-audit.mjs +0 -173
  188. package/scripts/scan-file-io.mjs +0 -717
  189. package/scripts/scan-fs-hotspots.mjs +0 -107
  190. package/scripts/symbol-index.mjs +0 -85
  191. package/scripts/verify-prestep.mjs +0 -100
  192. package/skills/dev/audit-rule-authoring.md +0 -58
  193. package/skills/guide/guide-audit.md +0 -270
  194. /package/lib/{audit → app}/ownership.js +0 -0
  195. /package/lib/app/{schema-audit.js → schema-preprocess.js} +0 -0
  196. /package/lib/{audit-defaults.js → git/defaults.js} +0 -0
@@ -1,78 +0,0 @@
1
- /**
2
- * 编译层 · 正则类 kind(两个)
3
- *
4
- * regex(正文正则,按 ext 作用域跑)、path-regex(路径正则)。
5
- * 两者都是「模式串命中即报」,差别只在匹配对象是文件内容还是文件路径。
6
- */
7
-
8
- import { registerCompiler } from '../registry.js';
9
- import { DIMENSIONS, ruleOut, safeRe, severityLevel, pickDimensions } from './helpers.js';
10
-
11
- /* ───────────────────────── 注册:正则两类 ───────────────────────── */
12
-
13
- registerCompiler(
14
- 'regex',
15
- (r) => Array.isArray(r?.patterns) || typeof r?.pattern === 'string',
16
- (r, ctx) => {
17
- // 子模式支持(文档 §13 承诺「可直接落地」):patterns 条目可为字符串或对象 {id,pattern,message}
18
- const list = [r.pattern, ...(Array.isArray(r.patterns) ? r.patterns : [])]
19
- .map((p) => {
20
- if (typeof p === 'string') return { regex: safeRe(p, r?.name || r?.id, ctx.errors), message: null };
21
- if (p && typeof p === 'object' && typeof p.pattern === 'string') {
22
- return { regex: safeRe(p.pattern, r?.name || r?.id, ctx.errors), message: p.message || null };
23
- }
24
- return null;
25
- })
26
- .filter((x) => x && x.regex);
27
- if (!list.length) return null; // 无有效 pattern → 编译失败交调用方
28
- return ruleOut({
29
- id: r.id, name: r.name || r.id, kind: 'regex', severity: r.severity,
30
- level: severityLevel(r.severity),
31
- // 每个条目带 regex + 可选专属 message(checks.js 对 RegExp 条目的向后兼容)
32
- pattern: list[0].regex, patterns: list.map((x, i) => (i === 0 ? x.regex : x.regex)), // 保持 RegExp 主键兼容
33
- message: r.description || r.name || '',
34
- dimensions: pickDimensions(r, [DIMENSIONS.可读性], ctx?.errors),
35
- // subPatterns 走 extra 展开(ruleOut 只白名单 id/name/kind/... 顶层字段 + extra)
36
- extra: {
37
- subPatterns: list,
38
- exts: Array.isArray(r.exts) ? r.exts.map((x) => String(x).toLowerCase().replace(/^\./, '')) : undefined,
39
- // 路径级排除——按 relPath 前缀过滤(如 client-node-builtin-require
40
- // 只查浏览器侧,排除 server/ test/ lib/ 等 Node 目录,修纯正则误伤)
41
- excludePaths: Array.isArray(r.exclude_paths) ? r.exclude_paths.map(String) : undefined,
42
- // 路径级白名单——只对指定文件跑该规则(如「package.json 的 version 必须 SemVer」:
43
- // 仅 exts:["json"] 会把规则套到所有 json 上,第三方仓库成千上万个 json 被误报,实测 1435 条)。
44
- // 语义见 lib/checks/filter.js filterRulesByPath:不含 '/' 按文件名匹配,含 '/' 按路径后缀匹配。
45
- includePaths: Array.isArray(r.include_paths) ? r.include_paths.map(String) : undefined,
46
- // 白名单行豁免——命中 whitelist_patterns 的行不报(修凭据类误报:
47
- // 字段引用/API 名/字符串字面量 ≠ 硬编码凭据值)
48
- whitelistPatterns: Array.isArray(r.whitelist_patterns) ? r.whitelist_patterns.map(String) : undefined,
49
- // 正则初筛 → AST 精筛开关——声明后正则只筛候选行,再由 token 级
50
- // 判定确认命中行确实是代码行,注释/字符串里的内容不再误报。
51
- // astConfirm: true → 用 makeCodeLineFilter(行级:是否代码行);
52
- // astConfirm: "magic-number" → 用 checkMagicNumberSmartAst(值级:该数字
53
- // 是否真魔数——版本号/日期/HTTP 状态码/命名常量值/参数默认值/索引运算
54
- // i+1 等自动豁免,修纯 regex 把索引运算当魔数的大面积误报)。
55
- astConfirm: r.astConfirm === true || r.astConfirm === 'magic-number' ? r.astConfirm : undefined,
56
- // 具名精筛(供子模式规则声明「命中后还要 AST 确认什么」)——
57
- // 如 performance/memory-bomb 的 small-file-read:确认读的是否受控小文件。
58
- astConfirmKind: typeof r.ast_confirm_kind === 'string' ? r.ast_confirm_kind
59
- : (typeof r.astConfirmKind === 'string' ? r.astConfirmKind : undefined),
60
- examples: r.examples || undefined, // G6 认领:bad/good 示例展示字段
61
- },
62
- });
63
- },
64
- );
65
-
66
- registerCompiler(
67
- 'path-regex',
68
- (r) => r?.kind === 'path-regex' || (r?.path_pattern && !/^credfile-/.test(r?.id || '')),
69
- (r, ctx) => {
70
- const re = safeRe(r.path_pattern, r?.name || r?.id, ctx.errors);
71
- return ruleOut({
72
- id: r.id, name: r.name || r.id, kind: 'path-regex', severity: r.severity,
73
- level: severityLevel(r.severity), pathPattern: re?.source,
74
- message: r.description || r.name || '',
75
- dimensions: pickDimensions(r, [DIMENSIONS.可读性, DIMENSIONS.可维护性], ctx?.errors),
76
- });
77
- },
78
- );
@@ -1,107 +0,0 @@
1
- /**
2
- * 编译层 · 结构类 kind(三个)
3
- *
4
- * 注释黑名单(comment 槽位)、目录级审计(folder 槽位:目录数/单目录文件数)、
5
- * npm 结构化(npm-json:license/repository/files 字段判定)。
6
- */
7
-
8
- import { registerCompiler } from '../registry.js';
9
- import { DIMENSIONS, ruleOut, severityLevel, pickDimensions } from './helpers.js';
10
-
11
- /* ───────────────────────── 注册:注释黑名单(comment 槽位,1.0.3) ───────────────────────── */
12
-
13
- /**
14
- * 注释措辞黑名单(comment-wording 分数制)。
15
- * 认领条件:黑名单数组 pattern+weight 形态(comment 槽位总纲规则)。
16
- * 编译产物:blacklist[]({pattern, weight} 直接下传检查器,检查器做行级加分扣分判定)。
17
- */
18
- registerCompiler(
19
- 'blacklist',
20
- (r) => Array.isArray(r?.blacklist) && r.blacklist.length > 0,
21
- (r) => ruleOut({
22
- id: r.id, name: r.name || r.id, kind: 'blacklist', severity: r.severity || 'warning',
23
- level: severityLevel(r.severity || 'warning'),
24
- message: r.description || r.name || '注释措辞审查',
25
- dimensions: pickDimensions(r, [DIMENSIONS.文档]),
26
- extra: {
27
- // 路径级排除必须放进 extra:ruleOut 只透传固定顶层字段 + extra,
28
- // 顶层塞 excludePaths 会被静默丢弃(实测:声明了却仍照报归档目录)。
29
- excludePaths: Array.isArray(r.exclude_paths) ? r.exclude_paths.map(String) : undefined,
30
- blacklist: Array.isArray(r.blacklist) ? r.blacklist.map((b) => ({ pattern: b.pattern, ...(b.weight !== undefined ? { weight: Number(b.weight) || 0 } : {}) })) : [],
31
- whitelist: Array.isArray(r.whitelist) ? r.whitelist.map((w) => ({ pattern: w.pattern, ...(w.penalty !== undefined ? { penalty: Number(w.penalty) || 0 } : {}) })) : [],
32
- additionalFeatures: Array.isArray(r.additional_features) ? r.additional_features.map((a) => ({ pattern: a.pattern, weight: Number(a.weight) || 0 })) : [],
33
- // G6 认领:scoring.threshold_suspicious(comment.yml 60)→ threshold,action/suggestions 展示字段透传
34
- threshold: Number(r.threshold ?? r.scoring?.threshold_suspicious) || undefined,
35
- scoring: r.scoring || undefined,
36
- action: r.action || undefined,
37
- suggestions: Array.isArray(r.suggestions) ? r.suggestions : undefined,
38
- },
39
- }),
40
- );
41
-
42
- /* ───────────────────────── 注册:目录级审计(folder 槽位,1.0.3) ───────────────────────── */
43
-
44
- /**
45
- * 目录级审计规则(文件夹数量审计:目录总数/单目录文件数/解包特征/.gitignore 覆盖)。
46
- * 认领条件:category === 'folder' 或带 threshold+exclude_dirs/signatures 组合字段。
47
- * 编译产物:目录级规则对象(threshold/excludeDirs/signatures/requiredPatterns 下传 checkFolderRules)。
48
- */
49
- registerCompiler(
50
- 'folder',
51
- (r) => r?.category === 'folder' || (r?.threshold !== undefined && (Array.isArray(r?.exclude_dirs) || Array.isArray(r?.signatures) || Array.isArray(r?.required_patterns))),
52
- (r) => ruleOut({
53
- id: r.id, name: r.name || r.id, kind: 'folder', severity: r.severity,
54
- level: severityLevel(r.severity),
55
- message: r.message || r.description || r.name || '',
56
- dimensions: pickDimensions(r, [DIMENSIONS.可维护性, DIMENSIONS.可部署性]),
57
- extra: {
58
- threshold: r.threshold !== undefined ? Number(r.threshold) : undefined,
59
- excludeDirs: Array.isArray(r.exclude_dirs) ? r.exclude_dirs : [],
60
- signatures: Array.isArray(r.signatures) ? r.signatures : [],
61
- requiredPatterns: Array.isArray(r.required_patterns) ? r.required_patterns : [],
62
- },
63
- }),
64
- );
65
-
66
- /* ───────────────────────── 注册:npm 结构化(npm-json,1.0.3) ───────────────────────── */
67
-
68
- /**
69
- * npm 结构化规则(package.json 真实解析判定)。
70
- * 认领条件:显式 kind==='npm-json'(这两条原为「命中即提示」弱 pattern,
71
- * 引擎未实现真实判定 = 死规则;v2 忠实执行导致对任意 package.json 误报)。
72
- * 编译产物:保留 id/severity/message,检查器 checkNpmJson 做 JSON 解析判定。
73
- */
74
- registerCompiler(
75
- 'npm-json',
76
- (r) => r?.kind === 'npm-json',
77
- (r) => ruleOut({
78
- id: r.id, name: r.name || r.id, kind: 'npm-json', severity: r.severity,
79
- level: severityLevel(r.severity),
80
- message: r.description || r.name || '',
81
- dimensions: pickDimensions(r, [DIMENSIONS.可部署性]),
82
- }),
83
- );
84
-
85
- /* ───────────────────────── 注册:拼接产物作用域撞名(dsh 槽位,scope-collision) ───────────────────────── */
86
-
87
- /**
88
- * 拼接产物作用域撞名(多段 JS 拼进同一作用域时 var/function 静默覆盖)。
89
- * 认领条件:显式 kind==='scope-collision'。
90
- *
91
- * 编译产物**故意不带任何项目契约**(前缀 / 顶层零声明 / 产物文件清单):
92
- * 规则包是跨仓库共享的(同一份 yml 审计所有仓库),契约必须取自被审项目自己的
93
- * package.json(lib/audit/scope-policy.js)——写进 yml 会让别人项目也收到
94
- * 「缺少 dshgp_ 前缀」这类与它无关的告警。
95
- * 作用域(exts / exclude_paths / file_patterns)仍走统一补齐(lib/rule/registry.js),
96
- * 本编译器无需自己处理。
97
- */
98
- registerCompiler(
99
- 'scope-collision',
100
- (r) => r?.kind === 'scope-collision',
101
- (r) => ruleOut({
102
- id: r.id, name: r.name || r.id, kind: 'scope-collision', severity: r.severity || 'error',
103
- level: severityLevel(r.severity || 'error'),
104
- message: r.description || r.name || '拼接产物作用域撞名',
105
- dimensions: pickDimensions(r, [DIMENSIONS.健壮性, DIMENSIONS.可维护性]),
106
- }),
107
- );
@@ -1,17 +0,0 @@
1
- /**
2
- * 规则编译器注册表 · 纯引用文件(1.1.4 起)
3
- *
4
- * 本文件历史上是一个 459 行的单文件注册表(16 段 registerCompiler 声明 + 5 个助手
5
- * 全挤在一起,新增一个 kind 要在几百行文件里找位置)。
6
- * 1.1.4 按「域」拆到同目录 compilers/ 下各模块,本文件退化为纯再导出:
7
- * 实现全在 lib/rule/compilers/*.js,本文件不含任何实现。
8
- *
9
- * 保留本文件只为让 `from './rule/compilers.js'` 这类既有 import 路径继续有效。
10
- * 新增一个 kind 的编译器 → 写进 lib/rule/compilers/ 对应域模块。
11
- *
12
- * 注意注册是**副作用**(模块加载时调 registerCompiler):compilers/index.js 里
13
- * 的 import 顺序 = 原文件注册顺序,改动顺序会影响 listRegisteredKinds() 输出次序。
14
- */
15
- import './compilers/index.js';
16
-
17
- export { safeRe, DIMENSIONS, listRegisteredKinds } from './compilers/index.js';
@@ -1,45 +0,0 @@
1
- /**
2
- * dsh-git-push 同形字符检测(G3 防再犯,1.0.4)
3
- *
4
- * 背景:规则 yml 的 kind/id 是引擎匹配键(registerCompiler 的 kind 用 ASCII 注册)。
5
- * 若 yml 里 kind/id 夹带西里尔/希腊同形字符(如 с→c、е→e、а→a),视觉上几乎相同,
6
- * 但 `RULE_COMPILERS.find(e => e.kind === rule.kind)` 匹配不上 → 规则静默失效(编译报
7
- * 「未知规则类型」或字段探测落空),且无任何提示。本模块在 compileRule 入口检测,
8
- * 把「静默失效」变为「显式报错」。
9
- *
10
- * 用法:findHomoglyphs('credential-ref') → [{ ch:'с', ascii:'c', index:1 }](空数组=纯 ASCII)
11
- */
12
- export const HOMOGLYPH_MAP = {
13
- // 西里尔(Cyrillic,U+0400–U+04FF)→ 视觉同形 ASCII
14
- 'а': 'a', 'б': 'b', 'д': 'd', 'е': 'e', 'о': 'o', 'р': 'p', 'с': 'c',
15
- 'у': 'y', 'х': 'x', 'в': 'B', 'г': 'r', 'з': '3', 'н': 'H', 'к': 'K',
16
- 'м': 'M', 'т': 'T', 'і': 'i', 'ѕ': 's', 'ј': 'j', 'ɡ': 'g',
17
- // 希腊(Greek,U+0370–U+03FF)→ 视觉同形 ASCII
18
- 'α': 'a', 'ο': 'o', 'ρ': 'p', 'σ': 'o', 'τ': 't', 'ν': 'v', 'χ': 'x',
19
- 'ε': 'e', 'κ': 'k', 'μ': 'm', 'ι': 'i', 'β': 'B', 'δ': 'D', 'γ': 'y',
20
- // 常用混淆(易误录)
21
- 'İ': 'I', 'ı': 'i', 'ł': 'l', 'ø': 'o', 'Ø': 'O', 'æ': 'ae',
22
- };
23
-
24
- /** 组合正则:匹配任一非 ASCII 同形字符。 */
25
- export const HOMOGLYPH_RE = new RegExp(`[${Object.keys(HOMOGLYPH_MAP).join('')}]`, 'g');
26
-
27
- /**
28
- * 检测字符串中的同形字符。
29
- * @param {string} text 待检文本(如规则 id / kind)
30
- * @returns {Array<{ch:string, ascii:string, index:number}>} 命中列表(空=纯 ASCII)
31
- */
32
- export function findHomoglyphs(text) {
33
- if (typeof text !== 'string' || !text) return [];
34
- const hits = [];
35
- for (let i = 0; i < text.length; i++) {
36
- const ch = text[i];
37
- if (HOMOGLYPH_MAP[ch]) hits.push({ ch, ascii: HOMOGLYPH_MAP[ch], index: i });
38
- }
39
- return hits;
40
- }
41
-
42
- /** 检测文本是否含非 ASCII 同形字符(布尔,供文件级扫描用)。 */
43
- export function hasHomoglyphs(text) {
44
- return typeof text === 'string' && HOMOGLYPH_RE.test(text);
45
- }
@@ -1,274 +0,0 @@
1
- // dsh-skip-sensitive: FORCE_LOAD_FALLBACK 含私密文件清单声明(凭据路径数据定义,非文档引用旧位置)
2
- /**
3
- * dsh-git-push 规则总入口:yml 装载与解析
4
- *
5
- * 统一装载所有 yml 规则槽位(nodejs/npm/html/frontend/comment/dsh/private/structure/version/template 等),
6
- * 支持 yml 衍生新字段(编译函数按字段指派,见 ./registry.js)。
7
- */
8
- import { readFileSync, readdirSync, existsSync, writeFileSync } from 'node:fs';
9
- import { normalizeScopeRules } from './scope.js';
10
- import { join, dirname } from 'node:path';
11
- import { fileURLToPath } from 'node:url';
12
- // js-yaml 走 npm 依赖(仓库内不保存副本)。
13
- // 这里**故意用静态 import**:规则加载是启动关键路径,依赖没装上就应当在模块加载期
14
- // 抛 ERR_MODULE_NOT_FOUND(错误里带包名,够响亮),而不是被 try/catch 吞成「0 条规则」
15
- // 继续跑——静默无规则比启动失败更危险(口径见 docs/2026-10-28-弃零依赖引入npm与AST优先规则方案.MD D5)。
16
- import { load as yamlLoad } from 'js-yaml';
17
-
18
- const __dirname = dirname(fileURLToPath(import.meta.url));
19
- export const RULE_YAML_DIR = join(__dirname, '..', 'audit-rules');
20
-
21
- /**
22
- * 核心槽位优先级提示(**不是全量清单,禁止补成全部槽位**)。
23
- *
24
- * 槽位集合全动态:放一个 audit-rules-<名>.yml 进目录就自动成为槽位,
25
- * 无需改代码——见 discoverRuleSlots()。本常量只用于把高频核心槽位排到前面,
26
- * **只维护核心子集即可**;新增/未列出的槽位由 resolveSlotOrder 按文件名字典序
27
- * 自动追加到末尾,加槽位零改动(放 yml 即生效)。
28
- */
29
- export const SLOT_ORDER_HINT = ['nodejs', 'frontend', 'npm', 'comment', 'dsh', 'structure', 'private', 'template'];
30
-
31
- /**
32
- * 强制加载槽位(1.1.0,disabled 无法关闭的安全红线):
33
- * - nodejs:含凭据/硬编码/路径穿越等安全规则(secret-*、cred*、security/*),不可被 yml 关闭
34
- * - private:私密文件拦截(独立通道,天然强制)
35
- * 即使槽位 yml 顶层标 `disabled: true` 也强制加载(环境变量显式列出同样生效)。
36
- */
37
- export const FORCE_LOAD_SLOTS = new Set(['nodejs', 'private']);
38
-
39
- /**
40
- * 强制加载规则前缀(1.1.0):规则条目即使标 `disabled: true` 也保留——
41
- * 凭据/硬编码/私密引用类安全红线不允许被 yml 关闭。
42
- * 覆盖:secret-*(github-pat/openai-key/keyvalue/email/aws-access-key/generic-token)、
43
- * credfile-* 与 credref-*(凭据文件/引用)、security/*(路径穿越/硬编码凭据/求值)、
44
- * npm/npmrc-authtoken(.npmrc 凭据)、dsh/schema-secret-*(schema 凭据字段)。
45
- * @param {string} ruleId 规则 id
46
- * @returns {boolean} true=强制加载(无视 disabled)
47
- */
48
- export function isForceLoadRule(ruleId) {
49
- return /^(secret-|cred(file|ref)?-|security\/|npm\/npmrc-authtoken|dsh\/schema-secret)/.test(String(ruleId || ''));
50
- }
51
-
52
- /**
53
- * 强制加载槽位内置兜底规则(1.1.0):文件丢失/被删时安全审计不断档——
54
- * 凭据/硬编码/路径穿越类最小安全集 + 私密文件清单(与 audit-rules-nodejs.yml /
55
- * audit-rules-private.yml 语义一致的精简版)。加载时若发现强制槽位文件缺失,
56
- * 用本兜底合并进规则集并记入 errors(CLI/工具可感知「规则包不完整」)。
57
- */
58
- export const FORCE_LOAD_FALLBACK = {
59
- nodejs: [
60
- {
61
- id: 'secret-generic-token', name: '疑似凭据 token 硬编码', category: 'security',
62
- severity: 'error', description: '疑似 token/secret 硬编码(内置兜底,规则文件缺失)',
63
- pattern: '\\b(?:ghp_|gho_|ghu_|ghs_|ghr_|github_pat_|sk-)[A-Za-z0-9_-]{15,}\\b', fixable: false,
64
- },
65
- {
66
- id: 'security/no-hardcoded-credentials', name: '禁止硬编码凭据', category: 'security',
67
- severity: 'error', description: '凭据不应硬编码在源代码中(内置兜底,规则文件缺失)',
68
- patterns: [
69
- 'password\\s*[=:]+\\s*[\'"][^\'"]+[\'"]',
70
- 'secret\\s*[=:]+\\s*[\'"][^\'"]+[\'"]',
71
- 'api[_-]?key\\s*[=:]+\\s*[\'"][^\'"]+[\'"]',
72
- 'token\\s*[=:]+\\s*[\'"][^\'"]+[\'"]',
73
- ],
74
- fixable: false,
75
- },
76
- {
77
- id: 'security/no-path-traversal', name: '路径穿越防护', category: 'security',
78
- severity: 'error', description: '直接使用用户输入作为文件路径存在目录遍历风险(内置兜底,规则文件缺失)',
79
- fixable: false,
80
- },
81
- ],
82
- private_files: [
83
- '**/id_ed25519', '**/id_rsa', '**/*.pem', '**/*.key', '**/github-token',
84
- '**/.git-push-token', '**/.env', '**/.env.*', '**/data/sensitive/**',
85
- '**/.ssh/**', '**/.dsh/git-push/**', '**/.npmrc',
86
- ],
87
- };
88
-
89
- /**
90
- * @deprecated 兼容旧调用:等于槽位排序偏好。槽位集合请用 discoverRuleSlots()。
91
- */
92
- export const RULE_SLOTS = SLOT_ORDER_HINT;
93
-
94
- /**
95
- * 读取单个槽位 yml(纯数据,不做合并)。
96
- * @returns {{ok:true, data:object, file:string} | {ok:false, error:string}}
97
- */
98
- export function loadYamlRuleFile(slot, dir = RULE_YAML_DIR) {
99
- const file = join(dir, `audit-rules-${slot}.yml`);
100
- try {
101
- if (!existsSync(file)) return { ok: false, error: `规则文件缺失: ${file}` };
102
- const parsed = yamlLoad(readFileSync(file, 'utf8'));
103
- return { ok: true, data: parsed || { rules: [] }, file };
104
- } catch (e) {
105
- return { ok: false, error: `规则文件解析失败 ${slot}: ${e.message}` };
106
- }
107
- }
108
-
109
- /**
110
- * 发现目录下的全部规则槽位文件(含新增 yml 自动生效)。
111
- */
112
- export function discoverRuleSlots(dir = RULE_YAML_DIR) {
113
- try {
114
- return readdirSync(dir)
115
- .filter((f) => f.startsWith('audit-rules-') && f.endsWith('.yml'))
116
- .map((f) => f.replace(/^audit-rules-/, '').replace(/\.yml$/, ''));
117
- } catch {
118
- return [];
119
- }
120
- }
121
-
122
- /**
123
- * 解析生效槽位顺序(**全动态**:槽位集合由目录内的规则文件决定)。
124
- *
125
- * 规则:
126
- * 1) 槽位集合 = 目录里实际存在的 `audit-rules-<名>.yml`(放文件即生效,无需改代码)
127
- * 2) 顺序 = 配置若给了顺序则按配置;否则按 SLOT_ORDER_HINT 偏好排序,未列出的按字典序追加
128
- * 3) 配置声明的槽位若文件不存在 → 静默跳过(不报缺失,方便先写配置后放文件)
129
- * 4) template 槽位默认不加载(模板保持为空,不进默认装载)
130
- *
131
- * @param {string[]|string} [order] 配置指定的槽位顺序(数组或逗号分隔字符串)
132
- * @param {object} [opts] { dir, includeTemplate=false }
133
- * @returns {string[]} 最终槽位顺序
134
- */
135
- export function resolveSlotOrder(order = null, { dir = RULE_YAML_DIR, includeTemplate = false } = {}) {
136
- const discovered = discoverRuleSlots(dir);
137
- const allowed = new Set(discovered);
138
- let configured = order;
139
- if (!configured && process.env.DSH_GIT_PUSH_RULE_SLOTS) {
140
- configured = String(process.env.DSH_GIT_PUSH_RULE_SLOTS);
141
- }
142
- if (typeof configured === 'string') {
143
- configured = configured.split(',').map((s) => s.trim()).filter(Boolean);
144
- }
145
- const hasConfig = Array.isArray(configured) && configured.length > 0;
146
- const seen = new Set();
147
- const out = [];
148
- const push = (slot) => {
149
- if (!slot || seen.has(slot)) return;
150
- // 强制加载槽位(nodejs/private):即使目录里文件缺失也进入装载列表(loadRuleFiles 兜底),
151
- // 保证安全红线不因规则包被删/目录指向错误而静默消失
152
- if (!allowed.has(slot) && !FORCE_LOAD_SLOTS.has(slot)) return;
153
- if (slot === 'template' && !includeTemplate) return;
154
- seen.add(slot);
155
- out.push(slot);
156
- };
157
- if (hasConfig) {
158
- // 配置顺序优先(配置里没有但目录存在的,随后按偏好补上)
159
- for (const slot of configured) push(slot);
160
- }
161
- // 动态发现:按排序偏好排,未列在偏好里的按字典序追加
162
- const hintRest = SLOT_ORDER_HINT.filter((s) => !seen.has(s));
163
- for (const slot of hintRest) push(slot);
164
- for (const slot of [...discovered].sort()) push(slot);
165
- return out;
166
- }
167
-
168
- /**
169
- * 按顺序装载并合并多个槽位(后覆盖前)。
170
- * @param {string[]|string} [order] 槽位顺序(缺省走 resolveSlotOrder 配置驱动解析)
171
- *
172
- * disabled 机制(1.1.0):
173
- * 1) 文件级:yml 顶层 `disabled: true` → 整槽位默认不加载(如 audit-rules-i18n.yml 默认关)。
174
- * 例外:环境变量 DSH_GIT_PUSH_RULE_SLOTS 显式列出该槽位 → 强制加载(显式指定即开)。
175
- * 2) 规则级:单条规则 `disabled: true` → 该条规则不编译(合并时直接过滤,无需删/改文件)。
176
- */
177
- export function loadRuleFiles(order = null, opts = {}) {
178
- const dir = opts.dir || RULE_YAML_DIR;
179
- const slots = Array.isArray(order) ? order : resolveSlotOrder(order, { dir });
180
- // UI 禁用槽位:设置页单击禁用 → 装载最前过滤;
181
- // nodejs/private 属 FORCE_LOAD_SLOTS 安全红线,UI 禁用不生效(后端强制加载)。
182
- const uiDisabled = new Set(Array.isArray(opts.disabledSlots) ? opts.disabledSlots.filter(Boolean) : []);
183
- // 修复 explicit 误伤:显式强制名单**只认环境变量 DSH_GIT_PUSH_RULE_SLOTS**
184
- // (用户点名要强制开启的槽位),不再把调用方传的 order/settings.auditRuleOrder 当强制名单——
185
- // 否则 auditRuleOrder 全量 14 个会被当 explicit,yml 顶层 disabled:true 全部失效(i18n 默认关闭被误加载)。
186
- const explicit = new Set(
187
- String(process.env.DSH_GIT_PUSH_RULE_SLOTS || '')
188
- .split(',').map((s) => s.trim()).filter(Boolean),
189
- );
190
- const errors = [];
191
- const files = [];
192
- const merged = { metadata: {}, rules: [], severity_map: {}, thresholds: {}, ignore: [], private_files: [] };
193
- for (const slot of slots) {
194
- // UI 单击禁用优先:该槽位任何规则都不加载(安全红线槽位除外)
195
- if (uiDisabled.has(slot) && !FORCE_LOAD_SLOTS.has(slot)) continue;
196
- const r = loadYamlRuleFile(slot, dir);
197
- if (!r.ok) {
198
- // 强制加载槽位(nodejs/private)文件缺失 → 内置兜底,安全审计不断档 + 显式记录
199
- if (FORCE_LOAD_SLOTS.has(slot)) {
200
- if (slot === 'nodejs') merged.rules.push(...FORCE_LOAD_FALLBACK.nodejs);
201
- else merged.private_files.push(...FORCE_LOAD_FALLBACK.private_files);
202
- errors.push(`强制加载槽位 ${slot} 规则文件缺失(${r.error})——已用内置兜底规则集,建议恢复 audit-rules-${slot}.yml`);
203
- continue;
204
- }
205
- errors.push(r.error); continue;
206
- }
207
- // 文件级 disabled:yml 顶层 disabled:true 且未被显式列出且非强制加载槽位 → 跳过整槽位
208
- if (r.data?.disabled === true && !explicit.has(slot) && !FORCE_LOAD_SLOTS.has(slot)) continue;
209
- files.push(r.file);
210
- const ruleData = r.data;
211
- if (ruleData?.metadata && !merged.metadata.name) merged.metadata = ruleData.metadata;
212
- // 规则级 disabled:合并前过滤 disabled:true 条目(安全红线规则 isForceLoadRule 强制保留)
213
- // 逐条打 __slot 归属标记——按规则包聚合审计命中数(侧边栏规则包行的
214
- // 「拦截/警告/通过」显示该规则包的实际命中数)。__slot 用下划线前缀避免与 yml 字段冲突。
215
- merged.rules.push(...(Array.isArray(ruleData?.rules)
216
- ? ruleData.rules.filter((x) => x?.disabled !== true || isForceLoadRule(x.id))
217
- .map((x) => (x && typeof x === 'object' ? { ...x, __slot: slot, scopeRules: normalizeScopeRules(x) } : x))
218
- : []));
219
- Object.assign(merged.severity_map, ruleData?.severity_map || {});
220
- Object.assign(merged.thresholds, ruleData?.thresholds || {});
221
- merged.ignore.push(...(Array.isArray(ruleData?.ignore) ? ruleData.ignore : []));
222
- // 私密拦截清单跨文件追加(强制槽位 private.yml 永远最后加载 → 天然追加)
223
- if (Array.isArray(ruleData?.private_files)) merged.private_files.push(...ruleData.private_files);
224
- }
225
- return { ok: errors.length === 0, merged, order: slots, files, errors };
226
- }
227
-
228
- /**
229
- * 设置/取消槽位的 yml 顶层 `disabled`(约定:启用/禁用以 yml 解析,不单独存变量)。
230
- *
231
- * 文本级操作(保留文件内注释与其它内容,不用 js-yaml dump 避免丢注释):
232
- * - 启用:删除顶层 `disabled:` 行
233
- * - 禁用:已存在 → 值改为 true;不存在 → 在 metadata 前插入 `disabled: true`
234
- * nodejs/private 强制加载槽位禁止禁用(安全红线,由调用方拒绝,此处同样防御)。
235
- * @param {string} slot 槽位名
236
- * @param {boolean} disabled 目标状态
237
- * @param {object} [opts] { dir }
238
- * @returns {{ok: boolean, disabled: boolean, error?: string}}
239
- */
240
- export function setSlotDisabled(slot, disabled, opts = {}) {
241
- const dir = opts.dir || RULE_YAML_DIR;
242
- if (FORCE_LOAD_SLOTS.has(slot)) {
243
- return { ok: false, error: `${slot} 属安全红线强制槽位,不可通过 UI 禁用` };
244
- }
245
- const file = join(dir, `audit-rules-${slot}.yml`);
246
- if (!existsSync(file)) return { ok: false, error: `规则文件缺失: ${file}` };
247
- const text = readFileSync(file, 'utf8');
248
- // 顶层 disabled(无缩进)行:^disabled: [true|false],多行匹配
249
- const re = /^disabled:\s*(true|false)\s*$/m;
250
- let out;
251
- if (disabled) {
252
- if (re.test(text)) out = text.replace(re, 'disabled: true');
253
- else {
254
- // 在第一个非注释、非空行(通常是 metadata:)之前插入
255
- const lines = text.split('\n');
256
- let idx = lines.findIndex((l) => l.trim() && !l.trim().startsWith('#'));
257
- if (idx < 0) idx = lines.length;
258
- lines.splice(idx, 0, 'disabled: true');
259
- out = lines.join('\n');
260
- }
261
- } else {
262
- // 修复污染:删除整行(含行尾换行),不能只删 `disabled: true` 内容——
263
- // 否则残留的 \n 会留下一个空行(folder.yml/i18n.yml 曾被误加空行)。
264
- out = re.test(text) ? text.replace(/^disabled:\s*(true|false)\s*$\n?/m, '') : text;
265
- // 清理可能留下的多空行粘连(保留单个空行语义)
266
- out = out.replace(/\n\s*\n\s*\n/g, '\n\n');
267
- }
268
- try {
269
- writeFileSync(file, out, 'utf8');
270
- } catch (e) {
271
- return { ok: false, error: `写入失败: ${e.message}` };
272
- }
273
- return { ok: true, disabled };
274
- }
@@ -1,122 +0,0 @@
1
- /**
2
- * dsh-git-push 规则总入口(核心)
3
- *
4
- * 铁律:加字段 = 加函数 + registerCompiler 一行注册;compileRule 主体永不修改。
5
- * 判定方式:不强制 yml 写 kind,按字段自动指派编译函数(detect 条件)。
6
- * 每个编译函数声明 dimensions(10 维度绑定,支持一字段多维度)。
7
- */
8
- import { findHomoglyphs } from './homoglyph.js';
9
-
10
- export const RULE_COMPILERS = [];
11
-
12
- /**
13
- * 注册一个规则编译函数。
14
- * @param {string} kind kebab-case 规则类型(如 'max-depth')
15
- * @param {(rule)=>boolean} detect 认领条件(规则条目满足即归本编译函数)
16
- * @param {(rule, ctx)=>any} compile 编译函数,返回 { ok:true, rule } 或 { ok:false, error }
17
- */
18
- export function registerCompiler(kind, detect, compile) {
19
- RULE_COMPILERS.push({ kind, detect, compile });
20
- }
21
-
22
- /**
23
- * 统一规则编译入口:遍历注册表,detect 命中 → compile。
24
- * 显式 kind 字段优先;无 kind 则字段探测。
25
- * @param {object} rule yml 规则条目
26
- * @param {object} ctx { errors, label } 编译上下文
27
- */
28
- export function compileRule(rule, ctx = {}) {
29
- // G3 防再犯:kind/id 夹带同形字符(с→c/е→e/а→a 等)→ 匹配不上注册表,
30
- // 静默失效零提示。入口显式拦截:检出同形 → 报错(不进入 detect/compile)。
31
- for (const key of ['kind', 'id']) {
32
- if (typeof rule?.[key] !== 'string') continue;
33
- const hits = findHomoglyphs(rule[key]);
34
- if (hits.length) {
35
- const detail = hits.map((h) => `「${h.ch}」→${h.ascii}@${h.index}`).join(' ');
36
- return { ok: false, error: `${key}=${rule[key]} 含同形字符(${detail}),须用纯 ASCII(可复制正确写法或人工重敲)` };
37
- }
38
- }
39
- // 槽位归属透传——loader 给每条 yml 规则打了 __slot(来源规则包),
40
- // 编译结果统一补 slot 字段,供审计结果按规则包聚合命中数
41
- // (侧边栏规则包行的「拦截/警告/通过」= 该规则包实际命中的问题数)。
42
- const slot = typeof rule?.__slot === 'string' ? rule.__slot : undefined;
43
- const withSlot = (res) => {
44
- if (res && res.ok && res.rule) {
45
- if (slot && res.rule.slot === undefined) res.rule.slot = slot;
46
- // 试点:external 透传(yml external: true 的规则编译后保留——
47
- // groupByKind 据此内置停跑,由 audit-ext 统一动态入口执行)
48
- if (res.rule.external === undefined && rule.external !== undefined) res.rule.external = rule.external;
49
- }
50
- return res;
51
- };
52
- if (rule?.kind) {
53
- const byKind = RULE_COMPILERS.find((e) => e.kind === rule.kind);
54
- if (byKind) return withSlot(byKind.compile(rule, ctx));
55
- return { ok: false, error: `未知规则类型 kind=${rule.kind}(${rule?.id || rule?.name})` };
56
- }
57
- for (const entry of RULE_COMPILERS) {
58
- if (entry.detect(rule)) return withSlot(entry.compile(rule, ctx));
59
- }
60
- return { ok: false, error: `无法识别规则类型: ${rule?.id || rule?.name || '?'}` };
61
- }
62
-
63
- /** 编译全部规则条目(阶段3 统一入口的循环形态)。 */
64
- export function compileAllRules(rules, ctx = {}) {
65
- const out = [];
66
- for (const r of rules || []) {
67
- const compiled = compileRule(r, ctx);
68
- if (compiled.ok) out.push(withRuleScope(compiled.rule, r));
69
- else ctx.errors?.push(compiled.error);
70
- }
71
- return out;
72
- }
73
-
74
- /**
75
- * 统一补齐规则作用域字段(exts + astConfirmKind)——。
76
- *
77
- * 背景(真实缺陷):`exts` 原本要求每个编译器自己归一化后塞进 `extra` 透传,
78
- * 16 个编译器里 10 个漏了(credential-ref/[FUNC]/semantic/blacklist/npm-json 等)。
79
- * 后果是 yml 里写了 `exts` 却被**静默忽略**——规则照旧跑遍所有文本文件,
80
- * 产生误报且看不出原因(实例:comment 包的 blacklist 规则声明了只查代码/HTML,
81
- * 仍把 .json 配置文件的流程约定报成 blocker,卡死提交门禁)。
82
- *
83
- * 放在这里而不是各编译器:作用域是规则的通用属性,与具体 kind 无关;
84
- * 统一收口后新增编译器自动具备,不会再漏。已在编译器内显式归一化的保持不变。
85
- *
86
- * @param compiled 编译产物(顶层 exts 或 extra.exts 均可被 filterRulesByExt 读取)
87
- * @param source 原始 yml 规则
88
- */
89
- function withRuleScope(compiled, source) {
90
- if (!compiled) return compiled;
91
- let out = compiled;
92
- const patch = (obj, key, value) => (out = out === obj ? { ...obj, [key]: value } : { ...out, [key]: value });
93
-
94
- // ① 文件作用域 exts
95
- if (!(Array.isArray(out.exts) && out.exts.length) && Array.isArray(source?.exts) && source.exts.length) {
96
- patch(out, 'exts', source.exts.map((x) => String(x).toLowerCase().replace(/^\./, '')));
97
- }
98
- // ② 具名精筛 astConfirmKind —— 与 exts 同类缺陷:原本只有 regex 编译器透传,
99
- // [FUNC]/blacklist/semantic 等 kind 声明了也被静默忽略(实例:secret-github-pat
100
- // 编译成 [FUNC],声明的 placeholder-credential 精筛不生效,占位符仍被报泄漏)。
101
- if (out.astConfirmKind === undefined && source?.astConfirmKind) {
102
- patch(out, 'astConfirmKind', source.astConfirmKind);
103
- }
104
- // ③ 作用域规则 scope_rules —— 与上面 ①exts / ②astConfirmKind **同类缺陷**:
105
- // loader 已把 yml 的 scope_rules 规范化为 source.scopeRules(lib/rule/loader.js),
106
- // 但编译器重建规则对象时只透传了 exts/astConfirmKind,scopeRules 被丢弃
107
- // ⇒ yml 里声明的 scope_rules 在生产中**静默失效**。
108
- // 实测影响:startup/serialization 的 exempt(max-function-length / max-complexity 等)
109
- // 与 DSH 客户端单文件的 downgrade **全都不生效**,看起来只有检查器里的兜底在起作用。
110
- if (!(Array.isArray(out.scopeRules) && out.scopeRules.length)) {
111
- const srcScope = source?.scopeRules || source?.scope_rules;
112
- if (Array.isArray(srcScope) && srcScope.length) patch(out, 'scopeRules', srcScope);
113
- }
114
- // ④ 列级精筛 astConfirmSpan(2026-10-15 新增)—— 与上面 ①②③ **完全同类**的缺陷:
115
- // 新字段只在 regex 编译器里透传,而编译器重建规则对象时又会丢 ⇒ 生产路径读不到、
116
- // 列级过滤静默失效(实测:单元测试直连过滤器时通过,端到端审计仍照旧误报 ✗)。
117
- // 语义:只有显式 true 才开启列级过滤(其余一律不做,避免误杀"命中本来就该在字符串里"的规则)。
118
- if (out.astConfirmSpan === undefined && source?.astConfirmSpan !== undefined) {
119
- patch(out, 'astConfirmSpan', source.astConfirmSpan === true);
120
- }
121
- return out;
122
- }