dsh-git-push 2.18.2 → 2.20.17

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 (90) hide show
  1. package/.gitignore +4 -0
  2. package/README.md +12 -5
  3. package/cli-audit.mjs +141 -0
  4. package/cli-tool.mjs +86 -0
  5. package/cli.mjs +116 -324
  6. package/lib/ARCHITECTURE.md +3 -0
  7. package/lib/app/audit-api.js +1 -1
  8. package/lib/app/command-registry.js +16 -3
  9. package/lib/app/constants.js +9 -0
  10. package/lib/app/handlers/clone.js +12 -3
  11. package/lib/app/handlers/http-constants.js +11 -2
  12. package/lib/app/handlers/npm.js +4 -2
  13. package/lib/app/handlers/repos.js +10 -1
  14. package/lib/app/handlers/settings.js +9 -1
  15. package/lib/app/http-handlers.js +24 -3
  16. package/lib/app/inject-text.js +1 -0
  17. package/lib/app/schema-audit.js +42 -0
  18. package/lib/app/schema.js +19 -19
  19. package/lib/app/scope-check.js +69 -0
  20. package/lib/app/settings-bridge.js +51 -0
  21. package/lib/app/tool-call.js +56 -7
  22. package/lib/ast/credential.js +130 -14
  23. package/lib/ast/dataflow.js +127 -10
  24. package/lib/ast/index.js +2 -0
  25. package/lib/ast/naming.js +9 -1
  26. package/lib/ast/scope-collisions.js +228 -0
  27. package/lib/ast/treesitter.js +142 -1
  28. package/lib/audit/history.js +1 -1
  29. package/lib/audit/orchestrate.js +93 -6
  30. package/lib/audit/scope-policy.js +110 -0
  31. package/lib/audit-rules/audit-rules-dsh.yml +16 -1
  32. package/lib/audit-rules/audit-rules-nodejs.yml +21 -6
  33. package/lib/audit-rules/audit-rules-paths.yml +7 -1
  34. package/lib/audit-ui-sdk/contract.js +117 -0
  35. package/lib/audit-ui-sdk/index.js +17 -0
  36. package/lib/checks/common.js +4 -4
  37. package/lib/checks/dispatch.js +5 -0
  38. package/lib/checks/index.js +2 -0
  39. package/lib/checks/regex.js +8 -3
  40. package/lib/checks/scope-collision.js +68 -0
  41. package/lib/cli/commands-audit.mjs +13 -18
  42. package/lib/cli/commands-tool.mjs +93 -0
  43. package/lib/cli/commands-vcs.mjs +2 -1
  44. package/lib/cli/shared.mjs +448 -0
  45. package/lib/client-parts/{account.js → git/account.js} +1 -1
  46. package/lib/client-parts/{actions.js → git/actions.js} +26 -11
  47. package/lib/client-parts/{apply.js → git/apply.js} +1 -1
  48. package/lib/client-parts/{browser.js → git/browser.js} +1 -1
  49. package/lib/client-parts/{const.js → git/const.js} +6 -1
  50. package/lib/client-parts/{controller.js → git/controller.js} +23 -11
  51. package/lib/client-parts/{icons.js → git/icons.js} +1 -1
  52. package/lib/client-parts/{loader.js → git/loader.js} +1 -1
  53. package/lib/client-parts/{npm.js → git/npm.js} +1 -1
  54. package/lib/client-parts/{page.js → git/page.js} +11 -21
  55. package/lib/client-parts/{repo.js → git/repo.js} +1 -1
  56. package/lib/client-parts/{settings.js → git/settings.js} +1 -1
  57. package/lib/client-parts/{utils.js → git/utils.js} +1 -1
  58. package/lib/client.js +75 -354
  59. package/lib/commit-push/pre-commit-engine.js +388 -0
  60. package/lib/commit-push.js +44 -17
  61. package/lib/exempt/index.js +5 -2
  62. package/lib/git/ignore.js +6 -4
  63. package/lib/git/init-compat.js +83 -4
  64. package/lib/git/push.js +25 -2
  65. package/lib/git/sensitive.js +30 -1
  66. package/lib/git/transport.js +31 -10
  67. package/lib/http/index.js +82 -10
  68. package/lib/lint-adapter/detect.js +161 -0
  69. package/lib/lint-adapter/index.js +50 -0
  70. package/lib/lint-adapter/runner.js +133 -0
  71. package/lib/npm/npmrc.js +22 -5
  72. package/lib/rule/compilers/structure.js +24 -0
  73. package/lib/score/index.js +36 -4
  74. package/lib/self/index.js +1 -1
  75. package/package.json +25 -2
  76. package/scripts/audit-gate.mjs +235 -0
  77. package/scripts/build-client.mjs +15 -8
  78. package/scripts/bump-version.mjs +20 -5
  79. package/scripts/check-js-scope.mjs +87 -0
  80. package/scripts/check.mjs +51 -4
  81. package/scripts/scan-file-io.mjs +5 -1
  82. package/scripts/scan-version.mjs +10 -7
  83. package/skills/dev/dsh-git-push.md +70 -2
  84. package/skills/guide/guide-audit.md +11 -11
  85. package/skills/guide/guide-cli-scripts.md +3 -3
  86. package/skills/guide/guide-commit-push.md +2 -2
  87. package/skills/guide/guide-inject-ui.md +0 -16
  88. package/assets/start.sh +0 -396
  89. package/scripts/scan-hardcoded-paths.mjs +0 -125
  90. /package/lib/client-parts/{audit.js → audit/audit.js} +0 -0
