dsh-git-push 0.0.0-stage → 2.8.4

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 (278) hide show
  1. package/.auditignore +30 -0
  2. package/.gitignore +39 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1482 -2
  5. package/cli.mjs +360 -0
  6. package/cordis.patch.yml +14 -0
  7. package/lib/ARCHITECTURE.md +34 -0
  8. package/lib/BUGFIX-NOTES-2026-09-14.md +278 -0
  9. package/lib/app/apply.js +275 -0
  10. package/lib/app/audit-api.js +158 -0
  11. package/lib/app/command-registry.js +262 -0
  12. package/lib/app/constants.js +16 -0
  13. package/lib/app/handlers/account.js +166 -0
  14. package/lib/app/handlers/clone.js +168 -0
  15. package/lib/app/handlers/http-constants.js +9 -0
  16. package/lib/app/handlers/identity-rewrite.js +94 -0
  17. package/lib/app/handlers/meta.js +175 -0
  18. package/lib/app/handlers/npm.js +169 -0
  19. package/lib/app/handlers/repo-actions.js +143 -0
  20. package/lib/app/handlers/repos.js +231 -0
  21. package/lib/app/handlers/settings.js +62 -0
  22. package/lib/app/host-doc-checks.js +25 -0
  23. package/lib/app/http-handlers.js +131 -0
  24. package/lib/app/index.js +30 -0
  25. package/lib/app/inject-text.js +191 -0
  26. package/lib/app/scan-root.js +23 -0
  27. package/lib/app/schema.js +150 -0
  28. package/lib/app/settings-bridge.js +167 -0
  29. package/lib/app/slash-commands.js +395 -0
  30. package/lib/app/slot-stats.js +35 -0
  31. package/lib/app/tool-call.js +662 -0
  32. package/lib/app/tools.js +40 -0
  33. package/lib/ast/brace.js +105 -0
  34. package/lib/ast/callgraph.js +135 -0
  35. package/lib/ast/code-lines.js +114 -0
  36. package/lib/ast/consts.js +12 -0
  37. package/lib/ast/control-flow.js +461 -0
  38. package/lib/ast/credential.js +199 -0
  39. package/lib/ast/dataflow.js +274 -0
  40. package/lib/ast/dup-code.js +165 -0
  41. package/lib/ast/index.js +36 -0
  42. package/lib/ast/io-risk-const.js +95 -0
  43. package/lib/ast/io-risk-fn.js +208 -0
  44. package/lib/ast/io-risk-loop.js +308 -0
  45. package/lib/ast/io-risk.js +314 -0
  46. package/lib/ast/lang.js +156 -0
  47. package/lib/ast/line-count.js +52 -0
  48. package/lib/ast/magic-number.js +272 -0
  49. package/lib/ast/naming.js +284 -0
  50. package/lib/ast/perf.js +472 -0
  51. package/lib/ast/scope.js +241 -0
  52. package/lib/ast/shell.js +131 -0
  53. package/lib/ast/size.js +378 -0
  54. package/lib/ast/symbol-index.js +399 -0
  55. package/lib/ast/tokenizer.js +341 -0
  56. package/lib/audit/analysis-coverage.js +98 -0
  57. package/lib/audit/audit-file.js +182 -0
  58. package/lib/audit/checks.js +17 -0
  59. package/lib/audit/client-entry.js +93 -0
  60. package/lib/audit/collector.js +477 -0
  61. package/lib/audit/ext-runner.js +80 -0
  62. package/lib/audit/file-context.js +138 -0
  63. package/lib/audit/finding.js +50 -0
  64. package/lib/audit/gitignore-match.js +113 -0
  65. package/lib/audit/glob.js +63 -0
  66. package/lib/audit/history-report.js +100 -0
  67. package/lib/audit/history.js +126 -0
  68. package/lib/audit/ignore-blind.js +101 -0
  69. package/lib/audit/index.js +33 -0
  70. package/lib/audit/orchestrate.js +476 -0
  71. package/lib/audit/public.js +24 -0
  72. package/lib/audit/repo-level.js +30 -0
  73. package/lib/audit/report-yaml.js +86 -0
  74. package/lib/audit/slot.js +65 -0
  75. package/lib/audit-defaults.js +18 -0
  76. package/lib/audit-rules/audit-rules-comment.yml +247 -0
  77. package/lib/audit-rules/audit-rules-cpp.yml +22 -0
  78. package/lib/audit-rules/audit-rules-docs.yml +32 -0
  79. package/lib/audit-rules/audit-rules-dsh.yml +162 -0
  80. package/lib/audit-rules/audit-rules-filehealth.yml +42 -0
  81. package/lib/audit-rules/audit-rules-folder.yml +99 -0
  82. package/lib/audit-rules/audit-rules-frontend.yml +335 -0
  83. package/lib/audit-rules/audit-rules-go.yml +22 -0
  84. package/lib/audit-rules/audit-rules-i18n.yml +45 -0
  85. package/lib/audit-rules/audit-rules-java.yml +105 -0
  86. package/lib/audit-rules/audit-rules-nodejs.yml +647 -0
  87. package/lib/audit-rules/audit-rules-npm.yml +187 -0
  88. package/lib/audit-rules/audit-rules-paths.yml +92 -0
  89. package/lib/audit-rules/audit-rules-performance.yml +207 -0
  90. package/lib/audit-rules/audit-rules-php.yml +22 -0
  91. package/lib/audit-rules/audit-rules-private.yml +24 -0
  92. package/lib/audit-rules/audit-rules-python.yml +106 -0
  93. package/lib/audit-rules/audit-rules-robustness.yml +27 -0
  94. package/lib/audit-rules/audit-rules-rust.yml +22 -0
  95. package/lib/audit-rules/audit-rules-structure.yml +159 -0
  96. package/lib/audit-rules/audit-rules-swift.yml +22 -0
  97. package/lib/audit-rules/audit-rules-template.yml +108 -0
  98. package/lib/checks/button-bind.js +276 -0
  99. package/lib/checks/common.js +170 -0
  100. package/lib/checks/credential-file.js +43 -0
  101. package/lib/checks/dataflow.js +40 -0
  102. package/lib/checks/dispatch.js +112 -0
  103. package/lib/checks/dup-code.js +69 -0
  104. package/lib/checks/dup-const.js +232 -0
  105. package/lib/checks/file-health.js +150 -0
  106. package/lib/checks/filter.js +131 -0
  107. package/lib/checks/folder.js +173 -0
  108. package/lib/checks/hardcoded-path.js +98 -0
  109. package/lib/checks/index.js +46 -0
  110. package/lib/checks/io.js +66 -0
  111. package/lib/checks/magic-number.js +42 -0
  112. package/lib/checks/npm-json.js +273 -0
  113. package/lib/checks/private.js +63 -0
  114. package/lib/checks/regex.js +256 -0
  115. package/lib/checks/semantic.js +134 -0
  116. package/lib/checks/structural.js +274 -0
  117. package/lib/cli/commands-account.mjs +107 -0
  118. package/lib/cli/commands-audit.mjs +144 -0
  119. package/lib/cli/commands-doc.mjs +127 -0
  120. package/lib/cli/commands-vcs.mjs +175 -0
  121. package/lib/client/index.js +162 -0
  122. package/lib/client-parts/00-loader.js +33 -0
  123. package/lib/client-parts/01-const.js +207 -0
  124. package/lib/client-parts/02-utils.js +62 -0
  125. package/lib/client-parts/03-icons.js +12 -0
  126. package/lib/client-parts/10-account.js +83 -0
  127. package/lib/client-parts/11-browser.js +95 -0
  128. package/lib/client-parts/20-repo.js +374 -0
  129. package/lib/client-parts/21-audit.js +301 -0
  130. package/lib/client-parts/22-settings.js +146 -0
  131. package/lib/client-parts/23-npm.js +383 -0
  132. package/lib/client-parts/30-page.js +56 -0
  133. package/lib/client-parts/40-controller.js +1092 -0
  134. package/lib/client-parts/41-actions.js +279 -0
  135. package/lib/client-parts/99-apply.js +72 -0
  136. package/lib/client.js +3195 -0
  137. package/lib/commit-push.js +144 -0
  138. package/lib/context/index.js +363 -0
  139. package/lib/core/atomic-json.js +98 -0
  140. package/lib/core/config.js +40 -0
  141. package/lib/core/credentials.js +274 -0
  142. package/lib/core/endpoints.js +109 -0
  143. package/lib/core/exec.js +162 -0
  144. package/lib/exempt/index.js +292 -0
  145. package/lib/fs/edit-after-read.js +103 -0
  146. package/lib/fsx.js +87 -0
  147. package/lib/git/account-status.js +140 -0
  148. package/lib/git/account.js +233 -0
  149. package/lib/git/api.js +136 -0
  150. package/lib/git/atomic-json.js +6 -0
  151. package/lib/git/browse.js +38 -0
  152. package/lib/git/clone-download.js +397 -0
  153. package/lib/git/clone-history-mode.js +143 -0
  154. package/lib/git/clone-history.js +175 -0
  155. package/lib/git/clone-jobs.js +250 -0
  156. package/lib/git/clone-replay-io.js +172 -0
  157. package/lib/git/clone-replay.js +275 -0
  158. package/lib/git/clone.js +445 -0
  159. package/lib/git/cloud.js +46 -0
  160. package/lib/git/commit-message.js +141 -0
  161. package/lib/git/config.js +6 -0
  162. package/lib/git/cred-env.js +88 -0
  163. package/lib/git/credentials.js +6 -0
  164. package/lib/git/endpoints.js +6 -0
  165. package/lib/git/exec.js +6 -0
  166. package/lib/git/identity-rewrite.js +297 -0
  167. package/lib/git/identity.js +150 -0
  168. package/lib/git/ignore.js +69 -0
  169. package/lib/git/index.js +41 -0
  170. package/lib/git/module-splitter.js +47 -0
  171. package/lib/git/post-push.js +101 -0
  172. package/lib/git/push-diagnose.js +142 -0
  173. package/lib/git/push.js +470 -0
  174. package/lib/git/remote-resolve.js +146 -0
  175. package/lib/git/remote.js +128 -0
  176. package/lib/git/repo-index.js +512 -0
  177. package/lib/git/repos.js +235 -0
  178. package/lib/git/scan-runner.js +159 -0
  179. package/lib/git/sensitive.js +134 -0
  180. package/lib/git/transport.js +430 -0
  181. package/lib/git/visibility.js +35 -0
  182. package/lib/git/wrapped-git.js +68 -0
  183. package/lib/http/index.js +170 -0
  184. package/lib/index.js +24 -0
  185. package/lib/link-check/index.js +187 -0
  186. package/lib/npm/account.js +64 -0
  187. package/lib/npm/install.js +211 -0
  188. package/lib/npm/npmrc.js +56 -0
  189. package/lib/npm/publish.js +167 -0
  190. package/lib/npm/registry.js +147 -0
  191. package/lib/plugin/auto-detect.js +92 -0
  192. package/lib/plugin/auto-push.js +154 -0
  193. package/lib/plugin/index.js +250 -0
  194. package/lib/readme-templates/readme.yml +38 -0
  195. package/lib/rule/compilers/credential.js +62 -0
  196. package/lib/rule/compilers/dataflow.js +38 -0
  197. package/lib/rule/compilers/file-health.js +75 -0
  198. package/lib/rule/compilers/frontend.js +86 -0
  199. package/lib/rule/compilers/func.js +35 -0
  200. package/lib/rule/compilers/helpers.js +71 -0
  201. package/lib/rule/compilers/index.js +29 -0
  202. package/lib/rule/compilers/link-semantic.js +45 -0
  203. package/lib/rule/compilers/list-kinds.js +12 -0
  204. package/lib/rule/compilers/numeric-kinds.js +66 -0
  205. package/lib/rule/compilers/regex.js +78 -0
  206. package/lib/rule/compilers/structure.js +80 -0
  207. package/lib/rule/compilers.js +17 -0
  208. package/lib/rule/homoglyph.js +45 -0
  209. package/lib/rule/loader.js +270 -0
  210. package/lib/rule/registry.js +115 -0
  211. package/lib/rule/scope.js +67 -0
  212. package/lib/score/docs-score.js +166 -0
  213. package/lib/score/index.js +140 -0
  214. package/lib/self/index.js +193 -0
  215. package/lib/skip-dirs.js +64 -0
  216. package/lib/tool-probes.json +50 -0
  217. package/lib/user-requirements.json +14 -0
  218. package/lib/vendor/js-yaml/LICENSE +21 -0
  219. package/lib/vendor/js-yaml/js-yaml.mjs +3073 -0
  220. package/package.json +95 -4
  221. package/scripts/__pycache__/module-splitter.cpython-38.pyc +0 -0
  222. package/scripts/audit-ext/_example-readme-present.mjs +34 -0
  223. package/scripts/audit-ext/variable-min-length.mjs +102 -0
  224. package/scripts/audit-runner.mjs +35 -0
  225. package/scripts/audit-runtime-check.mjs +129 -0
  226. package/scripts/browser-page-probe.mjs +271 -0
  227. package/scripts/build-client.mjs +119 -0
  228. package/scripts/check.mjs +88 -0
  229. package/scripts/clean-date-comments.py +102 -0
  230. package/scripts/doc-drift.mjs +200 -0
  231. package/scripts/doc-func.mjs +212 -0
  232. package/scripts/doc-tree.mjs +456 -0
  233. package/scripts/doc-version.mjs +220 -0
  234. package/scripts/frontend-preview-check.mjs +124 -0
  235. package/scripts/hot-path-probe-cjs.cjs +71 -0
  236. package/scripts/hot-path-probe-fs-shim.mjs +28 -0
  237. package/scripts/hot-path-probe-fsp-shim.mjs +31 -0
  238. package/scripts/hot-path-probe.mjs +153 -0
  239. package/scripts/module-splitter.py +800 -0
  240. package/scripts/platform-scan.mjs +168 -0
  241. package/scripts/preview-gen.mjs +489 -0
  242. package/scripts/preview-local-runner.mjs +55 -0
  243. package/scripts/preview-server-direct.mjs +116 -0
  244. package/scripts/preview-server.mjs +305 -0
  245. package/scripts/preview-slot-data.mjs +123 -0
  246. package/scripts/probe-recheck.mjs +47 -0
  247. package/scripts/readme-gen.mjs +268 -0
  248. package/scripts/rename-locator.mjs +97 -0
  249. package/scripts/rule-switch.mjs +97 -0
  250. package/scripts/rules-solo-audit.mjs +173 -0
  251. package/scripts/scan-file-io.mjs +713 -0
  252. package/scripts/scan-hardcoded-paths.mjs +125 -0
  253. package/scripts/scan-repos.mjs +167 -0
  254. package/scripts/scan-version.mjs +122 -0
  255. package/scripts/scrub-user-wording.mjs +420 -0
  256. package/scripts/symbol-index.mjs +85 -0
  257. package/scripts/sync-plugin-install.mjs +223 -0
  258. package/scripts/sync-plugin.mjs +279 -0
  259. package/scripts/verify-prestep.mjs +100 -0
  260. package/skills/dev/audit-rule-authoring.md +58 -0
  261. package/skills/dev/dsh-git-push.md +323 -0
  262. package/skills/dev/git-push-live-fix.md +45 -0
  263. package/skills/dsh-repo-index.md +35 -0
  264. package/skills/guide/guide-audit.md +167 -0
  265. package/skills/guide/guide-cli-scripts.md +104 -0
  266. package/skills/guide/guide-clone-repos.md +173 -0
  267. package/skills/guide/guide-commit-push.md +156 -0
  268. package/skills/guide/guide-inject-ui.md +166 -0
  269. package/skills/guide/guide-slash-completion.md +118 -0
  270. package/skills/workflow/README.md +21 -0
  271. package/skills/workflow/git-commit-discipline.md +68 -0
  272. package/skills/workflow/git-project-startup.md +85 -0
  273. package/skills/workflow/git-rebuild-process.md +57 -0
  274. package/skills/workflow/github-operations.md +91 -0
  275. package/skills/workflow/readme-sync-git-md.md +28 -0
  276. package/skills/workflow/task-completion-report.md +73 -0
  277. package/skills/workflow/tool-json-add-ask.md +35 -0
  278. package/skills/workflow/versioning-rule.md +211 -0
