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.
- package/.auditignore +30 -0
- package/.gitignore +39 -0
- package/LICENSE +21 -0
- package/README.md +1482 -2
- package/cli.mjs +360 -0
- package/cordis.patch.yml +14 -0
- package/lib/ARCHITECTURE.md +34 -0
- package/lib/BUGFIX-NOTES-2026-09-14.md +278 -0
- package/lib/app/apply.js +275 -0
- package/lib/app/audit-api.js +158 -0
- package/lib/app/command-registry.js +262 -0
- package/lib/app/constants.js +16 -0
- package/lib/app/handlers/account.js +166 -0
- package/lib/app/handlers/clone.js +168 -0
- package/lib/app/handlers/http-constants.js +9 -0
- package/lib/app/handlers/identity-rewrite.js +94 -0
- package/lib/app/handlers/meta.js +175 -0
- package/lib/app/handlers/npm.js +169 -0
- package/lib/app/handlers/repo-actions.js +143 -0
- package/lib/app/handlers/repos.js +231 -0
- package/lib/app/handlers/settings.js +62 -0
- package/lib/app/host-doc-checks.js +25 -0
- package/lib/app/http-handlers.js +131 -0
- package/lib/app/index.js +30 -0
- package/lib/app/inject-text.js +191 -0
- package/lib/app/scan-root.js +23 -0
- package/lib/app/schema.js +150 -0
- package/lib/app/settings-bridge.js +167 -0
- package/lib/app/slash-commands.js +395 -0
- package/lib/app/slot-stats.js +35 -0
- package/lib/app/tool-call.js +662 -0
- package/lib/app/tools.js +40 -0
- package/lib/ast/brace.js +105 -0
- package/lib/ast/callgraph.js +135 -0
- package/lib/ast/code-lines.js +114 -0
- package/lib/ast/consts.js +12 -0
- package/lib/ast/control-flow.js +461 -0
- package/lib/ast/credential.js +199 -0
- package/lib/ast/dataflow.js +274 -0
- package/lib/ast/dup-code.js +165 -0
- package/lib/ast/index.js +36 -0
- package/lib/ast/io-risk-const.js +95 -0
- package/lib/ast/io-risk-fn.js +208 -0
- package/lib/ast/io-risk-loop.js +308 -0
- package/lib/ast/io-risk.js +314 -0
- package/lib/ast/lang.js +156 -0
- package/lib/ast/line-count.js +52 -0
- package/lib/ast/magic-number.js +272 -0
- package/lib/ast/naming.js +284 -0
- package/lib/ast/perf.js +472 -0
- package/lib/ast/scope.js +241 -0
- package/lib/ast/shell.js +131 -0
- package/lib/ast/size.js +378 -0
- package/lib/ast/symbol-index.js +399 -0
- package/lib/ast/tokenizer.js +341 -0
- package/lib/audit/analysis-coverage.js +98 -0
- package/lib/audit/audit-file.js +182 -0
- package/lib/audit/checks.js +17 -0
- package/lib/audit/client-entry.js +93 -0
- package/lib/audit/collector.js +477 -0
- package/lib/audit/ext-runner.js +80 -0
- package/lib/audit/file-context.js +138 -0
- package/lib/audit/finding.js +50 -0
- package/lib/audit/gitignore-match.js +113 -0
- package/lib/audit/glob.js +63 -0
- package/lib/audit/history-report.js +100 -0
- package/lib/audit/history.js +126 -0
- package/lib/audit/ignore-blind.js +101 -0
- package/lib/audit/index.js +33 -0
- package/lib/audit/orchestrate.js +476 -0
- package/lib/audit/public.js +24 -0
- package/lib/audit/repo-level.js +30 -0
- package/lib/audit/report-yaml.js +86 -0
- package/lib/audit/slot.js +65 -0
- package/lib/audit-defaults.js +18 -0
- package/lib/audit-rules/audit-rules-comment.yml +247 -0
- package/lib/audit-rules/audit-rules-cpp.yml +22 -0
- package/lib/audit-rules/audit-rules-docs.yml +32 -0
- package/lib/audit-rules/audit-rules-dsh.yml +162 -0
- package/lib/audit-rules/audit-rules-filehealth.yml +42 -0
- package/lib/audit-rules/audit-rules-folder.yml +99 -0
- package/lib/audit-rules/audit-rules-frontend.yml +335 -0
- package/lib/audit-rules/audit-rules-go.yml +22 -0
- package/lib/audit-rules/audit-rules-i18n.yml +45 -0
- package/lib/audit-rules/audit-rules-java.yml +105 -0
- package/lib/audit-rules/audit-rules-nodejs.yml +647 -0
- package/lib/audit-rules/audit-rules-npm.yml +187 -0
- package/lib/audit-rules/audit-rules-paths.yml +92 -0
- package/lib/audit-rules/audit-rules-performance.yml +207 -0
- package/lib/audit-rules/audit-rules-php.yml +22 -0
- package/lib/audit-rules/audit-rules-private.yml +24 -0
- package/lib/audit-rules/audit-rules-python.yml +106 -0
- package/lib/audit-rules/audit-rules-robustness.yml +27 -0
- package/lib/audit-rules/audit-rules-rust.yml +22 -0
- package/lib/audit-rules/audit-rules-structure.yml +159 -0
- package/lib/audit-rules/audit-rules-swift.yml +22 -0
- package/lib/audit-rules/audit-rules-template.yml +108 -0
- package/lib/checks/button-bind.js +276 -0
- package/lib/checks/common.js +170 -0
- package/lib/checks/credential-file.js +43 -0
- package/lib/checks/dataflow.js +40 -0
- package/lib/checks/dispatch.js +112 -0
- package/lib/checks/dup-code.js +69 -0
- package/lib/checks/dup-const.js +232 -0
- package/lib/checks/file-health.js +150 -0
- package/lib/checks/filter.js +131 -0
- package/lib/checks/folder.js +173 -0
- package/lib/checks/hardcoded-path.js +98 -0
- package/lib/checks/index.js +46 -0
- package/lib/checks/io.js +66 -0
- package/lib/checks/magic-number.js +42 -0
- package/lib/checks/npm-json.js +273 -0
- package/lib/checks/private.js +63 -0
- package/lib/checks/regex.js +256 -0
- package/lib/checks/semantic.js +134 -0
- package/lib/checks/structural.js +274 -0
- package/lib/cli/commands-account.mjs +107 -0
- package/lib/cli/commands-audit.mjs +144 -0
- package/lib/cli/commands-doc.mjs +127 -0
- package/lib/cli/commands-vcs.mjs +175 -0
- package/lib/client/index.js +162 -0
- package/lib/client-parts/00-loader.js +33 -0
- package/lib/client-parts/01-const.js +207 -0
- package/lib/client-parts/02-utils.js +62 -0
- package/lib/client-parts/03-icons.js +12 -0
- package/lib/client-parts/10-account.js +83 -0
- package/lib/client-parts/11-browser.js +95 -0
- package/lib/client-parts/20-repo.js +374 -0
- package/lib/client-parts/21-audit.js +301 -0
- package/lib/client-parts/22-settings.js +146 -0
- package/lib/client-parts/23-npm.js +383 -0
- package/lib/client-parts/30-page.js +56 -0
- package/lib/client-parts/40-controller.js +1092 -0
- package/lib/client-parts/41-actions.js +279 -0
- package/lib/client-parts/99-apply.js +72 -0
- package/lib/client.js +3195 -0
- package/lib/commit-push.js +144 -0
- package/lib/context/index.js +363 -0
- package/lib/core/atomic-json.js +98 -0
- package/lib/core/config.js +40 -0
- package/lib/core/credentials.js +274 -0
- package/lib/core/endpoints.js +109 -0
- package/lib/core/exec.js +162 -0
- package/lib/exempt/index.js +292 -0
- package/lib/fs/edit-after-read.js +103 -0
- package/lib/fsx.js +87 -0
- package/lib/git/account-status.js +140 -0
- package/lib/git/account.js +233 -0
- package/lib/git/api.js +136 -0
- package/lib/git/atomic-json.js +6 -0
- package/lib/git/browse.js +38 -0
- package/lib/git/clone-download.js +397 -0
- package/lib/git/clone-history-mode.js +143 -0
- package/lib/git/clone-history.js +175 -0
- package/lib/git/clone-jobs.js +250 -0
- package/lib/git/clone-replay-io.js +172 -0
- package/lib/git/clone-replay.js +275 -0
- package/lib/git/clone.js +445 -0
- package/lib/git/cloud.js +46 -0
- package/lib/git/commit-message.js +141 -0
- package/lib/git/config.js +6 -0
- package/lib/git/cred-env.js +88 -0
- package/lib/git/credentials.js +6 -0
- package/lib/git/endpoints.js +6 -0
- package/lib/git/exec.js +6 -0
- package/lib/git/identity-rewrite.js +297 -0
- package/lib/git/identity.js +150 -0
- package/lib/git/ignore.js +69 -0
- package/lib/git/index.js +41 -0
- package/lib/git/module-splitter.js +47 -0
- package/lib/git/post-push.js +101 -0
- package/lib/git/push-diagnose.js +142 -0
- package/lib/git/push.js +470 -0
- package/lib/git/remote-resolve.js +146 -0
- package/lib/git/remote.js +128 -0
- package/lib/git/repo-index.js +512 -0
- package/lib/git/repos.js +235 -0
- package/lib/git/scan-runner.js +159 -0
- package/lib/git/sensitive.js +134 -0
- package/lib/git/transport.js +430 -0
- package/lib/git/visibility.js +35 -0
- package/lib/git/wrapped-git.js +68 -0
- package/lib/http/index.js +170 -0
- package/lib/index.js +24 -0
- package/lib/link-check/index.js +187 -0
- package/lib/npm/account.js +64 -0
- package/lib/npm/install.js +211 -0
- package/lib/npm/npmrc.js +56 -0
- package/lib/npm/publish.js +167 -0
- package/lib/npm/registry.js +147 -0
- package/lib/plugin/auto-detect.js +92 -0
- package/lib/plugin/auto-push.js +154 -0
- package/lib/plugin/index.js +250 -0
- package/lib/readme-templates/readme.yml +38 -0
- package/lib/rule/compilers/credential.js +62 -0
- package/lib/rule/compilers/dataflow.js +38 -0
- package/lib/rule/compilers/file-health.js +75 -0
- package/lib/rule/compilers/frontend.js +86 -0
- package/lib/rule/compilers/func.js +35 -0
- package/lib/rule/compilers/helpers.js +71 -0
- package/lib/rule/compilers/index.js +29 -0
- package/lib/rule/compilers/link-semantic.js +45 -0
- package/lib/rule/compilers/list-kinds.js +12 -0
- package/lib/rule/compilers/numeric-kinds.js +66 -0
- package/lib/rule/compilers/regex.js +78 -0
- package/lib/rule/compilers/structure.js +80 -0
- package/lib/rule/compilers.js +17 -0
- package/lib/rule/homoglyph.js +45 -0
- package/lib/rule/loader.js +270 -0
- package/lib/rule/registry.js +115 -0
- package/lib/rule/scope.js +67 -0
- package/lib/score/docs-score.js +166 -0
- package/lib/score/index.js +140 -0
- package/lib/self/index.js +193 -0
- package/lib/skip-dirs.js +64 -0
- package/lib/tool-probes.json +50 -0
- package/lib/user-requirements.json +14 -0
- package/lib/vendor/js-yaml/LICENSE +21 -0
- package/lib/vendor/js-yaml/js-yaml.mjs +3073 -0
- package/package.json +95 -4
- package/scripts/__pycache__/module-splitter.cpython-38.pyc +0 -0
- package/scripts/audit-ext/_example-readme-present.mjs +34 -0
- package/scripts/audit-ext/variable-min-length.mjs +102 -0
- package/scripts/audit-runner.mjs +35 -0
- package/scripts/audit-runtime-check.mjs +129 -0
- package/scripts/browser-page-probe.mjs +271 -0
- package/scripts/build-client.mjs +119 -0
- package/scripts/check.mjs +88 -0
- package/scripts/clean-date-comments.py +102 -0
- package/scripts/doc-drift.mjs +200 -0
- package/scripts/doc-func.mjs +212 -0
- package/scripts/doc-tree.mjs +456 -0
- package/scripts/doc-version.mjs +220 -0
- package/scripts/frontend-preview-check.mjs +124 -0
- package/scripts/hot-path-probe-cjs.cjs +71 -0
- package/scripts/hot-path-probe-fs-shim.mjs +28 -0
- package/scripts/hot-path-probe-fsp-shim.mjs +31 -0
- package/scripts/hot-path-probe.mjs +153 -0
- package/scripts/module-splitter.py +800 -0
- package/scripts/platform-scan.mjs +168 -0
- package/scripts/preview-gen.mjs +489 -0
- package/scripts/preview-local-runner.mjs +55 -0
- package/scripts/preview-server-direct.mjs +116 -0
- package/scripts/preview-server.mjs +305 -0
- package/scripts/preview-slot-data.mjs +123 -0
- package/scripts/probe-recheck.mjs +47 -0
- package/scripts/readme-gen.mjs +268 -0
- package/scripts/rename-locator.mjs +97 -0
- package/scripts/rule-switch.mjs +97 -0
- package/scripts/rules-solo-audit.mjs +173 -0
- package/scripts/scan-file-io.mjs +713 -0
- package/scripts/scan-hardcoded-paths.mjs +125 -0
- package/scripts/scan-repos.mjs +167 -0
- package/scripts/scan-version.mjs +122 -0
- package/scripts/scrub-user-wording.mjs +420 -0
- package/scripts/symbol-index.mjs +85 -0
- package/scripts/sync-plugin-install.mjs +223 -0
- package/scripts/sync-plugin.mjs +279 -0
- package/scripts/verify-prestep.mjs +100 -0
- package/skills/dev/audit-rule-authoring.md +58 -0
- package/skills/dev/dsh-git-push.md +323 -0
- package/skills/dev/git-push-live-fix.md +45 -0
- package/skills/dsh-repo-index.md +35 -0
- package/skills/guide/guide-audit.md +167 -0
- package/skills/guide/guide-cli-scripts.md +104 -0
- package/skills/guide/guide-clone-repos.md +173 -0
- package/skills/guide/guide-commit-push.md +156 -0
- package/skills/guide/guide-inject-ui.md +166 -0
- package/skills/guide/guide-slash-completion.md +118 -0
- package/skills/workflow/README.md +21 -0
- package/skills/workflow/git-commit-discipline.md +68 -0
- package/skills/workflow/git-project-startup.md +85 -0
- package/skills/workflow/git-rebuild-process.md +57 -0
- package/skills/workflow/github-operations.md +91 -0
- package/skills/workflow/readme-sync-git-md.md +28 -0
- package/skills/workflow/task-completion-report.md +73 -0
- package/skills/workflow/tool-json-add-ask.md +35 -0
- package/skills/workflow/versioning-rule.md +211 -0
|
@@ -0,0 +1,713 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* dsh-git-push — 文件读写调用扫描器(同日升级三标签能力——识别读/写/删除三类调用)
|
|
4
|
+
*
|
|
5
|
+
* 用途:把项目代码里所有「读/写文件」的调用位置找出来,并尽力解析出读写的
|
|
6
|
+
* 文件路径/文件名——用于核查「某配置写没写、某个文件被哪些地方读写」。
|
|
7
|
+
*
|
|
8
|
+
* 扫描对象:fs 相关调用(readFileSync/readFile/writeFileSync/writeFile/appendFileSync/
|
|
9
|
+
* renameSync/rename/mkdirSync/readdirSync/existsSync/statSync/unlinkSync/rmSync/
|
|
10
|
+
* copyFileSync/chmodSync/createWriteStream/createReadStream/openSync 等)。
|
|
11
|
+
*
|
|
12
|
+
* 路径解析策略(按优先级):
|
|
13
|
+
* ① 静态字符串参数('config.json'、join(a, 'x.json') 的可计算片段)
|
|
14
|
+
* ② 模板字符串(`${dir}/x.json`,插值部分标 <expr>)
|
|
15
|
+
* ③ 变量参数(溯源同文件内的 `const x = '…'` / `const x = join(…)` 赋值,
|
|
16
|
+
* 能解析就展开,不能则标变量名 + 位置;解析不到标「(未解析)」但仍登记命中)
|
|
17
|
+
*
|
|
18
|
+
* ── 三标签(本次升级,每条命中都带)──
|
|
19
|
+
* ① **类型** type:sync / async —— 同步 I/O 落在异步路径会阻塞事件循环
|
|
20
|
+
* (由操作名是否带 Sync 后缀判定)
|
|
21
|
+
* ② **操作** kind:read / write / delete / rename —— 写类(write/delete/rename)
|
|
22
|
+
* 涉及数据安全,风险更高,默认排前
|
|
23
|
+
* ③ **上下文**:是否在 async 函数内(inAsync)、是否在循环内(inLoop)、
|
|
24
|
+
* 是否在请求处理路径上(inRequest)—— 决定这次 I/O 会不会卡住其他请求
|
|
25
|
+
* 综合出 risk 等级:🔴 high(写/删 且 并发路径)· 🟠 medium(同步阻塞或写类)· · low
|
|
26
|
+
*
|
|
27
|
+
* 用法:
|
|
28
|
+
* node scripts/scan-file-io.mjs <文件|目录>… # 扫指定路径(默认 lib/ scripts/ cli.mjs)
|
|
29
|
+
* node scripts/scan-file-io.mjs --summary # 三标签汇总视图(类型/操作/上下文/风险 计数)
|
|
30
|
+
* node scripts/scan-file-io.mjs --report # 风险报告:统计 + 改造优先级清单(文本表格)
|
|
31
|
+
* node scripts/scan-file-io.mjs --report --report-limit 50 # 清单最多 50 条
|
|
32
|
+
* node scripts/scan-file-io.mjs --json # JSON 输出(含全部标签字段)
|
|
33
|
+
* node scripts/scan-file-io.mjs --write # 只看写类操作(write/delete/rename)
|
|
34
|
+
* node scripts/scan-file-io.mjs --type sync # 按类型过滤(sync / async,可逗号多值)
|
|
35
|
+
* node scripts/scan-file-io.mjs --kind delete,rename # 按操作过滤(read/write/delete/rename)
|
|
36
|
+
* node scripts/scan-file-io.mjs --risk high # 只看高危
|
|
37
|
+
* node scripts/scan-file-io.mjs --op writeFileSync # 按操作名过滤(可逗号多值)
|
|
38
|
+
*
|
|
39
|
+
* 输出(文本):风险徽标 | 行号 | 操作 | 三标签串 | 路径参数(解析结果)
|
|
40
|
+
*/
|
|
41
|
+
import { readFileSync, readdirSync, statSync } from 'node:fs';
|
|
42
|
+
// 分级引擎改为复用 AST 层(四级标准),行级逻辑只保留路径解析
|
|
43
|
+
import { scanIoRiskAst, RISK_BADGE, RISK_LABEL, summarizeIoRisk, rankIoFixList } from '../lib/ast/io-risk.js';
|
|
44
|
+
import { join, extname, resolve, dirname, basename } from 'node:path';
|
|
45
|
+
import { fileURLToPath } from 'node:url';
|
|
46
|
+
|
|
47
|
+
/* ───────── 扫描脚本常量 ───────── */
|
|
48
|
+
const REPORT_LIMIT_DEFAULT = 20; // --report-limit 默认条数
|
|
49
|
+
const REPORT_BAR_WIDTH = 72; // 报告分隔线宽度
|
|
50
|
+
|
|
51
|
+
/* ───────────────────────── 配置 ───────────────────────── */
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* 要识别的文件操作。每个条目:
|
|
55
|
+
* op —— 精确操作名(含 Sync 后缀与否决定 **类型标签**:sync/async)
|
|
56
|
+
* kind —— **操作标签**:read | write | delete | rename | meta
|
|
57
|
+
* write —— 是否写类(数据安全风险高,供 --write 过滤与排序)
|
|
58
|
+
*/
|
|
59
|
+
const FS_OPS = [
|
|
60
|
+
// 读
|
|
61
|
+
{ op: 'readFile', kind: 'read', write: false },
|
|
62
|
+
{ op: 'readFileSync', kind: 'read', write: false },
|
|
63
|
+
{ op: 'readdir', kind: 'read', write: false },
|
|
64
|
+
{ op: 'readdirSync', kind: 'read', write: false },
|
|
65
|
+
{ op: 'createReadStream', kind: 'read', write: false },
|
|
66
|
+
// 写
|
|
67
|
+
{ op: 'writeFile', kind: 'write', write: true },
|
|
68
|
+
{ op: 'writeFileSync', kind: 'write', write: true },
|
|
69
|
+
{ op: 'appendFile', kind: 'write', write: true },
|
|
70
|
+
{ op: 'appendFileSync', kind: 'write', write: true },
|
|
71
|
+
{ op: 'createWriteStream', kind: 'write', write: true },
|
|
72
|
+
{ op: 'mkdir', kind: 'write', write: true },
|
|
73
|
+
{ op: 'mkdirSync', kind: 'write', write: true },
|
|
74
|
+
{ op: 'copyFile', kind: 'write', write: true },
|
|
75
|
+
{ op: 'copyFileSync', kind: 'write', write: true },
|
|
76
|
+
{ op: 'open', kind: 'write', write: true },
|
|
77
|
+
{ op: 'openSync', kind: 'write', write: true },
|
|
78
|
+
{ op: 'chmod', kind: 'write', write: true },
|
|
79
|
+
{ op: 'chmodSync', kind: 'write', write: true },
|
|
80
|
+
// 删除
|
|
81
|
+
{ op: 'unlink', kind: 'delete', write: true },
|
|
82
|
+
{ op: 'unlinkSync', kind: 'delete', write: true },
|
|
83
|
+
{ op: 'rm', kind: 'delete', write: true },
|
|
84
|
+
{ op: 'rmSync', kind: 'delete', write: true },
|
|
85
|
+
{ op: 'rmdir', kind: 'delete', write: true },
|
|
86
|
+
{ op: 'rmdirSync', kind: 'delete', write: true },
|
|
87
|
+
// 重命名
|
|
88
|
+
{ op: 'rename', kind: 'rename', write: true },
|
|
89
|
+
{ op: 'renameSync', kind: 'rename', write: true },
|
|
90
|
+
// 元数据(读类,不写入)
|
|
91
|
+
{ op: 'existsSync', kind: 'read', write: false },
|
|
92
|
+
{ op: 'accessSync', kind: 'read', write: false },
|
|
93
|
+
{ op: 'stat', kind: 'read', write: false },
|
|
94
|
+
{ op: 'statSync', kind: 'read', write: false },
|
|
95
|
+
{ op: 'realpathSync', kind: 'read', write: false },
|
|
96
|
+
];
|
|
97
|
+
|
|
98
|
+
/** 写类操作标签集合(--write 过滤用)。 */
|
|
99
|
+
const WRITE_KINDS = new Set(['write', 'delete', 'rename']);
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* 上下文标签:判断命中行处于什么结构里(决定这次 I/O 会不会卡住别的请求)。
|
|
103
|
+
* inAsync —— 在 `async` 函数体内(同步 I/O 在这里直接阻塞事件循环)
|
|
104
|
+
* inLoop —— 在 for/while/do/forEach/map 等循环体内(多次 I/O 放大阻塞)
|
|
105
|
+
* inRequest —— 在请求处理路径上(HTTP handler / 路由 / 回调参数名像 req/res)
|
|
106
|
+
*/
|
|
107
|
+
/** 函数签名判定用:控制流关键字前缀(这些不是函数定义)。 */
|
|
108
|
+
const CONTROL_KEYWORDS = /^\s*(?:if|for|while|switch|catch|do|else|return|await|throw|typeof|new|delete|void|in|of|case|default|try|finally|with|yield)\b/;
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* 判断一行是否是**真正的函数签名**(函数声明/函数表达式/箭头函数/方法简写)。
|
|
112
|
+
* 关键排除项(都踩过坑):
|
|
113
|
+
* · 控制流关键字开头的行(`if (x) {` 曾被当成方法简写)
|
|
114
|
+
* · 普通 const 赋值里的括号表达式(`const owner = (a && b) || ''` 曾被当成箭头函数)
|
|
115
|
+
*/
|
|
116
|
+
function isFnSignature(s) {
|
|
117
|
+
if (CONTROL_KEYWORDS.test(s)) return false;
|
|
118
|
+
return /^\s*(?:export\s+)?(?:default\s+)?async\s+function\b/.test(s)
|
|
119
|
+
|| /^\s*(?:export\s+)?function\b/.test(s)
|
|
120
|
+
|| /^\s*(?:export\s+)?(?:const|let|var)\s+[\w$]+\s*=\s*(?:async\s+)?function\b/.test(s)
|
|
121
|
+
|| /^\s*(?:export\s+)?(?:const|let|var)\s+[\w$]+\s*=\s*(?:async\s+)?(?:\([^)]*\)|[\w$]+)\s*=>/.test(s)
|
|
122
|
+
|| /^\s*(?:async\s+)?[\w$]+\s*\([^)]*\)\s*\{\s*$/.test(s);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* 剥离注释行,返回「只有代码」的行数组(用于上下文判定,避免说明文字里的
|
|
127
|
+
* handle / route 之类字样被当代码——扫描器自身注释就踩过这个坑)。
|
|
128
|
+
*/
|
|
129
|
+
function stripCommentLines(lines, uptoIdx) {
|
|
130
|
+
const out = [];
|
|
131
|
+
let inBlock = false;
|
|
132
|
+
for (let i = 0; i <= uptoIdx; i++) {
|
|
133
|
+
const raw = lines[i];
|
|
134
|
+
if (inBlock) {
|
|
135
|
+
const end = raw.indexOf('*/');
|
|
136
|
+
if (end === -1) continue;
|
|
137
|
+
inBlock = false;
|
|
138
|
+
const rest = raw.slice(end + 2);
|
|
139
|
+
if (rest.trim()) out.push(rest);
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
const open = raw.indexOf('/*');
|
|
143
|
+
if (open !== -1 && raw.indexOf('*/', open) === -1) {
|
|
144
|
+
inBlock = true;
|
|
145
|
+
const head = raw.slice(0, open);
|
|
146
|
+
if (head.trim()) out.push(head);
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
if (/^\s*\/\//.test(raw) || /^\s*\*/.test(raw)) continue;
|
|
150
|
+
out.push(raw);
|
|
151
|
+
}
|
|
152
|
+
return out;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** 从命中行向上扫描,判定是否处于 async 函数体 / 循环体内。 */
|
|
156
|
+
function scanEnclosure(lines, lineIdx) {
|
|
157
|
+
let inAsync = false;
|
|
158
|
+
let inLoop = false;
|
|
159
|
+
for (let i = lineIdx; i >= 0; i--) {
|
|
160
|
+
const code = stripLiterals(lines[i]);
|
|
161
|
+
// 上行函数签名:async function / async (...) => / function ... { ... }
|
|
162
|
+
if (i !== lineIdx && /^\s*(?:async\s+)?(?:function\b|\w+\s*\([^)]*\)\s*(?:=>)?\s*\{)/.test(code)) {
|
|
163
|
+
if (/\basync\b/.test(code)) inAsync = true;
|
|
164
|
+
}
|
|
165
|
+
// 循环结构(含数组迭代方法)
|
|
166
|
+
if (/^\s*(?:for|while|do)\b/.test(code) || /\.(?:forEach|map|filter|reduce|for\s+of)\s*\(/.test(code)) {
|
|
167
|
+
inLoop = true;
|
|
168
|
+
}
|
|
169
|
+
// 到达顶层(文件级缩进 0 的结束括号)就先停
|
|
170
|
+
if (/^\}\s*;?\s*$/.test(code) && i < lineIdx) break;
|
|
171
|
+
}
|
|
172
|
+
return { inAsync, inLoop };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* 判定是否处于**请求处理路径**:向上找最近的函数签名,在该函数体内找真实 HTTP 特征。
|
|
177
|
+
* 不限固定窗口——大 handler 里 I/O 常离签名几十行,固定 30 行窗口够不到。
|
|
178
|
+
* 特征必须具体(req.headers / req.method / res.writeHead / handleXxx( /
|
|
179
|
+
* createServer((req,res) / 成对 (req, res) 签名),孤立的 req/url 字样不算。
|
|
180
|
+
*/
|
|
181
|
+
function inRequestPath(lines, lineIdx) {
|
|
182
|
+
const codeLines = stripCommentLines(lines, lineIdx);
|
|
183
|
+
// 只保留最近一个函数体(从最后一个函数签名行到命中行),避免串到上一个函数
|
|
184
|
+
let sigStart = 0;
|
|
185
|
+
for (let i = codeLines.length - 1; i >= 0; i--) {
|
|
186
|
+
if (isFnSignature(codeLines[i])) { sigStart = i; break; }
|
|
187
|
+
}
|
|
188
|
+
const signatureText = codeLines.slice(sigStart).join('\n');
|
|
189
|
+
return /\b(?:req|request)\.(?:headers|method|url|body|on)\b/.test(signatureText)
|
|
190
|
+
|| /\bres\.(?:writeHead|write|end|setHeader|statusCode)\b/.test(signatureText)
|
|
191
|
+
|| /\b(?:handle|route|onRequest)[A-Za-z_$]*\s*\(/.test(signatureText)
|
|
192
|
+
|| /\bcreateServer\s*\(\s*(?:async\s*)?\(?\s*(?:req|request)\s*,/.test(signatureText)
|
|
193
|
+
|| /\(\s*(?:req|request)\s*,\s*(?:res|response)\s*\)/.test(signatureText);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** 判定命中行所处上下文(三标签之③)。 */
|
|
197
|
+
function contextAt(lines, lineIdx) {
|
|
198
|
+
const { inAsync, inLoop } = scanEnclosure(lines, lineIdx);
|
|
199
|
+
return { inAsync, inLoop, inRequest: inRequestPath(lines, lineIdx) };
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** 类型标签:按操作名是否带 Sync 后缀判定(同步 I/O 会阻塞事件循环)。 */
|
|
203
|
+
function ioTypeOf(opName = '') {
|
|
204
|
+
return /Sync$/.test(opName) ? 'sync' : 'async';
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** 递归时跳过的目录。 */
|
|
208
|
+
const SKIP_DIRS = new Set(['node_modules', '.git', '.trash', 'dist', 'build', '.bak']);
|
|
209
|
+
|
|
210
|
+
/* ───────────────────────── 扫描 ───────────────────────── */
|
|
211
|
+
|
|
212
|
+
/** 收集指定文件/目录下的源码文件(.js/.mjs/.cjs/.ts,跳过 node_modules 等)。 */
|
|
213
|
+
function collectFiles(targets) {
|
|
214
|
+
const out = [];
|
|
215
|
+
const walk = (p) => {
|
|
216
|
+
let st;
|
|
217
|
+
try { st = statSync(p); } catch { return; }
|
|
218
|
+
if (st.isDirectory()) {
|
|
219
|
+
let es;
|
|
220
|
+
try { es = readdirSync(p, { withFileTypes: true }); } catch { return; }
|
|
221
|
+
for (const en of es) {
|
|
222
|
+
if (SKIP_DIRS.has(en.name)) continue;
|
|
223
|
+
walk(join(p, en.name));
|
|
224
|
+
}
|
|
225
|
+
} else if (['.js', '.mjs', '.cjs', '.ts'].includes(extname(p))) {
|
|
226
|
+
out.push(p);
|
|
227
|
+
}
|
|
228
|
+
};
|
|
229
|
+
for (const t of targets) walk(resolve(t));
|
|
230
|
+
return out;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** 剔除代码中被字符串/注释/正则字面量包裹的部分,返回「可匹配」的代码片段。
|
|
234
|
+
* 用于避免正则字面量(/mkdir\(/)、字符串、注释里的操作名被误识别为调用。 */
|
|
235
|
+
/**
|
|
236
|
+
* 判断当前位置的 `/` 是「正则字面量开头」还是「除号」。
|
|
237
|
+
*
|
|
238
|
+
* 规则(原内联在 stripLiterals 里,提取后既可单独阅读也便于复用):
|
|
239
|
+
* 只有**表达式起始位置**的 `/` 才是正则开头——行首,或前一个非空字符属于
|
|
240
|
+
* `( , : ; [ ! & | ? { } + - * / % < > ~ ^`,或前面刚结束 return/typeof/case/in/of/new/
|
|
241
|
+
* delete/void/do/else/yield/await;标识符/数字/`)`/`]` 之后的 `/` 是**除号**。
|
|
242
|
+
* 此前不加区分一律当正则,导致 `readFile('/tmp/x')` 里的 `/tmp` 被当成正则开始,
|
|
243
|
+
* 把整行剩余部分吞掉 → 漏报(真实事故)。
|
|
244
|
+
*
|
|
245
|
+
* @param {string} out 已输出的代码前缀(字面量已被剥离)
|
|
246
|
+
* @param {string} next `/` 的下一个字符
|
|
247
|
+
*/
|
|
248
|
+
function isRegexStart(out, next) {
|
|
249
|
+
if (!/[A-Za-z0-9\\^$.|?*+()[\]{}]/.test(next || '')) return false;
|
|
250
|
+
const trimmed = out.trimEnd();
|
|
251
|
+
const prev = trimmed.slice(-1);
|
|
252
|
+
if (prev === '' || /[=(,:;[!&|?{}+\-*/%<>~^]/.test(prev)) return true;
|
|
253
|
+
return /\b(?:return|typeof|case|in|of|new|delete|void|do|else|yield|await)$/.test(trimmed);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* 处于「字符串 / 行注释 / 块注释 / 正则」某一态时的推进。
|
|
258
|
+
*
|
|
259
|
+
* 为什么单独成函数:这四个态的处理原与「识别态起点」混在 stripLiterals 的同一个 while 里
|
|
260
|
+
* (自审 max-cyclomatic-complexity 报 25)。提取后主循环只剩「怎么进态」,
|
|
261
|
+
* 态内推进(含转义跳两字符、块注释闭合判定)集中在这里。
|
|
262
|
+
*
|
|
263
|
+
* @param {string} line 当前行
|
|
264
|
+
* @param {number} i 当前位置
|
|
265
|
+
* @param {object} st 可变状态 { quote, lineComment, blockComment, regexMode }
|
|
266
|
+
* @returns {number} 新下标;-1 表示当前不在任何态内(交给主循环判态起点)
|
|
267
|
+
*/
|
|
268
|
+
function advanceInsideState(line, i, st) {
|
|
269
|
+
const char = line[i];
|
|
270
|
+
const next = line[i + 1];
|
|
271
|
+
if (st.lineComment) return i + 1;
|
|
272
|
+
if (st.blockComment) {
|
|
273
|
+
if (char === '*' && next === '/') { st.blockComment = false; return i + 2; }
|
|
274
|
+
return i + 1;
|
|
275
|
+
}
|
|
276
|
+
if (st.quote) {
|
|
277
|
+
if (char === '\\') return i + 2;
|
|
278
|
+
if (char === st.quote) st.quote = null;
|
|
279
|
+
return i + 1;
|
|
280
|
+
}
|
|
281
|
+
if (st.regexMode) {
|
|
282
|
+
if (char === '\\') return i + 2;
|
|
283
|
+
if (char === '/') st.regexMode = false;
|
|
284
|
+
return i + 1;
|
|
285
|
+
}
|
|
286
|
+
return -1;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function stripLiterals(line) {
|
|
290
|
+
let out = '';
|
|
291
|
+
let i = 0;
|
|
292
|
+
const st = { quote: null, lineComment: false, blockComment: false, regexMode: false };
|
|
293
|
+
while (i < line.length) {
|
|
294
|
+
const char = line[i];
|
|
295
|
+
const next = line[i + 1];
|
|
296
|
+
// 态内推进(字符串/注释/正则)
|
|
297
|
+
const advanced = advanceInsideState(line, i, st);
|
|
298
|
+
if (advanced >= 0) { i = advanced; continue; }
|
|
299
|
+
// 态起点识别
|
|
300
|
+
if (char === '/' && next === '/') { st.lineComment = true; i += 2; continue; }
|
|
301
|
+
if (char === '/' && next === '*') { st.blockComment = true; i += 2; continue; }
|
|
302
|
+
// 正则字面量判定(规则与事故说明见 isRegexStart):是正则则进入正则态,
|
|
303
|
+
// 否则当除号——落在末尾的 `out += char` 正常输出。
|
|
304
|
+
if (char === '/' && isRegexStart(out, next)) { st.regexMode = true; i++; continue; }
|
|
305
|
+
if (char === "'" || char === '"' || char === '`') { st.quote = char; i++; continue; }
|
|
306
|
+
out += char;
|
|
307
|
+
i++;
|
|
308
|
+
}
|
|
309
|
+
return out;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* 扫描单个文件,返回命中列表。
|
|
314
|
+
* @returns {Array<{file:string, line:number, op:string, path:string, raw:string}>}
|
|
315
|
+
*/
|
|
316
|
+
function scanFile(file) {
|
|
317
|
+
let text;
|
|
318
|
+
try { text = readFileSync(file, 'utf8'); } catch { return []; }
|
|
319
|
+
const lines = text.split('\n');
|
|
320
|
+
const hits = [];
|
|
321
|
+
// 本文件的 AST 分级结果(四级标准,与审计一致);解析失败则空数组,走行级兜底
|
|
322
|
+
let astHits = [];
|
|
323
|
+
try { astHits = scanIoRiskAst(text); } catch { astHits = []; }
|
|
324
|
+
// 预收集本文件的变量赋值(路径类):const x = 'str' / const x = join(...) 等
|
|
325
|
+
const varMap = collectVarAssignments(lines);
|
|
326
|
+
for (let i = 0; i < lines.length; i++) {
|
|
327
|
+
const line = lines[i];
|
|
328
|
+
const code = stripLiterals(line); // 剔除字符串/注释/正则字面量,防误识别
|
|
329
|
+
if (/^\s*import\s|^\s*\/\/|^\s*\*/.test(line)) continue;
|
|
330
|
+
for (const entry of FS_OPS) {
|
|
331
|
+
// 词边界匹配,避免 readFile 命中 readFileSync / 自定义前缀名
|
|
332
|
+
const callRe = new RegExp(`(?<![\\w$])${entry.op}\\s*\\(`);
|
|
333
|
+
if (!callRe.test(code)) continue;
|
|
334
|
+
// 参数提取失败**不丢弃命中**:字符串字面量已被 stripLiterals 剔除(防误识别),
|
|
335
|
+
// 而路径往往正是字符串字面量——此前 `arg === null → continue` 会把
|
|
336
|
+
// `await readFile('/x')` 这类整条漏报。提取不到时路径标「(未解析)」照常登记。
|
|
337
|
+
const arg = extractArg(code, entry.op, entry.op);
|
|
338
|
+
const rawArg = arg === null ? '(未解析)' : arg;
|
|
339
|
+
const resolved = arg === null ? '(未解析)' : resolvePathArg(arg, varMap, i);
|
|
340
|
+
const lineCtx = contextAt(lines, i);
|
|
341
|
+
// 上下文与分级以 AST 为准(tokenizer + 花括号配对,比行级启发式准);
|
|
342
|
+
// 查不到该 (行号,操作名) 才退回行级结果
|
|
343
|
+
const graded = riskOfByAst(astHits, i + 1, entry.op, entry, lineCtx);
|
|
344
|
+
const ctx = graded.ctx;
|
|
345
|
+
hits.push({
|
|
346
|
+
file,
|
|
347
|
+
line: i + 1,
|
|
348
|
+
op: entry.op,
|
|
349
|
+
// ── 三标签 ──
|
|
350
|
+
type: ioTypeOf(entry.op), // 类型:sync / async
|
|
351
|
+
kind: entry.kind, // 操作:read / write / delete / rename / meta
|
|
352
|
+
inAsync: ctx.inAsync, // 上下文:异步函数体内
|
|
353
|
+
inLoop: ctx.inLoop, // 上下文:循环体内
|
|
354
|
+
inRequest: ctx.inRequest, // 上下文:请求处理路径
|
|
355
|
+
inStartup: ctx.inStartup, // 上下文:启动路径(新增,四级标准)
|
|
356
|
+
risk: graded.risk, // 综合风险等级(四级,供排序/过滤)
|
|
357
|
+
riskFromAst: graded.fromAst, // 分级来源(AST / 行级兜底)
|
|
358
|
+
path: resolved,
|
|
359
|
+
raw: rawArg,
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
return hits;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* 综合风险评级(判读「这次 I/O 会不会卡住其他请求 / 会不会丢数据」):
|
|
368
|
+
* high —— 写/删/改名 且 在请求路径或循环里(并发下都可能被放大)
|
|
369
|
+
* medium —— 同步 I/O 落在 async 路径/循环里(阻塞事件循环),或写类操作
|
|
370
|
+
* low —— 其余(普通读、异步读)
|
|
371
|
+
*/
|
|
372
|
+
/**
|
|
373
|
+
* 旧行级启发式分级(3 级)——仅作 AST 不可用时的兜底。
|
|
374
|
+
* 自常规路径改用 lib/ast/io-risk.js 的四级标准(与审计一致),
|
|
375
|
+
* 本函数保留以免 AST 解析异常时整条命中丢失分级信息。
|
|
376
|
+
*/
|
|
377
|
+
function riskOfFallback(entry, ctx) {
|
|
378
|
+
const writeish = WRITE_KINDS.has(entry.kind);
|
|
379
|
+
const sync = ioTypeOf(entry.op) === 'sync';
|
|
380
|
+
if (writeish && (ctx.inRequest || ctx.inLoop)) return 'high';
|
|
381
|
+
if (sync && (ctx.inAsync || ctx.inLoop || ctx.inRequest)) return 'medium';
|
|
382
|
+
if (writeish) return 'medium';
|
|
383
|
+
return 'low';
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* 按 (行号, 操作名) 从 AST 结果查分级。
|
|
388
|
+
* AST 层在循环/函数上下文判定上比行级启发式准确(tokenizer + 花括号配对),
|
|
389
|
+
* 故以它为准;查不到(如宏/动态调用)才退回行级。
|
|
390
|
+
*
|
|
391
|
+
* @param {Array} astHits 本文件的 scanIoRiskAst 结果
|
|
392
|
+
* @param {number} line 1-based 行号
|
|
393
|
+
* @param {string} op 操作名(如 readFileSync)
|
|
394
|
+
* @param {object} entry 行级命中项
|
|
395
|
+
* @param {object} ctx 行级上下文
|
|
396
|
+
*/
|
|
397
|
+
function riskOfByAst(astHits, line, op, entry, ctx) {
|
|
398
|
+
const hit = astHits.find((h) => h.line === line && h.call === op);
|
|
399
|
+
if (!hit) return { risk: riskOfFallback(entry, ctx), ctx, fromAst: false };
|
|
400
|
+
return {
|
|
401
|
+
risk: hit.risk,
|
|
402
|
+
ctx: {
|
|
403
|
+
inAsync: hit.inAsync,
|
|
404
|
+
inLoop: hit.inLoop,
|
|
405
|
+
inRequest: hit.inRequest,
|
|
406
|
+
inStartup: hit.inStartup,
|
|
407
|
+
},
|
|
408
|
+
fromAst: true,
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/** 预收集文件级变量赋值(只收字符串/join 类路径表达式)。 */
|
|
413
|
+
function collectVarAssignments(lines) {
|
|
414
|
+
const map = new Map(); // 变量名 → { value, line }
|
|
415
|
+
for (let i = 0; i < lines.length; i++) {
|
|
416
|
+
const line = lines[i];
|
|
417
|
+
// const NAME = '...' 或 const NAME = join('...', '...')
|
|
418
|
+
const declMatch = line.match(/^\s*(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(.+?)\s*;?\s*$/);
|
|
419
|
+
if (!declMatch) continue;
|
|
420
|
+
const name = declMatch[1];
|
|
421
|
+
const valueExpr = declMatch[2].trim();
|
|
422
|
+
if (/^['"`]/.test(valueExpr) || /^join\s*\(/.test(valueExpr) || /^resolve\s*\(/.test(valueExpr)) {
|
|
423
|
+
map.set(name, { value: valueExpr, line: i + 1 });
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
return map;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/** 以匹配到的操作名为锚点,提取其括号内第一个参数(字符串/模板/变量)。 */
|
|
430
|
+
function extractArg(line, op, opName) {
|
|
431
|
+
// 操作名可能带别名(readFileSync as rfs),但行内通常是 <opName>(…)
|
|
432
|
+
const nameRe = new RegExp(`[A-Za-z_$][\\w$]*\\b`, 'g');
|
|
433
|
+
let found = null;
|
|
434
|
+
let foundIdx = -1;
|
|
435
|
+
let nameMatch;
|
|
436
|
+
while ((nameMatch = nameRe.exec(line)) !== null) {
|
|
437
|
+
if (nameMatch[0] === opName) { found = nameMatch[0]; foundIdx = nameMatch.index; break; }
|
|
438
|
+
}
|
|
439
|
+
// 备选:行内只有该操作名出现且带括号(无别名场景退化)
|
|
440
|
+
if (found === null) {
|
|
441
|
+
const simple = line.match(new RegExp(`\\b${opName}\\s*\\(`));
|
|
442
|
+
if (!simple) return null;
|
|
443
|
+
foundIdx = simple.index + simple[0].indexOf('(');
|
|
444
|
+
}
|
|
445
|
+
const openIdx = line.indexOf('(', foundIdx);
|
|
446
|
+
if (openIdx === -1) return null;
|
|
447
|
+
const after = line.slice(openIdx + 1);
|
|
448
|
+
const am = after.match(/^\s*(?:'([^']*)'|"([^"]*)"|`([^`]*)`|([A-Za-z_$][\w$]*))/);
|
|
449
|
+
if (!am) return null;
|
|
450
|
+
if (am[1] !== undefined) return am[1];
|
|
451
|
+
if (am[2] !== undefined) return am[2];
|
|
452
|
+
if (am[3] !== undefined) return `\`${am[3]}\``;
|
|
453
|
+
return am[4]; // 变量名
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/** 尽力把参数解析为可读路径:静态串原样;模板串标 <expr>;变量溯源。 */
|
|
457
|
+
function resolvePathArg(arg, varMap, lineIdx) {
|
|
458
|
+
if (arg.startsWith('`')) {
|
|
459
|
+
// 模板字符串:去掉反引号,插值标 <expr>;join(…) 展开
|
|
460
|
+
const inner = arg.slice(1, -1);
|
|
461
|
+
const cleaned = inner.replace(/\$\{[^}]*\}/g, '<expr>');
|
|
462
|
+
return `\`${cleaned}\``;
|
|
463
|
+
}
|
|
464
|
+
if (arg.startsWith("'") || arg.startsWith('"')) return arg.slice(1, -1);
|
|
465
|
+
// 变量:溯源
|
|
466
|
+
const v = varMap.get(arg);
|
|
467
|
+
if (v) return `${v.value} (L${v.line})`;
|
|
468
|
+
return `${arg} (变量未溯源)`;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/* ───────────────────────── 输出 ───────────────────────── */
|
|
472
|
+
|
|
473
|
+
/** 单条命中渲染成一行标签串(三标签 + 风险)。 */
|
|
474
|
+
function tagsOf(h) {
|
|
475
|
+
const t = [h.type === 'sync' ? '同步' : '异步', h.kind];
|
|
476
|
+
if (h.inAsync) t.push('async内');
|
|
477
|
+
if (h.inLoop) t.push('循环内');
|
|
478
|
+
if (h.inRequest) t.push('请求路径');
|
|
479
|
+
return t.join('·');
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/** 风险徽标。 */
|
|
483
|
+
function riskMark(risk) {
|
|
484
|
+
return risk === 'high' ? '🔴' : risk === 'medium' ? '🟠' : '·';
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/**
|
|
488
|
+
* 文本输出(按风险降序,高危在前)。
|
|
489
|
+
* @param {Array} hits 命中
|
|
490
|
+
* @param {object} opts { writeOnly, riskOnly, summary }
|
|
491
|
+
*/
|
|
492
|
+
function printText(hits, { writeOnly = false, riskOnly = '', summary = false } = {}) {
|
|
493
|
+
let filtered = writeOnly ? hits.filter((h) => WRITE_KINDS.has(h.kind)) : hits;
|
|
494
|
+
if (riskOnly) filtered = filtered.filter((h) => h.risk === riskOnly);
|
|
495
|
+
if (!filtered.length) { console.log('(未命中任何文件操作)'); return; }
|
|
496
|
+
|
|
497
|
+
// 汇总视图:按 类型/操作/风险 计数(复用 CLI 同款 summarize)
|
|
498
|
+
if (summary) {
|
|
499
|
+
summarize(filtered);
|
|
500
|
+
return;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
// 按文件分组;组内按行号
|
|
504
|
+
const byFile = new Map();
|
|
505
|
+
for (const entry of filtered) {
|
|
506
|
+
if (!byFile.has(entry.file)) byFile.set(entry.file, []);
|
|
507
|
+
byFile.get(entry.file).push(entry);
|
|
508
|
+
}
|
|
509
|
+
for (const [file, hs] of [...byFile.entries()].sort()) {
|
|
510
|
+
console.log(`\n── ${file} (${hs.length}) ──`);
|
|
511
|
+
for (const entry of hs.sort((a, b) => a.line - b.line)) {
|
|
512
|
+
console.log(` ${riskMark(entry.risk)} L${String(entry.line).padEnd(4)} ${entry.op.padEnd(14)} ${tagsOf(entry)}`);
|
|
513
|
+
console.log(` ${entry.path}`);
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
console.log(`\n合计 ${filtered.length} 处文件操作(🔴high=写/删且并发路径 · 🟠medium=同步阻塞或写类 · ·low=普通读)`);
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
/** JSON 输出(含全部标签字段)。 */
|
|
520
|
+
function printJson(hits) {
|
|
521
|
+
console.log(JSON.stringify(hits, null, 2));
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/* ───────────────────────── 主流程 ───────────────────────── */
|
|
525
|
+
|
|
526
|
+
/**
|
|
527
|
+
* 主流程(可被 CLI 复用)。
|
|
528
|
+
* @param {string[]} argv 参数(不含 node/脚本名)
|
|
529
|
+
*/
|
|
530
|
+
export function main(argv = process.argv.slice(2)) {
|
|
531
|
+
const args = argv;
|
|
532
|
+
const json = args.includes('--json');
|
|
533
|
+
const writeOnly = args.includes('--write');
|
|
534
|
+
const summary = args.includes('--summary');
|
|
535
|
+
const report = args.includes('--report');
|
|
536
|
+
let riskOnly = '';
|
|
537
|
+
const opFilter = [];
|
|
538
|
+
const kindFilter = [];
|
|
539
|
+
const typeFilter = [];
|
|
540
|
+
// 多值支持:--kind delete,rename 或 --kind delete --kind rename 均可
|
|
541
|
+
const splitMulti = (v) => String(v || '').split(',').map((x) => x.trim()).filter(Boolean);
|
|
542
|
+
// 记录「被 flag 消费掉的位置」,供 targets 精确排除——此前用黑名单正则排除单值,
|
|
543
|
+
// `--kind delete,rename` 这种逗号多值整体不匹配黑名单,被当成路径去扫(结果空)。
|
|
544
|
+
const consumed = new Set();
|
|
545
|
+
const takeValue = (i) => { consumed.add(i + 1); return args[i + 1]; };
|
|
546
|
+
let reportLimit = REPORT_LIMIT_DEFAULT;
|
|
547
|
+
for (let i = 0; i < args.length; i++) {
|
|
548
|
+
if (args[i] === '--op') opFilter.push(...splitMulti(takeValue(i)));
|
|
549
|
+
else if (args[i] === '--kind') kindFilter.push(...splitMulti(takeValue(i)));
|
|
550
|
+
else if (args[i] === '--type') typeFilter.push(...splitMulti(takeValue(i)));
|
|
551
|
+
else if (args[i] === '--risk') riskOnly = takeValue(i);
|
|
552
|
+
else if (args[i] === '--report-limit') reportLimit = Number(takeValue(i)) || REPORT_LIMIT_DEFAULT;
|
|
553
|
+
}
|
|
554
|
+
const targets = args.filter((a, i) => !a.startsWith('--') && !consumed.has(i));
|
|
555
|
+
const root = dirname(fileURLToPath(import.meta.url));
|
|
556
|
+
const defaults = targets.length ? targets : [
|
|
557
|
+
join(root, '..', 'lib'),
|
|
558
|
+
join(root, '..', 'scripts'),
|
|
559
|
+
join(root, '..', 'cli.mjs'),
|
|
560
|
+
join(root, '..', 'lib', 'client.js'),
|
|
561
|
+
];
|
|
562
|
+
const files = collectFiles(defaults);
|
|
563
|
+
let hits = [];
|
|
564
|
+
for (const f of files) hits = hits.concat(scanFile(f));
|
|
565
|
+
if (opFilter.length) hits = hits.filter((h) => opFilter.some((o) => h.op.includes(o)));
|
|
566
|
+
if (kindFilter.length) hits = hits.filter((h) => kindFilter.includes(h.kind));
|
|
567
|
+
if (typeFilter.length) hits = hits.filter((h) => typeFilter.includes(h.type));
|
|
568
|
+
// 高危优先(同风险按文件/行号稳定排序)
|
|
569
|
+
hits.sort((a, b) => {
|
|
570
|
+
const rank = { high: 0, medium: 1, low: 2 };
|
|
571
|
+
return (rank[a.risk] - rank[b.risk]) || a.file.localeCompare(b.file) || a.line - b.line;
|
|
572
|
+
});
|
|
573
|
+
if (json) printJson(hits);
|
|
574
|
+
else if (report) printReport(hits, { limit: reportLimit });
|
|
575
|
+
else printText(hits, { writeOnly, riskOnly, summary });
|
|
576
|
+
return hits;
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
/** 供 CLI 复用:扫描 + 按标签过滤,返回命中数组(不打印)。 */
|
|
580
|
+
export function scanFileIo(opts = {}) {
|
|
581
|
+
const { targets = [], opFilter = [], kindFilter = [], typeFilter = [], riskOnly = '', writeOnly = false } = opts;
|
|
582
|
+
const root = dirname(fileURLToPath(import.meta.url));
|
|
583
|
+
const dirs = targets.length ? targets : [
|
|
584
|
+
join(root, '..', 'lib'), join(root, '..', 'scripts'),
|
|
585
|
+
join(root, '..', 'cli.mjs'), join(root, '..', 'lib', 'client.js'),
|
|
586
|
+
];
|
|
587
|
+
const files = collectFiles(dirs);
|
|
588
|
+
let hits = [];
|
|
589
|
+
for (const f of files) hits = hits.concat(scanFile(f));
|
|
590
|
+
if (writeOnly) hits = hits.filter((h) => WRITE_KINDS.has(h.kind));
|
|
591
|
+
if (opFilter.length) hits = hits.filter((h) => opFilter.some((o) => h.op.includes(o)));
|
|
592
|
+
if (kindFilter.length) hits = hits.filter((h) => kindFilter.includes(h.kind));
|
|
593
|
+
if (typeFilter.length) hits = hits.filter((h) => typeFilter.includes(h.type));
|
|
594
|
+
if (riskOnly) hits = hits.filter((h) => h.risk === riskOnly);
|
|
595
|
+
hits.sort((a, b) => {
|
|
596
|
+
const rank = { high: 0, medium: 1, low: 2 };
|
|
597
|
+
return (rank[a.risk] - rank[b.risk]) || a.file.localeCompare(b.file) || a.line - b.line;
|
|
598
|
+
});
|
|
599
|
+
return hits;
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
/** 供 CLI 复用:打印三标签汇总。 */
|
|
603
|
+
export function summarize(hits) {
|
|
604
|
+
const count = (key) => {
|
|
605
|
+
const counter = new Map();
|
|
606
|
+
for (const entry of hits) counter.set(entry[key], (counter.get(entry[key]) || 0) + 1);
|
|
607
|
+
return [...counter.entries()].sort((a, b) => b[1] - a[1]);
|
|
608
|
+
};
|
|
609
|
+
console.log(`合计 ${hits.length} 处文件操作\n`);
|
|
610
|
+
console.log('【类型】' + count('type').map(([k, v]) => `${k === 'sync' ? '同步' : '异步'} ${v}`).join(' '));
|
|
611
|
+
console.log('【操作】' + count('kind').map(([k, v]) => `${k} ${v}`).join(' '));
|
|
612
|
+
console.log('【上下文】异步函数内 ' + hits.filter((h) => h.inAsync).length
|
|
613
|
+
+ ' 循环内 ' + hits.filter((h) => h.inLoop).length
|
|
614
|
+
+ ' 请求路径 ' + hits.filter((h) => h.inRequest).length
|
|
615
|
+
+ ' 启动路径 ' + hits.filter((h) => h.inStartup).length);
|
|
616
|
+
// 四级风险(起与审计 robustness/io-risk 同一标准)
|
|
617
|
+
console.log('【风险】' + ['high', 'medium', 'low', 'safe']
|
|
618
|
+
.map((r) => `${RISK_BADGE[r]}${RISK_LABEL[r]} ${hits.filter((h) => h.risk === r).length}`)
|
|
619
|
+
.join(' '));
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
/**
|
|
623
|
+
* --report:统计 + 改造优先级清单(文本表格)。
|
|
624
|
+
* 与 --summary(用户视角的计数概览)不同,本视图面向「下一步改哪个」:
|
|
625
|
+
* ① 统计块:同步/异步占比、四级风险分布、I/O 密集文件排行
|
|
626
|
+
* ② 优先级清单:高风险项按 风险 > 写类 > 同步 排序,给出行号、上下文与理由
|
|
627
|
+
* 数据来源:AST 层 summarizeIoRisk / rankIoFixList(与审计同一标准)。
|
|
628
|
+
*
|
|
629
|
+
* @param {Array} hits 全部命中
|
|
630
|
+
* @param {{limit?:number}} opts limit=清单最多条数(默认 20)
|
|
631
|
+
*/
|
|
632
|
+
function printReport(hits, opts = {}) {
|
|
633
|
+
const limit = Number(opts.limit) > 0 ? Number(opts.limit) : REPORT_LIMIT_DEFAULT;
|
|
634
|
+
const sum = summarizeIoRisk(hits);
|
|
635
|
+
|
|
636
|
+
const bar = '─'.repeat(REPORT_BAR_WIDTH);
|
|
637
|
+
console.log(bar);
|
|
638
|
+
console.log(' I/O 风险报告(四级标准,与审计 robustness/io-risk 一致)');
|
|
639
|
+
console.log(bar);
|
|
640
|
+
console.log(` 总调用 ${sum.total} 处` + (sum.total
|
|
641
|
+
? `(同步 ${sum.sync} / 异步 ${sum.total - sum.sync},同步占比 ${Math.round(sum.sync / sum.total * 100)}%)`
|
|
642
|
+
: ''));
|
|
643
|
+
if (sum.total === 0) {
|
|
644
|
+
console.log(' 未发现文件 I/O 调用。');
|
|
645
|
+
console.log(bar);
|
|
646
|
+
return;
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
// 风险分布
|
|
650
|
+
console.log('');
|
|
651
|
+
console.log(' 【风险分布】');
|
|
652
|
+
for (const r of ['high', 'medium', 'low', 'safe']) {
|
|
653
|
+
const n = sum.byRisk[r] || 0;
|
|
654
|
+
const pct = Math.round(n / sum.total * 100);
|
|
655
|
+
const filled = Math.round(pct / 100 * 24);
|
|
656
|
+
console.log(` ${RISK_BADGE[r]} ${RISK_LABEL[r].padEnd(2)} ${String(n).padStart(4)} 处 ${'█'.repeat(filled)}${'░'.repeat(24 - filled)} ${pct}%`);
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
// 操作类别分布
|
|
660
|
+
console.log('');
|
|
661
|
+
console.log(' 【操作类别】');
|
|
662
|
+
const kindLabel = { read: '读取', write: '写入', delete: '删除', rename: '改名', meta: '元信息' };
|
|
663
|
+
console.log(' ' + Object.entries(sum.byKind)
|
|
664
|
+
.filter(([, v]) => v > 0)
|
|
665
|
+
.map(([k, v]) => `${kindLabel[k] || k} ${v}`)
|
|
666
|
+
.join(' '));
|
|
667
|
+
|
|
668
|
+
// I/O 密集文件排行
|
|
669
|
+
if (sum.byFile && sum.byFile.length) {
|
|
670
|
+
console.log('');
|
|
671
|
+
console.log(' 【I/O 密集文件 TOP' + Math.min(10, sum.byFile.length) + '】(改造收益从高到低)');
|
|
672
|
+
sum.byFile.slice(0, 10).forEach(({ file, count }, i) => {
|
|
673
|
+
console.log(` ${String(i + 1).padStart(2)}. ${String(count).padStart(3)} 处 ${file}`);
|
|
674
|
+
});
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
// 优先级清单
|
|
678
|
+
const ranked = rankIoFixList(hits).filter((h) => h.risk === 'high' || h.risk === 'medium');
|
|
679
|
+
console.log('');
|
|
680
|
+
console.log(' 【改造优先级清单】(高风险在前;风险 > 写类 > 同步)');
|
|
681
|
+
if (!ranked.length) {
|
|
682
|
+
console.log(' ✓ 无高风险/中风险项');
|
|
683
|
+
} else {
|
|
684
|
+
for (const entry of ranked.slice(0, limit)) {
|
|
685
|
+
const ctxs = [];
|
|
686
|
+
if (entry.inAsync) ctxs.push('异步路径');
|
|
687
|
+
if (entry.inLoop) ctxs.push('循环内');
|
|
688
|
+
if (entry.inRequest) ctxs.push('请求路径');
|
|
689
|
+
if (entry.inStartup) ctxs.push('启动路径');
|
|
690
|
+
const callName = entry.call || entry.op || '(未知调用)';
|
|
691
|
+
console.log(` ${String(entry.rank).padStart(3)}. ${RISK_BADGE[entry.risk]}${RISK_LABEL[entry.risk]} ${entry.file}:${entry.line}`);
|
|
692
|
+
console.log(` ${callName} · ${entry.kind} · ${ctxs.join('+') || '—'}`);
|
|
693
|
+
if (entry.reason) console.log(` ${entry.reason}`);
|
|
694
|
+
console.log(` 路径: ${entry.path || '(未解析)'}`);
|
|
695
|
+
}
|
|
696
|
+
if (ranked.length > limit) {
|
|
697
|
+
console.log(` … 另有 ${ranked.length - limit} 项,用 --report-limit <n> 调整`);
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
// 验证提醒
|
|
702
|
+
console.log('');
|
|
703
|
+
console.log(' 【改造后验证】');
|
|
704
|
+
console.log(' · 同步改异步后:跑一遍受影响路径的测试,确认无时序变化');
|
|
705
|
+
console.log(' · 循环内改并发:确认并发上限(避免 fd 耗尽),保留原顺序语义');
|
|
706
|
+
console.log(' · 写/删类改造:先确认有备份或 git 历史(可恢复)');
|
|
707
|
+
console.log(bar);
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
// 直接运行时入口(被 import 时不执行)
|
|
711
|
+
if (import.meta.url === `file://${process.argv[1]}` || process.argv[1]?.endsWith('scan-file-io.mjs')) {
|
|
712
|
+
main();
|
|
713
|
+
}
|