package/assets/start.sh DELETED
@@ -1,396 +0,0 @@
1
- #!/usr/bin/env bash
2
- # ============================================================
3
- # dsh-git-push 预览服务器启停脚本(模板源:bench-template/server/lib/preview/start.sh,下发改自用)
4
- # 用法:
5
- # ./start.sh start [--port PORT]
6
- # ./start.sh restart [--port PORT] # 默认命令
7
- # ./start.sh stop
8
- # ./start.sh status
9
- # ./start.sh --port PORT # 兼容旧用法(等价 restart)
10
- # PID:插件根 / dsh-git-push.pid(见 pid-file-at-project-root)
11
- # ============================================================
12
- set -uo pipefail
13
-
14
- # 脚本落在 assets/;ROOT 上溯到插件根
15
- ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
16
- PROJECT_NAME="$(basename "$ROOT")"
17
- # 预览服务入口:scripts/preview-server.mjs(2026-10-13 合并后单入口;--local/--shot/--direct 均在其内部)
18
- # 服务工作目录仍取脚本所在目录(assets/),入口用绝对路径调用,与 cwd 无关。
19
- SERVER_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
20
- SERVER_ENTRY="$ROOT/scripts/preview-server.mjs"
21
- PID_FILE="$ROOT/${PROJECT_NAME}.pid"
22
- LOG_FILE="$SERVER_DIR/preview-server.log"
23
- DEFAULT_PORT="${DEFAULT_PORT:-30999}"
24
- LOG_ROTATE_BYTES=$((10 * 1024 * 1024))
25
- STOP_WAIT_SEC=10
26
- START_WAIT_SEC="${START_WAIT_SEC:-15}"
27
-
28
- # ---------- 颜色 ----------
29
- C_GREEN="" C_YELLOW="" C_RED="" C_DIM="" C_RESET=""
30
- if [ -t 1 ] && [ -z "${NO_COLOR:-}" ] && [ "${TERM:-}" != "dumb" ]; then
31
- C_GREEN=$'\033[32m'
32
- C_YELLOW=$'\033[33m'
33
- C_RED=$'\033[31m'
34
- C_DIM=$'\033[2m'
35
- C_RESET=$'\033[0m'
36
- fi
37
- ok() { printf '%s%s%s\n' "$C_GREEN" "$*" "$C_RESET"; }
38
- warn() { printf '%s%s%s\n' "$C_YELLOW" "$*" "$C_RESET"; }
39
- err() { printf '%s%s%s\n' "$C_RED" "$*" "$C_RESET"; }
40
- dim() { printf '%s%s%s\n' "$C_DIM" "$*" "$C_RESET"; }
41
-
42
- # 历史 PID 位置(迁移兼容)
43
- legacy_pid_files() {
44
- printf '%s\n' \
45
- "$SERVER_DIR/app.pid" \
46
- "$SERVER_DIR/${PROJECT_NAME}.pid" \
47
- "/tmp/${PROJECT_NAME}.pid" \
48
- "/tmp/start-${PROJECT_NAME}.pid"
49
- }
50
-
51
- # ---------- Node 定位(独立可搬运,内联不 source)----------
52
- find_node() {
53
- local c nvm
54
- for c in \
55
- "$ROOT/tool/node/bin/node" \
56
- /usr/local/bin/node \
57
- /opt/homebrew/bin/node \
58
- /opt/node/bin/node \
59
- /var/packages/Node.js_v24/target/usr/local/bin/node \
60
- /var/packages/Node.js_v22/target/usr/local/bin/node \
61
- /var/packages/Node.js_v20/target/usr/local/bin/node \
62
- /var/packages/DeepSeekHarness-NAS/target/bin/node \
63
- node; do
64
- if [ -x "$c" ]; then NODE_BIN="$c"; return 0; fi
65
- if command -v "$c" >/dev/null 2>&1; then NODE_BIN="$(command -v "$c")"; return 0; fi
66
- done
67
- for nvm in "$HOME"/.nvm/versions/node/*/bin/node; do
68
- if [ -x "$nvm" ]; then NODE_BIN="$nvm"; return 0; fi
69
- done
70
- return 1
71
- }
72
-
73
- if ! find_node; then
74
- err "❌ 找不到 node。请安装 Node.js,或把官方二进制解压到 tool/node/"
75
- exit 1
76
- fi
77
- ok "✓ Node: $NODE_BIN ($("$NODE_BIN" -v 2>/dev/null))"
78
-
79
- file_size() {
80
- local f="$1"
81
- [ -f "$f" ] || { echo 0; return; }
82
- stat -c%s "$f" 2>/dev/null || stat -f%z "$f" 2>/dev/null || wc -c < "$f"
83
- }
84
-
85
- human_size() {
86
- local n="$1"
87
- if [ "$n" -ge 1048576 ]; then awk -v n="$n" 'BEGIN{printf "%.1fMB", n/1048576}'; else awk -v n="$n" 'BEGIN{printf "%.1fKB", n/1024}'; fi
88
- }
89
-
90
- # ---------- token 解析:DSH_PREVIEW_TOKEN env > DSH_HOME 上级 DeepSeekHarness-NAS.log 最新 token ----------
91
- resolve_token() {
92
- if [ -n "${DSH_PREVIEW_TOKEN:-}" ]; then printf '%s' "$DSH_PREVIEW_TOKEN"; return 0; fi
93
- local dsh_home="${DSH_HOME:-}"
94
- [ -n "$dsh_home" ] || dsh_home="$HOME/.dsh"
95
- local log_file="$dsh_home/../DeepSeekHarness-NAS.log"
96
- if [ -f "$log_file" ]; then
97
- grep -o 'token=[a-zA-Z0-9_-]\{20,\}' "$log_file" 2>/dev/null | tail -n1 | sed 's/^token=//'
98
- return 0
99
- fi
100
- return 0 # 找不到就空,预览服务(scripts/preview-server.mjs)内部还有兜底
101
- }
102
-
103
- # ---------- 端口工具 ----------
104
- port_in_use() {
105
- local port="$1" out=""
106
- if command -v ss >/dev/null 2>&1; then
107
- out="$(ss -tln 2>/dev/null)"
108
- elif command -v netstat >/dev/null 2>&1; then
109
- out="$(netstat -tln 2>/dev/null)"
110
- fi
111
- [ -n "$out" ] || return 1
112
- printf '%s\n' "$out" | awk -v p="$port" '
113
- $4 ~ ("[.:]" p "$") { found = 1; exit }
114
- END { exit(found ? 0 : 1) }'
115
- }
116
-
117
- port_pids() {
118
- local port="$1" out=""
119
- if command -v ss >/dev/null 2>&1; then
120
- out="$(ss -tlnp 2>/dev/null | awk -v p="$port" '$4 ~ ("[.:]" p "$") {print}')"
121
- elif command -v netstat >/dev/null 2>&1; then
122
- out="$(netstat -tlnp 2>/dev/null | awk -v p="$port" '$4 ~ ("[.:]" p "$") {print}')"
123
- fi
124
- [ -n "$out" ] || return 0
125
- printf '%s\n' "$out" | grep -o 'pid=[0-9]*' | cut -d= -f2
126
- printf '%s\n' "$out" | awk '{n=split($NF,a,"/"); if (n>1 && a[1] ~ /^[0-9]+$/) print a[1]}'
127
- }
128
-
129
- wait_port_free() {
130
- local port="$1" timeout="${2:-10}" i=0
131
- while [ "$i" -lt "$((timeout * 2))" ]; do
132
- port_in_use "$port" || return 0
133
- sleep 0.5
134
- i=$((i + 1))
135
- done
136
- return 1
137
- }
138
-
139
- listen_line() {
140
- local port="$1"
141
- if command -v ss >/dev/null 2>&1; then
142
- ss -tln 2>/dev/null | awk -v p=":$port" '$0 ~ p {print; exit}'
143
- elif command -v netstat >/dev/null 2>&1; then
144
- netstat -tln 2>/dev/null | awk -v p=":$port" '$0 ~ p {print; exit}'
145
- fi
146
- }
147
-
148
- pid_alive() {
149
- local p="$1"
150
- [ -n "$p" ] && kill -0 "$p" 2>/dev/null
151
- }
152
-
153
- read_pid_file() {
154
- local f="$1"
155
- [ -f "$f" ] && [ -s "$f" ] || return 1
156
- tr -d ' \t\r\n' < "$f"
157
- }
158
-
159
- collect_live_pids() {
160
- # 2026-09-20 修:端口必须随调用方实际端口走(--port 覆盖时查 DEFAULT_PORT 会抓错
161
- # 别的项目同端口进程 → 误报「已在运行」)。缺省仍用 DEFAULT_PORT 兼容旧调用。
162
- local f p seen=" " port="${1:-$DEFAULT_PORT}"
163
- for f in "$PID_FILE" $(legacy_pid_files); do
164
- p="$(read_pid_file "$f" 2>/dev/null || true)"
165
- if pid_alive "$p"; then
166
- case "$seen" in
167
- *" $p "*) ;;
168
- *) seen="$seen$p "; printf '%s\n' "$p" ;;
169
- esac
170
- fi
171
- done
172
- local lp
173
- lp="$(port_pids "$port")"
174
- for p in $lp; do
175
- case "$seen" in
176
- *" $p "*) ;;
177
- *) seen="$seen$p "; printf '%s\n' "$p" ;;
178
- esac
179
- done
180
- }
181
-
182
- rotate_log() {
183
- [ -f "$LOG_FILE" ] || return 0
184
- local sz
185
- sz="$(file_size "$LOG_FILE")"
186
- [ "$sz" -gt "$LOG_ROTATE_BYTES" ] || return 0
187
- local ts dest
188
- ts="$(date +%Y%m%d-%H%M%S)"
189
- dest="${LOG_FILE}.${ts}"
190
- mv "$LOG_FILE" "$dest" || return 0
191
- if command -v gzip >/dev/null 2>&1; then
192
- gzip -f "$dest" && dest="${dest}.gz"
193
- fi
194
- warn "⚠️ 日志超过 10MB,已轮转: $dest ($(human_size "$sz"))"
195
- }
196
-
197
- start_server() {
198
- # --port 覆盖时全局 PORT 已在 main 入口解析(stop/restart/status 同端口语义),
199
- # 这里保留原内联解析兜底(兼容直接调用函数),但统一用全局 PORT。
200
- local port_opt=""
201
- while [ $# -gt 0 ]; do
202
- case "$1" in
203
- --port) port_opt="${2:-}"; shift 2 ;;
204
- *) shift ;;
205
- esac
206
- done
207
- local port="${PORT:-${port_opt:-$DEFAULT_PORT}}"
208
- local live
209
- live="$(collect_live_pids "$port" | head -n 1 || true)"
210
- if [ -n "$live" ]; then
211
- warn "⚠️ 已在运行 (PID $live, 端口 $port)。如需重启: ./start.sh restart"
212
- return 1
213
- fi
214
- if port_in_use "$port"; then
215
- warn "⏳ 端口 $port 仍被占用,等待释放(最多 ${START_WAIT_SEC}s)..."
216
- if ! wait_port_free "$port" "$START_WAIT_SEC"; then
217
- err "❌ 端口 $port 等待 ${START_WAIT_SEC}s 仍未释放,放弃启动。"
218
- err " 排查:netstat -tlnp | grep :$port 或换端口: ./start.sh --port <新端口>"
219
- return 1
220
- fi
221
- ok "✓ 端口 $port 已释放"
222
- fi
223
- rm -f "$PID_FILE"
224
- mkdir -p "$SERVER_DIR"
225
- rotate_log
226
- local token
227
- token="$(resolve_token)"
228
- local cmd=("$NODE_BIN" "$SERVER_ENTRY" --port "$port" --no-open)
229
- if [ -n "$token" ]; then cmd+=("--token" "$token"); fi
230
- cd "$SERVER_DIR" || exit 1
231
- if command -v setsid >/dev/null 2>&1; then
232
- setsid nohup "${cmd[@]}" >> "$LOG_FILE" 2>&1 < /dev/null &
233
- else
234
- nohup "${cmd[@]}" >> "$LOG_FILE" 2>&1 < /dev/null &
235
- fi
236
- echo $! > "$PID_FILE"
237
- local new_pid okflag=0 i
238
- new_pid="$(cat "$PID_FILE")"
239
-
240
- for i in $(seq 1 8); do
241
- sleep 1
242
- if curl -sf -m 3 "http://127.0.0.1:$port/preview-ping" > /dev/null 2>&1; then
243
- okflag=1
244
- break
245
- fi
246
- pid_alive "$new_pid" || break
247
- done
248
- if [ "$okflag" = 1 ]; then
249
- ok "✅ 启动成功 PID=$new_pid 端口=$port"
250
- echo " 页面: http://<本机IP>:$port"
251
- echo " 日志: $LOG_FILE"
252
- echo " PID: $PID_FILE"
253
- else
254
- err "❌ 启动失败(8 秒内未通过健康检查),最近日志:"
255
- tail -15 "$LOG_FILE" 2>/dev/null
256
- return 1
257
- fi
258
- }
259
-
260
- stop_one() {
261
- local pid="$1"
262
- warn "⏹ SIGTERM PID=$pid (最多等 ${STOP_WAIT_SEC}s)"
263
- kill "$pid" 2>/dev/null || true
264
- local i
265
- for i in $(seq 1 "$STOP_WAIT_SEC"); do
266
- if ! pid_alive "$pid"; then
267
- ok "✓ PID $pid 已在 ${i}s 内退出"
268
- return 0
269
- fi
270
- sleep 1
271
- done
272
- if pid_alive "$pid"; then
273
- warn "⚠️ ${STOP_WAIT_SEC}s 未退出,SIGKILL PID=$pid"
274
- kill -9 "$pid" 2>/dev/null || true
275
- sleep 1
276
- fi
277
- if pid_alive "$pid"; then
278
- err "❌ PID $pid 仍在,请检查"
279
- return 1
280
- fi
281
- ok "✓ PID $pid 已强制结束"
282
- }
283
-
284
- stop_server() {
285
- local pids
286
- pids="$(collect_live_pids "$PORT" || true)"
287
- if [ -z "$pids" ]; then
288
- warn "⚠️ 未运行(无有效 PID)"
289
- rm -f "$PID_FILE"
290
- local f
291
- for f in $(legacy_pid_files); do rm -f "$f"; done
292
- return 0
293
- fi
294
- local rc=0
295
- for p in $pids; do
296
- stop_one "$p" || rc=1
297
- done
298
- rm -f "$PID_FILE"
299
- local f
300
- for f in $(legacy_pid_files); do rm -f "$f"; done
301
- if [ "$rc" = 0 ]; then
302
- ok "✅ 已停止"
303
- else
304
- err "❌ 停止未完成"
305
- fi
306
- return "$rc"
307
- }
308
-
309
- status_server() {
310
- local port="${PORT:-$DEFAULT_PORT}"
311
- echo "======== $PROJECT_NAME 预览服务器 ========"
312
- echo "根目录: $ROOT"
313
- echo "PID文件: $PID_FILE$([ -f "$PID_FILE" ] && echo " (存在)" || echo " (无)")"
314
-
315
- local p
316
- p="$(read_pid_file "$PID_FILE" 2>/dev/null || true)"
317
- if pid_alive "$p"; then
318
- ok "进程: ✓ PID $p"
319
- ps -o pid=,ppid=,etime=,rss=,stat=,args= -p "$p" 2>/dev/null | while IFS= read -r line; do
320
- dim " $line"
321
- done
322
- elif [ -n "$p" ]; then
323
- err "进程: ✗ PID 文件有 $p 但进程已退出"
324
- else
325
- err "进程: ✗ 未运行"
326
- fi
327
-
328
- local lis
329
- lis="$(listen_line "$port")"
330
- if [ -n "$lis" ]; then
331
- ok "监听: ✓ 端口 $port"
332
- dim " $lis"
333
- else
334
- warn "监听: 未发现 :$port"
335
- fi
336
-
337
- local curlout code time
338
- curlout="$(curl -sS -m 5 -o /tmp/${PROJECT_NAME}-status.body -w '%{http_code} %{time_total}' "http://127.0.0.1:$port/preview-ping" 2>/dev/null || echo "000 0")"
339
- code="${curlout%% *}"
340
- time="${curlout#* }"
341
- if [ "$code" = "200" ]; then
342
- ok "HTTP: ✓ GET /preview-ping $code ${time}s"
343
- head -c 80 "/tmp/${PROJECT_NAME}-status.body" 2>/dev/null; echo
344
- else
345
- err "HTTP: ✗ GET /preview-ping HTTP $code"
346
- fi
347
- rm -f "/tmp/${PROJECT_NAME}-status.body"
348
-
349
- if [ -f "$LOG_FILE" ]; then
350
- local sz mtime
351
- sz="$(file_size "$LOG_FILE")"
352
- mtime="$(date -r "$LOG_FILE" '+%Y-%m-%d %H:%M:%S' 2>/dev/null || stat -c %y "$LOG_FILE" 2>/dev/null | cut -d. -f1)"
353
- echo "日志: $LOG_FILE $(human_size "$sz") 更新 $mtime"
354
- echo "-------- 最近 8 行 --------"
355
- tail -8 "$LOG_FILE" 2>/dev/null
356
- else
357
- warn "日志: 尚无 $LOG_FILE"
358
- fi
359
- }
360
-
361
- CMD="${1:-restart}"
362
- if [ "$CMD" = "--port" ]; then
363
- CMD="restart"
364
- elif [ "$CMD" = "start" ] || [ "$CMD" = "stop" ] || [ "$CMD" = "restart" ] || [ "$CMD" = "status" ]; then
365
- shift
366
- else
367
- CMD="restart"
368
- fi
369
-
370
- # 全局端口解析(2026-09-20 修):start/restart 带 --port 时,stop/status 必须按同一端口
371
- # 收集存活进程——否则 restart --port X 会先按默认端口停掉**别的项目**的同端口服务(SIGTERM→SIGKILL 误杀)。
372
- PORT="${DEFAULT_PORT:-30999}"
373
- if [ $# -ge 2 ]; then
374
- for ((i = 1; i <= $#; i++)); do
375
- if [ "${!i}" = "--port" ] && [ $((i + 1)) -le $# ]; then
376
- PORT="${@:$((i + 1)):1}"
377
- break
378
- fi
379
- done
380
- fi
381
-
382
- case "$CMD" in
383
- start) start_server "$@" ;;
384
- stop) stop_server ;;
385
- restart)
386
- stop_server
387
- sleep 1
388
- start_server "$@"
389
- ;;
390
- status) status_server ;;
391
- *)
392
- err "❌ 未知命令: $CMD"
393
- echo "可用命令: start, stop, restart, status"
394
- exit 1
395
- ;;
396
- esac
@@ -1,125 +0,0 @@
1
- #!/usr/bin/env node
2
- // dsh-skip-i18n: CLI 输出硬编码中文为产品行为(无 i18n 需求)
3
- /**
4
- * scan-hardcoded-paths.mjs — 硬编码绝对路径的 dry-run 展示与改写(**调用审计引擎**)
5
- *
6
- * ⚠️ 本脚本**不含任何检测逻辑**(曾自带一份 PATTERNS,已删除 ✗ —— 同一事实两份实现必然分叉)。
7
- * 检测的唯一来源是审计引擎:
8
- * · 规则声明(正则初筛):lib/audit-rules/audit-rules-paths.yml → paths/hardcoded-absolute-path
9
- * · 精筛实现(fs 可访问性 + 相对路径换算):lib/checks/hardcoded-path.js
10
- * 本脚本只做三件事:① 跑引擎拿 findings(确认哪些文件/行被规则判为硬编码路径);
11
- * ② 展示 dry-run 表(可访问 ⇒ 附相对路径;不可访问 ⇒ 仅警告);③ `--write` 时才改写。
12
- *
13
- * 用法:
14
- * node scripts/scan-hardcoded-paths.mjs [--root <目录>] [--write] [--json] [--quiet]
15
- * --write 才写盘(默认 dry-run);--json 机器可读。
16
- */
17
- import { readFileSync, writeFileSync, existsSync } from 'node:fs';
18
- import { resolve, relative, join } from 'node:path';
19
- import { fileURLToPath } from 'node:url';
20
- import { hardcodedAbsPathHits, describeHardcodedAbsPath } from '../lib/checks/hardcoded-path.js';
21
- import { auditFull } from '../lib/audit/orchestrate.js';
22
-
23
- /** 本脚本只服务这一条规则(口径与引擎一致)。 */
24
- export const RULE_ID = 'paths/hardcoded-absolute-path';
25
-
26
- const argv = process.argv.slice(2);
27
- const has = (f) => argv.includes(f);
28
- const val = (f, d = '') => { const i = argv.indexOf(f); return i >= 0 && argv[i + 1] ? argv[i + 1] : d; };
29
-
30
- /**
31
- * 跑审计引擎,取本规则的 findings(**引擎是检测的唯一来源**)。
32
- * @returns {Promise<Array<{file:string,line:number,message:string}>>}
33
- */
34
- export async function engineFindings(root) {
35
- const abs = resolve(root);
36
- const res = await auditFull(abs, { scope: 'full' });
37
- const out = [];
38
- const walk = (x) => {
39
- if (Array.isArray(x)) return x.forEach(walk);
40
- if (x && typeof x === 'object') {
41
- const id = x.ruleId || x.id || x.rule;
42
- if (id && String(id).includes('hardcoded-absolute-path')) {
43
- out.push({ file: String(x.file || ''), line: Number(x.line) || 0, message: String(x.message || '') });
44
- }
45
- Object.values(x).forEach(walk);
46
- }
47
- };
48
- walk(res?.findings || res);
49
- return out;
50
- }
51
-
52
- /**
53
- * 组装 dry-run 报告:以**引擎 findings** 判定"哪些行是问题",用**引擎精筛实现**取详情
54
- * (可访问性 + 相对路径),两者同源 ⇒ 不会出现"脚本说有问题、审计说没问题"的分叉。
55
- */
56
- export async function scanHardcodedPaths(root) {
57
- const abs = resolve(root);
58
- const findings = await engineFindings(abs);
59
- const byFile = new Map();
60
- for (const f of findings) {
61
- const p = f.file ? (f.file.startsWith('/') ? f.file : join(abs, f.file)) : '';
62
- if (!p || !existsSync(p)) continue;
63
- if (!byFile.has(p)) byFile.set(p, new Set());
64
- byFile.get(p).add(f.line);
65
- }
66
- const hits = [];
67
- for (const [file, lines] of byFile) {
68
- const text = readFileSync(file, 'utf8');
69
- // 同一行可能被多条模式命中(如 `file:///volume9/x` 同时命中 file-url 与 posix)⇒
70
- // 同一行只保留**最具体**(raw 最长)的那条,避免一行报两次、计数虚高。
71
- const byLine = new Map();
72
- for (const h of hardcodedAbsPathHits(text, file, abs)) {
73
- if (!lines.has(h.line)) continue;
74
- const prev = byLine.get(h.line);
75
- if (!prev || h.raw.length > prev.raw.length) byLine.set(h.line, h);
76
- }
77
- for (const h of byLine.values()) hits.push({ ...h, file, relFile: relative(abs, file) || file });
78
- }
79
- return { root: abs, findings: findings.length, hits };
80
- }
81
-
82
- /** CLI 主流程。 */
83
- async function main() {
84
- const ROOT = resolve(val('--root', process.cwd()));
85
- const WRITE = has('--write');
86
- const JSON_OUT = has('--json');
87
- const QUIET = has('--quiet');
88
- const { hits } = await scanHardcodedPaths(ROOT);
89
- const accessible = hits.filter((h) => h.accessible);
90
- const inaccessible = hits.filter((h) => !h.accessible);
91
- const byOs = hits.reduce((a, h) => ((a[h.os] = (a[h.os] || 0) + 1), a), {});
92
-
93
- if (JSON_OUT) {
94
- console.log(JSON.stringify({ ok: hits.length === 0, root: ROOT, total: hits.length, accessible: accessible.length, inaccessible: inaccessible.length, byOs, hits }, null, 2));
95
- process.exit(hits.length ? 1 : 0);
96
- }
97
- if (!QUIET) console.log(`扫描根:${ROOT}(检测来源:审计引擎 ${RULE_ID})`);
98
- if (!hits.length) { console.log('硬编码绝对路径 ✅ 未发现'); process.exit(0); }
99
- for (const h of hits) {
100
- console.log(`⚠️ ${h.relFile}:${h.line} [${h.os}] ${h.raw}`);
101
- console.log(` ${h.accessible ? '→ 可访问 ⇒ dry-run 相对路径:' + (h.relative || '.') : '(本机不可访问 ⇒ 仅警告,无法换算)'}`);
102
- }
103
- console.log(`\n汇总:命中 ${hits.length} · 可访问 ${accessible.length} · 不可访问 ${inaccessible.length} · 分类 ${JSON.stringify(byOs)}`);
104
- if (!WRITE) { console.log('(dry-run:未写入任何文件;要真改加 --write)'); process.exit(hits.length ? 1 : 0); }
105
-
106
- let changed = 0;
107
- const byFile = new Map();
108
- for (const h of accessible) if (h.relative) { if (!byFile.has(h.file)) byFile.set(h.file, []); byFile.get(h.file).push(h); }
109
- for (const [file, list] of byFile) {
110
- let text = readFileSync(file, 'utf8');
111
- for (const h of list) {
112
- if (!text.includes(h.raw)) continue;
113
- console.log(` 改写 ${relative(ROOT, file)}: ${h.raw} → ${h.relative} (${describeHardcodedAbsPath(h)})`);
114
- text = text.split(h.raw).join(h.relative);
115
- changed += 1;
116
- }
117
- writeFileSync(file, text, 'utf8');
118
- }
119
- console.log(`✅ --write 完成:改写 ${changed} 处`);
120
- process.exit(0);
121
- }
122
-
123
- // ⚠️ 入口判断必须用 fileURLToPath:`new URL(...).pathname` 是 URL 编码的(含中文路径时是 %E5%B7%A5…),
124
- // 与 process.argv[1] 永不相等 ⇒ main() 静默不执行(实测踩到)。
125
- if (process.argv[1] && resolve(process.argv[1]) === resolve(fileURLToPath(import.meta.url))) main();
File without changes