@@ -0,0 +1,461 @@
1
+ /**
2
+ * AST 实现层 · 控制流检查
3
+ *
4
+ * 职责:同步 fs 调用、空 catch、圈复杂度、嵌套深度(token 级判定)。
5
+ * token 化保证注释里的示例代码不被计入。
6
+ */
7
+
8
+ import { tokenize } from './tokenizer.js';
9
+ import { matchBrace, collectInnerFnRanges, isBlockParen, matchingOpen } from './brace.js';
10
+ import { pythonFuncRanges } from './size.js';
11
+ import { javaKtFuncRanges } from './lang.js';
12
+
13
+ // 向后找异步函数体 '{' 的最大 token 跨度:与 brace.js 共用同一来源(lib/ast/consts.js)
14
+ import { FN_BODY_LOOKAHEAD } from './consts.js';
15
+
16
+ const SYNC_FS_FNS = new Set([
17
+ 'readFileSync', 'writeFileSync', 'readdirSync', 'existsSync', 'statSync', 'mkdirSync',
18
+ 'rmSync', 'unlinkSync', 'readlinkSync', 'lstatSync', 'renameSync', 'copyFileSync', 'appendFileSync',
19
+ ]);
20
+
21
+ /**
22
+ * 检查 async 路径中的 fs 同步调用(AST 级,修 named import 假阴性)。
23
+ * @param {string} text 文件全文
24
+ * @returns {Array<{line:number, call:string, via:string}>} via: 'named-import' | 'fs-prefix'
25
+ */
26
+ /** 第 1 段:收集 `import { readFileSync, X } from 'node:fs'` 的 fs 同步函数名(named import)。 */
27
+ function collectNamedSyncFs(tokens) { // dsh-skip-complexity: named-import 扫描器(import{..}→from 模式匹配,扫描结构必然嵌套)
28
+ const namedSync = new Set();
29
+ for (let i = 0; i < tokens.length - 1; i++) {
30
+ if (tokens[i].type === 'ident' && tokens[i].value === 'import'
31
+ && tokens[i + 1].type === 'punct' && tokens[i + 1].value === '{') {
32
+ let j = i + 2;
33
+ const names = [];
34
+ while (j < tokens.length && !(tokens[j].type === 'punct' && tokens[j].value === '}')) {
35
+ if (tokens[j].type === 'ident') names.push(tokens[j].value);
36
+ j++;
37
+ }
38
+ // 找 from 'node:fs' / 'fs'
39
+ let k = j + 1;
40
+ let from = '';
41
+ while (k < tokens.length && k < j + 8) {
42
+ if (tokens[k].type === 'ident' && tokens[k].value === 'from') {
43
+ const strTok = tokens[k + 1];
44
+ if (strTok && strTok.type === 'str') {
45
+ from = strTok.value.replace(/['"]/g, '');
46
+ if (/^(node:)?fs$/.test(from)) {
47
+ for (const nm of names) if (SYNC_FS_FNS.has(nm)) namedSync.add(nm);
48
+ }
49
+ }
50
+ break;
51
+ }
52
+ k++;
53
+ }
54
+ i = j;
55
+ }
56
+ }
57
+ return namedSync;
58
+ }
59
+
60
+ /** 第 2 段:定位所有 async 函数体边界(async function / async X(/ async (),返回 [起行, 止行, 开括号idx, 闭括号idx]。 */
61
+ function collectAsyncRanges(tokens) { // dsh-skip-complexity: async 函数体边界扫描器(token 遍历+配对,结构必然嵌套)
62
+ const asyncRanges = [];
63
+ for (let i = 0; i < tokens.length; i++) {
64
+ const t = tokens[i];
65
+ if (t.type === 'ident' && t.value === 'async') {
66
+ // 向后找函数体 '{'(跳过函数名/参数,限 20 token)
67
+ for (let j = i + 1; j < Math.min(tokens.length, i + FN_BODY_LOOKAHEAD); j++) {
68
+ const tj = tokens[j];
69
+ if (tj.type === 'punct' && tj.value === '{') {
70
+ const range = matchBrace(tokens, j);
71
+ if (range) asyncRanges.push([tokens[j].line, tokens[range[1]].line, j, range[1]]);
72
+ break;
73
+ }
74
+ if (tj.type === 'punct' && (tj.value === ';' || tj.value === '}')) break;
75
+ }
76
+ }
77
+ }
78
+ return asyncRanges;
79
+ }
80
+
81
+ /** 第 3 段:找同步 fs 调用(named 直调或 fs.XSync(前缀),落在 async 函数体内即报。 */
82
+ function scanSyncCalls(tokens, namedSync, asyncRanges) { // dsh-skip-complexity: 同步 fs 调用扫描器(定位调用点+区间归属判定,结构必然嵌套)
83
+ const out = [];
84
+ for (let i = 0; i < tokens.length; i++) {
85
+ const t = tokens[i];
86
+ if (t.type !== 'ident') continue;
87
+ let call = '';
88
+ let via = '';
89
+ if (namedSync.has(t.value)) {
90
+ const nx = tokens[i + 1];
91
+ if (nx && nx.type === 'punct' && nx.value === '(') { call = t.value; via = 'named-import'; }
92
+ } else if (t.value === 'fs') {
93
+ const nx = tokens[i + 1];
94
+ if (nx && nx.type === 'punct' && nx.value === '.') {
95
+ const nn = tokens[i + 2];
96
+ if (nn && nn.type === 'ident' && SYNC_FS_FNS.has(nn.value)) {
97
+ const after = tokens[i + 3];
98
+ if (after && after.type === 'punct' && after.value === '(') { call = nn.value; via = 'fs-prefix'; }
99
+ }
100
+ }
101
+ }
102
+ if (!call) continue;
103
+ // 判定是否在 async 函数区间内(token 索引区间)
104
+ const inAsync = asyncRanges.some(([, , oi, ci]) => i > oi && i < ci);
105
+ if (inAsync) out.push({ line: t.line, call, via });
106
+ }
107
+ return out;
108
+ }
109
+
110
+ /** 同步 fs 调用落在 async 函数体内 → 报「异步路径同步 I/O」(阻塞事件循环)。 */
111
+ export function checkSyncFs(text = '') {
112
+ const tokens = tokenize(text);
113
+ const namedSync = collectNamedSyncFs(tokens);
114
+ const asyncRanges = collectAsyncRanges(tokens);
115
+ return scanSyncCalls(tokens, namedSync, asyncRanges);
116
+ }
117
+
118
+ /**
119
+ * 检查静默吞错 catch(AST 级,括号平衡 → 块内去注释/空白后为空即报)。
120
+ * @param {string} text 文件全文
121
+ * @returns {Array<{line:number}>}
122
+ */
123
+ export function checkEmptyCatchAst(text = '') { // dsh-skip-complexity: 空 catch 检测器本体(token 遍历 + catch 体空判定多条件链,职责单一)
124
+ const tokens = tokenize(text);
125
+ const out = [];
126
+ for (let i = 0; i < tokens.length; i++) {
127
+ const t = tokens[i];
128
+ if (t.type !== 'ident' || t.value !== 'catch') continue;
129
+ // 跳过 **Promise 方法调用** `.catch(...)`——它不是 try/catch 语句,而是链式调用:
130
+ // 实测误报(dsh-session-conductor 的 12 条里有 6 条属此类):
131
+ // `await res.json().catch(() => ({}))`(取默认值)、`p.catch(() => {})`(故意静默兜底)
132
+ // 两者都不是「静默吞错的 catch 块」,按空 catch 报属误报。
133
+ // 判定:向前跳过空白/注释,若前一 token 是 `.` ⇒ 成员调用。
134
+ let back = i - 1;
135
+ while (back >= 0 && (tokens[back].type === 'ws' || tokens[back].type === 'comment')) back--;
136
+ if (back >= 0 && tokens[back].type === 'punct' && tokens[back].value === '.') continue;
137
+ // 找 catch 后的 '{'(跳过 (param) 与空白,限 10 token)
138
+ let openIdx = -1;
139
+ for (let j = i + 1; j < Math.min(tokens.length, i + 10); j++) {
140
+ const tj = tokens[j];
141
+ if (tj.type === 'punct' && tj.value === '{') { openIdx = j; break; }
142
+ if (tj.type === 'punct' && tj.value === '}') break; // catch (e) 无块 → 不是本类
143
+ }
144
+ if (openIdx === -1) continue;
145
+ const range = matchBrace(tokens, openIdx);
146
+ if (!range) continue;
147
+ const [, closeIdx] = range;
148
+ // 块内判定:有实质语句 → 正常;仅有说明性注释 → 视为「已说明的静默」(不算问题);
149
+ // 真正空块(无语句也无注释)→ 报问题(静默吞错且无任何交代)。
150
+ let hasBody = false;
151
+ let hasNote = false;
152
+ for (let k = openIdx + 1; k < closeIdx; k++) {
153
+ const tk = tokens[k];
154
+ if (tk.type === 'ws') continue;
155
+ if (tk.type === 'comment') {
156
+ // 修:注释「交代了原因」即算已说明——不再只看说明词表。
157
+ // 旧逻辑只认词表(跳过/忽略/…),「/* 无缓存/损坏则空 */」「预热失败不影响
158
+ // 主链路」这类**实质说明了为什么静默**的注释会误报(它们是好的静默)。
159
+ // 判定:去空白后长度 ≥ 4 且不只含单个标识符(`// e` 这种占位不算交代)。
160
+ // 词表语义保留为兜底(含说明词但很短也认)。
161
+ const noteText = String(tk.value || '').replace(/[/*\s]/g, '');
162
+ // CJK 按信息量折算:汉字单字信息量远高于 ASCII 字母,`/* 尽力 */`(2 字)已是完整交代,
163
+ // 但按「≥4 字符」的 ASCII 门槛会被判为「没交代」而误报(dsh-session-conductor 实测)。
164
+ // 判定:去符号后 ≥4 字符(ASCII 语境),或含 ≥2 个 CJK 字符(中文语境)。
165
+ const cjkCount = (noteText.match(/[\u4e00-\u9fa5]/g) || []).length;
166
+ if (/跳过|忽略|已断开|不抛|按空|不阻断|无需|降级|兜底|视为|不回滚|非\s*JSON|raw|空仓|best-effort/i.test(tk.value || '')
167
+ || (noteText.length >= 4 && !/^[a-zA-Z_$][\w$]*$/.test(noteText))
168
+ || cjkCount >= 2) hasNote = true;
169
+ continue;
170
+ }
171
+ hasBody = true;
172
+ break;
173
+ }
174
+ if (!hasBody && !hasNote) out.push({ line: t.line });
175
+ }
176
+ return out;
177
+ }
178
+
179
+ export function checkComplexityAst(text = '', { warn = 10, block = 20 } = {}) {
180
+ const tokens = tokenize(text);
181
+ const out = [];
182
+ // 分支关键字(口径校准,用户提供标准):
183
+ // if/else if 每分支、for、while(普通 while 与 do-while 的 while 均计 1——
184
+ // do-while 只计 1:**do 不进分支集合**,do-while 由 while token 计)、case(switch
185
+ // 每个分支)、catch。**带标签 break/continue 额外 +1**(跨循环/switch 的复杂控制流,
186
+ // 由下方 labelled-break 判定处理)。
187
+ const branch = new Set(['if', 'for', 'while', 'case', 'catch']);
188
+ // Python 分支——def + 缩进块,走行级复杂度统计(token 级大括号法对 py 失效)
189
+ if (pythonDetectDef(text)) {
190
+ return checkPythonComplexity(text, { warn, block });
191
+ }
192
+ // Java/Kotlin 分支——方法无 function 关键字,JS token 级只认 function → 零命中;
193
+ // 复用 javaKtFuncRanges 的方法区间,对每个方法体做 token 级分支计数(与 JS 同口径)
194
+ const jr = javaKtFuncRanges(text);
195
+ if (jr.length) return checkJavaKtComplexity(tokens, jr, { warn, block });
196
+ for (let i = 0; i < tokens.length; i++) {
197
+ const t = tokens[i];
198
+ if (t.type !== 'ident' || t.value !== 'function') continue;
199
+ let openIdx = -1;
200
+ for (let j = i + 1; j < Math.min(tokens.length, i + FN_BODY_LOOKAHEAD); j++) {
201
+ if (tokens[j].type === 'punct' && tokens[j].value === '{') { openIdx = j; break; }
202
+ }
203
+ if (openIdx === -1) continue;
204
+ const range = matchBrace(tokens, openIdx);
205
+ if (!range) continue;
206
+ // 修:嵌套函数的复杂度**不得累加到外层**(旧实现整段计入,导致
207
+ // 只要函数里定义了几个带分支的内部函数,外层就被虚报成高复杂度——如
208
+ // makeTitleResolver 自身仅 2 个 catch + 2 个 ??,却被报 29)。
209
+ // 做法:先收集内层函数体的 token 区间,扫外层时跳过这些区间;内层自身
210
+ // 由后续迭代单独评估(不再 i = range[1] 整体跳过,否则内层永远扫不到)。
211
+ const innerRanges = collectInnerFnRanges(tokens, openIdx + 1, range[1]);
212
+ const inInner = (k) => innerRanges.some(([a, b]) => k >= a && k < b);
213
+ let cx = 1;
214
+ for (let k = openIdx + 1; k < range[1]; k++) {
215
+ if (inInner(k)) continue;
216
+ const tk = tokens[k];
217
+ if (tk.type === 'comment') continue;
218
+ if (tk.type === 'ident' && branch.has(tk.value)) cx++;
219
+ // 分支点:逻辑与/或、空值合并、三元问号。**排除可选链 `?.`**——它是空值保护,
220
+ // 不产生独立执行路径(修:多字符 token 化后 `?.` 是独立 token,
221
+ // 不再被误认成三元 `?`)。
222
+ if (tk.type === 'punct' && ['&&', '||', '??', '?'].includes(tk.value)) cx++;
223
+ // 带标签 break/continue +1:break label; / continue label;——
224
+ // 跨循环/switch 的复杂控制流(跳出多层/跳到外层迭代),增加独立执行路径。
225
+ // 普通 break/continue(switch case 收尾、循环尾)不计——它们是常规流程。
226
+ if (tk.type === 'ident' && (tk.value === 'break' || tk.value === 'continue')) {
227
+ const nx = tokens[k + 1];
228
+ if (nx && nx.type === 'ident') cx++;
229
+ }
230
+ }
231
+ if (cx > warn) {
232
+ const nx = tokens[i + 1];
233
+ out.push({ line: tokens[openIdx].line, name: nx?.type === 'ident' ? nx.value : '(匿名)', complexity: cx, level: cx > block ? 'blocker' : 'warning' });
234
+ }
235
+ // 不跳过内部:继续迭代把内层函数也评估掉(i 只前进到本函数声明之后)
236
+ i = openIdx;
237
+ }
238
+ return out;
239
+ }
240
+
241
+ /**
242
+ * 检查嵌套深度(max-depth kind,AST 级)。
243
+ * 统计函数体内「控制流块」最大嵌套层数(if/for/while/try/switch 等)。
244
+ *
245
+ * 修 bug:旧实现把所有 `{` 都计入深度,**对象字面量/解构/JSON 结构**
246
+ * 被当成嵌套层级——`return { version: 2, skills: {}, sessions: {} }` 会被报
247
+ * depth=4,`try { ... } catch { return {...} }`(真实深度 2)也被报 depth=4,
248
+ * 造成大面积误报(一个仓库 19 条)。
249
+ * 现只统计「块语句」大括号:仅当 `{` 跟着控制流关键字或函数体时才算一层;
250
+ * 对象字面量(`{` 前是 `=`/`(`/`return`/`,`/`:`/`[` 等值位置)不计入。
251
+ * 块级关键字(计入):if / else / for / while / do / try / catch / finally / switch / function / =>。
252
+ * @param {string} text 文件全文
253
+ * @param {object} [opts] { warn=4, block=6 }
254
+ * @returns {Array<{line:number, depth:number, level:string}>}
255
+ */
256
+ export function checkNestingDepthAst(text = '', { warn = 4, block = 6 } = {}) { // dsh-skip-complexity: 嵌套深度统计器本体(统计 if/for 嵌套必然自身嵌套)
257
+ // Python 分支——缩进块(无大括号),走行级嵌套统计
258
+ if (pythonDetectDef(text)) return checkPythonNesting(text, { warn, block });
259
+ const tokens = tokenize(text);
260
+ const out = [];
261
+ // 进入块的前置关键字(`if (...) {`、`else {`、`try {`、`=> {` 等)
262
+ const BLOCK_KW = new Set(['if', 'else', 'for', 'while', 'do', 'try', 'catch', 'finally', 'switch', 'function']);
263
+ // 统计每个 `{` 是否属于块语句(与 token 下标对齐)
264
+ const isBlockBrace = new Map();
265
+ for (let i = 0; i < tokens.length; i++) {
266
+ const t = tokens[i];
267
+ if (!(t.type === 'punct' && t.value === '{')) continue;
268
+ // 向前找最近的有意义 token:若是 `)` → 可能 if/for/while/function 的参数尾(块)
269
+ // 或箭头函数参数尾(块);若直接是 BLOCK_KW/fn 关键字 → 块;
270
+ // 若是 `=>` → 箭头函数体(块);若是 `else`/`do`/`try`/`finally` → 块;
271
+ // 其余(`=` `(` `,` `:` `[` `return` `=>` 之外的值位置)→ 对象字面量,不计。
272
+ let prev = null;
273
+ for (let j = i - 1; j >= 0; j--) {
274
+ const tj = tokens[j];
275
+ if (tj.type === 'ws' || tj.type === 'comment') continue;
276
+ prev = tj;
277
+ break;
278
+ }
279
+ let isBlock = false;
280
+ if (prev) {
281
+ if (prev.type === 'ident' && BLOCK_KW.has(prev.value)) isBlock = true; // if (...) / else ...? 见下
282
+ else if (prev.type === 'punct' && prev.value === '=>') isBlock = true; // () => {
283
+ else if (prev.type === 'punct' && prev.value === ')') {
284
+ // `)` 前是 BLOCK_KW 或函数名 → 块语句/函数体;否则可能是调用参数里传对象
285
+ let before = null;
286
+ for (let j = tokens.indexOf(prev) - 1; j >= 0; j--) {
287
+ const tj = tokens[j];
288
+ if (tj.type === 'ws' || tj.type === 'comment') continue;
289
+ before = tj;
290
+ break;
291
+ }
292
+ isBlock = isBlockParen(tokens, prev) || (before && before.type === 'ident' && before.value === 'function');
293
+ }
294
+ }
295
+ isBlockBrace.set(i, isBlock);
296
+ }
297
+ let depth = 0;
298
+ let maxDepth = 0;
299
+ let maxLine = 1;
300
+ let fnStartLine = 0;
301
+ for (let i = 0; i < tokens.length; i++) {
302
+ const t = tokens[i];
303
+ if (t.type === 'ident' && t.value === 'function') fnStartLine = t.line;
304
+ if (t.type === 'punct' && t.value === '{') {
305
+ if (isBlockBrace.get(i)) {
306
+ depth++;
307
+ if (depth > maxDepth) { maxDepth = depth; maxLine = t.line; }
308
+ }
309
+ } else if (t.type === 'punct' && t.value === '}') {
310
+ // 只有块大括号才减(对象字面量的 `}` 不影响)
311
+ if (isBlockBrace.get(matchingOpen(tokens, i))) {
312
+ depth--;
313
+ if (depth === 0 && maxDepth > warn) {
314
+ out.push({ line: fnStartLine || maxLine, depth: maxDepth, level: maxDepth > block ? 'blocker' : 'warning' });
315
+ }
316
+ if (depth <= 0) { depth = 0; maxDepth = 0; }
317
+ }
318
+ }
319
+ }
320
+ return out;
321
+ }
322
+
323
+ /**
324
+ * 检测文本是否含 Python 函数定义(def ...:)——决定复杂度走行级统计。
325
+ * 纯 JS 项目(无 def)不受影响(零开销正则预检)。
326
+ */
327
+ function pythonDetectDef(text) {
328
+ return /^\s*def\s+[A-Za-z_]\w*\s*\(/m.test(String(text));
329
+ }
330
+
331
+ /**
332
+ * Python 圈复杂度(行级,)。
333
+ *
334
+ * Python 无大括号/function 关键字,token 级分支计数失效。按行统计:
335
+ * · 函数范围复用 pythonFuncRanges(def 行 + 缩进法确定函数体)
336
+ * · 分支点 = 函数体内**行首**(缩进后)的控制流关键字:if/elif/else/for/while/
337
+ * except/try/with/assert——每个 +1(与 JS 的 branch 集合对齐口径)
338
+ * · 逻辑运算符 &&/|| 在 Python 是 and/or(行内出现 +1);三元是 `x if c else y`
339
+ * (Python 无 `?`,不另计)
340
+ * · 嵌套函数复杂度不累加到外层(与 JS 版同语义:按 pythonFuncRanges 逐函数独立评估)
341
+ * 返回结构与 checkComplexityAst 一致({line, name, complexity, level})。
342
+ */
343
+ function checkPythonComplexity(text, { warn, block }) {
344
+ const out = [];
345
+ const lines = String(text).split('\n');
346
+ // 行级分支(口径:if/elif 每分支、for/while、try/except(catch 语义)、
347
+ // with/assert 为 Python 语义保留;**else 不计**——else 是 if 的配对分支非新分支,
348
+ // elif 才是新分支,与 JS 版「if/else if 每分支」对齐)
349
+ const BRANCH_LINE = /^\s*(if|elif|for|while|try|except|with|assert)\b/;
350
+ const BOOL_OP = /\b(and|or)\b/;
351
+ for (const r of pythonFuncRanges(text)) {
352
+ let cx = 1;
353
+ for (let i = r.startLine - 1; i < r.endLine; i++) {
354
+ const line = lines[i];
355
+ if (!line) continue;
356
+ if (/^\s*#/.test(line)) continue; // 注释不计
357
+ if (BRANCH_LINE.test(line)) cx++;
358
+ // 行内 and/or(非注释非字符串粗判——行级精度足够,注释行已跳过)
359
+ const m = BOOL_OP.exec(line.replace(/^\s*#.*$/, ''));
360
+ if (m) cx++;
361
+ }
362
+ if (cx > warn) {
363
+ out.push({ line: r.startLine, name: r.name, complexity: cx, level: cx > block ? 'blocker' : 'warning' });
364
+ }
365
+ }
366
+ return out;
367
+ }
368
+
369
+ /**
370
+ * Python 嵌套深度(行级缩进法,)。
371
+ *
372
+ * Python 用缩进表达块结构(无大括号)。逐行统计**块起始行**(行首控制流关键字:
373
+ * if/elif/else/for/while/try/except/with),每个 +1 缩进层级;函数体(def)是
374
+ * 顶层容器不计入嵌套(与 JS 版「函数体不计深度」口径一致——JS 统计的是函数内
375
+ * 控制流块的嵌套,def 本身不是「控制流块」)。
376
+ * 返回 {line, depth, level} 与 JS 版一致;超过 warn 报 warning、超过 block 报 blocker。
377
+ */
378
+ function checkPythonNesting(text, { warn, block }) {
379
+ const out = [];
380
+ const lines = String(text).split('\n');
381
+ const BLOCK_LINE = /^\s*(if|elif|else|for|while|try|except|with)\b/;
382
+ for (const r of pythonFuncRanges(text)) {
383
+ let depth = 0;
384
+ let maxDepth = 0;
385
+ let maxLine = r.startLine;
386
+ const bodyIndent = indentOf(lines[r.startLine - 1] || '') + 4; // def 缩进 + 一级
387
+ for (let i = r.startLine; i < r.endLine; i++) {
388
+ const line = lines[i];
389
+ if (!line || !line.trim()) continue;
390
+ if (/^\s*#/.test(line)) continue; // 注释不影响嵌套
391
+ const ind = indentOf(line);
392
+ // 缩进回到函数体外 → 函数结束(pythonFuncRanges 已保证不越界,防御性判断)
393
+ if (ind < bodyIndent) break;
394
+ if (BLOCK_LINE.test(line)) {
395
+ depth++;
396
+ if (depth > maxDepth) { maxDepth = depth; maxLine = i + 1; }
397
+ } else if (ind < depth * 4 + bodyIndent) {
398
+ // 缩进回退 → 块结束(近似:每级 4 空格;tab/混合缩进误差可接受)
399
+ depth = Math.max(0, Math.floor((ind - bodyIndent) / 4));
400
+ }
401
+ }
402
+ if (maxDepth > warn) {
403
+ out.push({ line: maxLine, depth: maxDepth, level: maxDepth > block ? 'blocker' : 'warning' });
404
+ }
405
+ }
406
+ return out;
407
+ }
408
+
409
+ /** 行首缩进空格数。 */
410
+ function indentOf(line) {
411
+ return (String(line).match(/^\s*/) || [''])[0].length;
412
+ }
413
+
414
+ /**
415
+ * Java/Kotlin 圈复杂度(token 级,按方法区间)。
416
+ *
417
+ * Java/Kotlin 方法与 JS 一样用花括号分块、分支关键字一致(if/for/while/case/catch/&&/||/?),
418
+ * 唯一差异是无 `function` 关键字——方法范围由 javaKtFuncRanges 提供,逐方法在 token 流里
419
+ * 按 [openIdx, closeIdx] 区间计数分支点(与 JS 版 checkComplexityAst 同口径)。
420
+ * 内层 lambda/匿名类的大括号由外层方法区间包含(方法体确实包括它们),复杂度的
421
+ * 「分支点」只统计 branch 关键字与逻辑运算符,不把 lambda { 本身计分支——与 JS 一致。
422
+ * @param {Array} tokens token 流
423
+ * @param {Array<{startLine:number,endLine:number,name:string}>} ranges 方法范围
424
+ * @returns {Array<{line:number,name:string,complexity:number,level:string}>}
425
+ */
426
+ function checkJavaKtComplexity(tokens, ranges, { warn, block }) {
427
+ const out = [];
428
+ // 与 JS 版同口径:if/else if 每分支、for、while(do-while 由 while 计 1,
429
+ // do 不进集合)、case、catch、when=Kotlin switch。带标签 break/continue 额外 +1。
430
+ const branch = new Set(['if', 'for', 'while', 'case', 'catch', 'when']); // when=Kotlin switch
431
+ // 方法体 token 区间([i,j])——按行号定位 tokens
432
+ for (const r of ranges) {
433
+ // 找方法体起点({ 行=r.startLine 的 token 下标)与结束(r.endLine 的最后一个 })
434
+ const startIdx = tokens.findIndex((t) => t.line === r.startLine);
435
+ if (startIdx === -1) continue;
436
+ // 从 startLine 向后找属于该方法的最后一个 } 之前的所有分支 token
437
+ let endIdx = -1;
438
+ for (let k = tokens.length - 1; k >= 0; k--) {
439
+ const tk = tokens[k];
440
+ if (tk.line === r.endLine && tk.type === 'punct' && tk.value === '}') { endIdx = k; break; }
441
+ }
442
+ if (endIdx === -1) continue;
443
+ let cx = 1;
444
+ for (let k = startIdx; k <= endIdx; k++) {
445
+ const tk = tokens[k];
446
+ if (tk.type === 'comment') continue;
447
+ if (tk.type === 'ident' && branch.has(tk.value)) cx++;
448
+ // 逻辑与/或/三元问号(Java 无 ??,Kotlin 有——同 JS 的 ? 分支语义;排除 ?. 可选链)
449
+ if (tk.type === 'punct' && ['&&', '||', '??', '?'].includes(tk.value)) cx++;
450
+ // 带标签 break/continue +1(break label; / continue label;——跨循环/switch 复杂控制流)
451
+ if (tk.type === 'ident' && (tk.value === 'break' || tk.value === 'continue')) {
452
+ const nx = tokens[k + 1];
453
+ if (nx && nx.type === 'ident') cx++;
454
+ }
455
+ }
456
+ if (cx > warn) {
457
+ out.push({ line: r.startLine, name: r.name || '(匿名)', complexity: cx, level: cx > block ? 'blocker' : 'warning' });
458
+ }
459
+ }
460
+ return out;
461
+ }
@@ -0,0 +1,199 @@
1
+ /**
2
+ * AST 实现层 · 凭据检查
3
+ *
4
+ * 职责:凭据标识符右侧值判定(硬编码/引用/类型检查)、前缀型密钥串的占位符精筛。
5
+ *
6
+ * 占位符判据(CRED_PLACEHOLDER / CRED_SCHEME_PREFIX / isMeaningfulCredentialValue)
7
+ * 必须只有一份:两处检查共用,否则判据漂移会出现「同一串值 A 规则放行、
8
+ * B 规则拦截」的自相矛盾。
9
+ */
10
+
11
+ import { tokenize } from './tokenizer.js';
12
+
13
+ /**
14
+ * 检查「凭据类标识符是否真的被赋了字面量值」(no-hardcoded-credentials kind 的 AST 精筛)。
15
+ *
16
+ * 正则 `token\s*[=:]+\s*['"][^'"]+['"]` 命中即报,会把下列**非硬编码**场景误报:
17
+ * - 类型/存在性检查:`typeof cfg.githubToken === 'string'`、`next.apiKey.trim()`
18
+ * - 字段透传/引用:`cfg.githubToken = init.githubToken`(右侧是变量,不是字面量)
19
+ * - 默认值取自配置:`token = options.token || ''`(右侧是表达式/空串)
20
+ * 本实现在 token 级确认:只有当「凭据标识符」右侧的赋值/初始化**直接是字符串字面量**
21
+ * 且该字面量**非空、非占位符**时才判定为硬编码。
22
+ *
23
+ * @param {string} text 文件全文
24
+ * @param {object} [opts] { literalOnly=true } 是否只认「右侧直接是字面量」
25
+ * @returns {Set<number>} 判定为「确实硬编码凭据」的行号集合
26
+ */
27
+ /**
28
+ * 凭据占位符判据(模块级共用)——。
29
+ *
30
+ * 为什么不写在单个检查里:占位符识别被两处用到,必须**同一套判据**——
31
+ * ① checkCredentialRefAst(凭据标识符右侧字面量)
32
+ * ② checkPlaceholderCredentialAst(前缀型密钥串,如 ghp_/sk-/AKIA)
33
+ * 各写一份必然漂移,出现「同一串值 A 规则放行、B 规则拦截」的矛盾。
34
+ */
35
+
36
+ /** 明显不是真凭据的值:空、掩码、占位文案、演示/测试数据。 */
37
+ const CRED_PLACEHOLDER = /^(|\s*|x+|\*+|<[^>]*>|your[-_ ]?.*|change[-_ ]?me|todo|placeholder|example.*|demo.*|sample.*|test.*|dummy.*|fake.*|xxx.*|redacted|masked|none|null|undefined)$/i;
38
+
39
+ /** 单段文本是否占位符文案。 */
40
+ function isPlaceholderText(text) {
41
+ return CRED_PLACEHOLDER.test(String(text));
42
+ }
43
+
44
+ /**
45
+ * 常见凭据 scheme 前缀:判占位符前先剥掉再判一次。
46
+ * 否则带前缀的演示值会漏判——`ghp_` + 「Example…」开头的演示值,其首个词不是 example,
47
+ * 匹配不到 `example.*`,就被当成真凭据报拦截(演示数据/夹具里的常见写法)。
48
+ * 剥前缀不会放过真凭据:真实随机串剥完仍非占位符,照样报。
49
+ */
50
+ const CRED_SCHEME_PREFIX = /^(gh[pousr]_|github_pat_|sk-[a-z]*-?|xox[baprs]-|glpat-|AKIA)/i;
51
+
52
+ /**
53
+ * 运行时求值形态:值不是「写死的字面量」,而是运行期由 shell/模板求出来的。
54
+ *
55
+ * 背景(真实误报):`TOKEN="$(read_token)"` 被 security/no-hardcoded-credentials
56
+ * 报为硬编码凭据——分词器把整个 `"$(read_token)"` 当成一个 str token,本模块
57
+ * 只看「是不是占位符文案」,看不出值是命令替换,于是照报。
58
+ * 这类写法值来自函数/shell,代码里并没有凭据内容,属误报。
59
+ *
60
+ * 只认三种明确形态(刻意收紧):
61
+ * ① `$(cmd)` 命令替换
62
+ * ② `${VAR}` 花括号插值
63
+ * ③ 以 `$` 开头:纯变量引用 `$TOKEN` / `$1`
64
+ * **不**认「含 $ 即可」——`my$ecret`、`pass$word!` 这类带 $ 的真密码必须照报,
65
+ * 否则规则出现后门(实测按「含 $」判会放过 4 类真凭据)。
66
+ */
67
+ const CRED_INTERPOLATED = /\$\(|\$\{|^\$[A-Za-z0-9_]/;
68
+
69
+ /** 去掉字符串字面量外层引号。 */
70
+ function stripQuotes(raw) {
71
+ return String(raw).replace(/^(\'|"|`)([\s\S]*)\1$/, '$2').trim();
72
+ }
73
+
74
+ /**
75
+ * 判断一个字面量值是否算「真凭据」(非空、非掩码、非占位/演示)。
76
+ *
77
+ * @param raw 原始字面量(可带引号)
78
+ * @returns true = 像真凭据(应报);false = 占位符/空值(豁免)
79
+ */
80
+ export function isMeaningfulCredentialValue(raw) {
81
+ const v = stripQuotes(raw);
82
+ if (!v) return false;
83
+ if (isPlaceholderText(v)) return false;
84
+ // 运行时求值($(cmd) / ${VAR} / $VAR)→ 值不在代码里,不是硬编码
85
+ if (CRED_INTERPOLATED.test(v)) return false;
86
+ return !isPlaceholderText(v.replace(CRED_SCHEME_PREFIX, ''));
87
+ }
88
+
89
+ /*
90
+ * 刻意不做「按 -/_ 拆段逐段判占位符」:试过并撤回。
91
+ * 拆段会把「sk- + test + 随机串」形状的值(scheme 段里带 test)整体豁免——
92
+ * 但这类值是真检出:仓库自身测试夹具正是用它证明「非豁免目录的 blocker 会拦截提交」,
93
+ * 放宽后门禁形同虚设。占位符豁免必须取最小面:只认「整串/剥掉 scheme 前缀后即以
94
+ * 占位词开头」,不认藏在中间段里的演示词。
95
+ */
96
+
97
+ /**
98
+ * astConfirmKind: "placeholder-credential" 的精筛集合(mode: deny)。
99
+ *
100
+ * 场景:`secret-github-pat` / `secret-openai-key` / `secret-aws-access-key` 这类
101
+ * **前缀形状匹配**的规则(`\\bghp_[A-Za-z0-9]{20,}\\b`),只看形状不看语义——
102
+ * 文档里写「测试用占位符 + ghp_ 前缀」、演示页假数据
103
+ * `ghp_ExampleToken…` 都会被判成真泄漏(error 级,摘要计入拦截数)。
104
+ *
105
+ * 判定:把命中的密钥串剥掉 scheme 前缀后套占位符判据;命中即加入豁免集。
106
+ * 只看「该串本身是不是占位符」,不做路径/文件级豁免——真 token 无论写在哪个文件都照报。
107
+ *
108
+ * @param text 文件全文
109
+ * @returns Set<number> 命中「占位符凭据」的行号(1 起始)
110
+ */
111
+ export function checkPlaceholderCredentialAst(text = '', file = '') {
112
+ const out = new Set();
113
+ const SCAN = /\b(gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|sk-(?:proj-)?[A-Za-z0-9-]{16,}|AKIA[0-9A-Z]{16})\b/g;
114
+ const lines = String(text).split('\n');
115
+ const isDoc = /\.(md|markdown|txt|rst)$/i.test(String(file || ''));
116
+ for (let i = 0; i < lines.length; i++) {
117
+ SCAN.lastIndex = 0;
118
+ let match;
119
+ while ((match = SCAN.exec(lines[i])) !== null) {
120
+ if (isMeaningfulCredentialValue(match[1]) === false) { out.add(i + 1); break; }
121
+ // 文档示例豁免——md 文档里出现 token 且该行/邻近行含「示例/演示/
122
+ // 占位/example/demo/sample」语义词,是上游文档的示例值引用(如 MCP 配置文档
123
+ // 写 `token=ghp_xxx` 说明用法),不是本仓库真实凭据。
124
+ // 仅文档文件生效;代码文件里的 token 无论上下文如何都照报(防后门)。
125
+ // 判据收紧:语义词需与 token **同行**(跨行引用不算),且 token 值本身
126
+ // 不像随机真实串(真实长随机 PAT 即使行内带「示例」字样也报——见
127
+ // isMeaningfulCredentialValue 的剥离前缀判占位逻辑,这里是文档级补充)。
128
+ if (isDoc && /示例|演示|占位|example|demo|sample|说明|配置示例/i.test(lines[i])) {
129
+ out.add(i + 1);
130
+ break;
131
+ }
132
+ }
133
+ }
134
+ return out;
135
+ }
136
+
137
+ /** 凭据语义标识符(命名含这些词的变量/字段才纳入判断)。 */
138
+ const CRED_IDENT = /(password|passwd|pwd|secret|token|apikey|api_key|accesskey|access_key|cookie|credential|privatekey|private_key)/i;
139
+
140
+ /**
141
+ * 在一段 token 序列上判「凭据标识符右侧是否直接是有效字符串字面量」,命中行号写入 out。
142
+ *
143
+ * @param {Array} tokens tokenize() 结果
144
+ * @param {Set<number>} out 命中行号集合(调用方传入,可累加)
145
+ * @param {number} [lineOffset=0] 行号偏移(子文本从第 1 行重新计数时用)
146
+ */
147
+ function scanCredentialTokens(tokens, out, lineOffset = 0) {
148
+ for (let i = 0; i < tokens.length; i++) {
149
+ const t = tokens[i];
150
+ if (t.type !== 'ident' || !CRED_IDENT.test(t.value)) continue;
151
+ // 向后找该标识符所在语句的赋值/比较运算符(遇到语句边界就放弃)
152
+ let opIdx = -1;
153
+ for (let j = i + 1; j < Math.min(tokens.length, i + 8); j++) {
154
+ const tj = tokens[j];
155
+ if (tj.type !== 'punct') continue;
156
+ // 误报修复:`(` `)` `,` 是表达式/实参/元素边界——标识符若是函数实参
157
+ // (如 encodeURIComponent(token))或数组元素,运算符并不属于它的赋值,
158
+ // 跨过边界会把**下一条语句**的 `:`/`=` 误认成它的(实测 start-preview.mjs:
159
+ // 'path: "/?" + 凭据字段名 + "=" + ..., method: "GET"'——token 后跨过 `)` `,` 命中
160
+ // method 的 `:` → next="GET" 被当硬编码凭据)。除 `.`(属性访问后仍可能 `=`)
161
+ // 外,遇边界一律 break——任何「标识符不是左值」的场景不再误报。
162
+ if ([';', '{', '}', '(', ')', ','].includes(tj.value)) break; // 语句/表达式/实参边界
163
+ if (['=', ':', '==', '===', '!='].includes(tj.value)) { opIdx = j; break; }
164
+ if (tj.value === '.') continue;
165
+ }
166
+ if (opIdx === -1) continue;
167
+ // 只看严格赋值 `=`(`==`/`===` 是判断、`:` 是对象字面量字段声明,另判)
168
+ const opTok = tokens[opIdx];
169
+ const next = tokens[opIdx + 1];
170
+ if (!next) continue;
171
+ if (opTok.value === '=') {
172
+ // 右侧直接是字符串字面量 → 真硬编码
173
+ if (next.type === 'str' && isMeaningfulCredentialValue(next.value)) out.add(t.line + lineOffset);
174
+ continue;
175
+ }
176
+ if (opTok.value === ':') {
177
+ // 对象字面量 `token: 'abc'` → 真硬编码;`token: cfg.token` 是引用,不报
178
+ if (next.type === 'str' && isMeaningfulCredentialValue(next.value)) out.add(t.line + lineOffset);
179
+ }
180
+ }
181
+ }
182
+
183
+ export function checkCredentialRefAst(text = '') {
184
+ const raw = String(text);
185
+ const out = new Set();
186
+ scanCredentialTokens(tokenize(raw), out);
187
+ // markdown 行内代码段兜底:`token: "abc"` 里的反引号被分词器当成模板字面量定界符,
188
+ // 整段合并成一个 tmpl token,内部**不产生** ident/punct/str,直接扫原始 token 会漏报。
189
+ // 而「文档里用行内代码段写配置示例」恰恰是最常见的写法——实测漏报:同一行写法在 .js 里
190
+ // 报、放进 .md 的行内代码段就不报。故把 tmpl 内部文本单独再分词扫一遍。
191
+ // 判据仍是同一个 scanCredentialTokens,不新增第二套判定。
192
+ for (const t of tokenize(raw)) {
193
+ if (t.type !== 'tmpl') continue;
194
+ const inner = String(t.value).replace(/^`+/, '').replace(/`+$/, '');
195
+ if (!inner.trim()) continue;
196
+ scanCredentialTokens(tokenize(inner), out, t.line - 1);
197
+ }
198
+ return out;
199
+ }