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,274 @@
1
+ /**
2
+ * Git 执行层 · 凭据
3
+ *
4
+ * 职责:解析/持久化 GitHub token 与 SSH 公钥、生成 SSH 密钥、脱敏展示。
5
+ *
6
+ * **凭据只读写 config.json**(彻底收敛):
7
+ * - token → config.json `githubToken` 键(唯一真源;不再读/写 github-token 平铺文件)
8
+ * - 公钥 → config.json `sshPub` 键(唯一真源;不再读/写 *.pub 平铺文件)
9
+ * - 私钥 → 仍是文件(id_rsa/id_ed25519/id_ecdsa,ssh 命令行必需,无法进 json)
10
+ * - 覆盖顺序:显式参数 → 环境变量 → 显式文件路径 → config.json
11
+ * 明文凭据只落本机配置目录(0600),不进仓库;写入侧拒绝脱敏值(防回显串污染真凭据)。
12
+ */
13
+
14
+ import { spawnSync } from 'node:child_process';
15
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync } from 'node:fs';
16
+ import { dirname, join, resolve } from 'node:path';
17
+ import { readJson, writeJsonAtomic, updateJsonAtomic } from './atomic-json.js';
18
+
19
+ /* ───────── 凭据常量 ───────── */
20
+ const PUB_FINGERPRINT_MAX_LEN = 20; // 公钥显示为指纹的最小长度(超过才截断)
21
+ const TOKEN_CHECK_TIMEOUT_MS = 30_000; // token 在线校验超时
22
+ const CONFIG_FILE_NAME = 'config.json'; // 插件配置文件名(token/公钥唯一真源)
23
+
24
+ /* ───────────────────────── 凭据:token / ssh 探测 ───────────────────────── */
25
+
26
+ /** 插件配置目录:DSH_HOME/git-push → HOME/.dsh/git-push → cwd/.dsh/git-push。 */
27
+ export function credentialsDir({ workspaceRoot = '' } = {}) {
28
+ if (process.env.DSH_HOME) return join(process.env.DSH_HOME, 'git-push');
29
+ if (process.env.HOME) return join(process.env.HOME, '.dsh', 'git-push');
30
+ if (workspaceRoot) return join(dirname(resolve(workspaceRoot)), '.dsh', 'git-push');
31
+ return join(process.cwd(), '.dsh', 'git-push');
32
+ }
33
+
34
+ /** 确保凭据目录存在(0700)。失败返回 { ok:false, error }。 */
35
+ function ensureCredentialsDir(workspaceRoot) {
36
+ const dir = credentialsDir({ workspaceRoot });
37
+ try { mkdirSync(dir, { recursive: true, mode: 0o700 }); } catch (e) { return { ok: false, error: `创建凭据目录失败: ${e?.message || e}` }; }
38
+ return { ok: true, dir };
39
+ }
40
+
41
+ /**
42
+ * SSH 私钥探测(全部候选,按偏好顺序):配置目录 id_rsa → id_ed25519 → id_ecdsa。
43
+ * 与 resolveSshKey 的区别:返回全部存在的候选而非首个——配置目录里可能同时躺着一把
44
+ * 已登记到 GitHub、一把没登记的,推送时需逐个试到能用的那把。
45
+ * @returns {Array<{keyPath: string, kind: string}>}
46
+ */
47
+ export function resolveSshKeys({ workspaceRoot = '' } = {}) {
48
+ const dir = credentialsDir({ workspaceRoot });
49
+ const found = [];
50
+ for (const name of ['id_rsa', 'id_ed25519', 'id_ecdsa']) {
51
+ const p = join(dir, name);
52
+ try {
53
+ if (existsSync(p)) found.push({ keyPath: p, kind: name });
54
+ } catch { /* 跳过 */ }
55
+ }
56
+ return found;
57
+ }
58
+
59
+ /** SSH 私钥探测(首个可用):配置目录 id_rsa → id_ed25519 → id_ecdsa。 */
60
+ export function resolveSshKey({ workspaceRoot = '' } = {}) {
61
+ const dir = credentialsDir({ workspaceRoot });
62
+ for (const name of ['id_rsa', 'id_ed25519', 'id_ecdsa']) {
63
+ const p = join(dir, name);
64
+ try {
65
+ if (existsSync(p)) return { keyPath: p, kind: name };
66
+ } catch { /* 跳过 */ }
67
+ }
68
+ return { keyPath: '', kind: '' };
69
+ }
70
+
71
+ /**
72
+ * token 解析(**凭据只读 config.json**, 彻底收敛):
73
+ * 1) 显式传入 opts.token
74
+ * 2) 环境变量 DSH_GIT_PUSH_TOKEN / GITHUB_TOKEN
75
+ * 3) opts.tokenPath(显式指定的外部文件,调用方明确给出才读)
76
+ * 4) repoPath/.git-push-token(仓库级显式覆盖文件)
77
+ * 5) **config.json 的 githubToken 键**(唯一真源)
78
+ * 配置目录下的 github-token / token 平铺文件**不再作为读取来源**(历史遗留,易残留占位符/旧值,
79
+ * 被误当有效凭据)。只回传 source,不回传明文给调用链以外的层。
80
+ * @returns {{token: string, source: string}}
81
+ */
82
+ export function resolveToken({ token = '', tokenPath = '', repoPath = '', workspaceRoot = '' } = {}) {
83
+ if (String(token || '').trim()) return { token: String(token).trim(), source: 'explicit' };
84
+ for (const env of ['DSH_GIT_PUSH_TOKEN', 'GITHUB_TOKEN']) {
85
+ const t = String(process.env[env] || '').trim();
86
+ // 环境变量同样校验格式(ghp_/github_pat_ 开头),非法跳过
87
+ if (t && /^(gh[pous]_|github_pat_)/.test(t)) return { token: t, source: `env:${env}` };
88
+ }
89
+ // 显式指定的文件路径(调用方明确给出才读,非隐式探测)
90
+ const explicitFiles = [];
91
+ if (tokenPath) explicitFiles.push(tokenPath);
92
+ if (repoPath) explicitFiles.push(join(repoPath, '.git-push-token'));
93
+ for (const p of explicitFiles) {
94
+ try {
95
+ if (!existsSync(p)) continue;
96
+ const t = readFileSync(p, 'utf8').trim();
97
+ if (t && /^(gh[pous]_|github_pat_)/.test(t)) return { token: t, source: p };
98
+ } catch { /* 读不到跳过 */ }
99
+ }
100
+ // 唯一真源:插件 config.json 的 githubToken 键
101
+ const credDir = credentialsDir({ workspaceRoot });
102
+ if (credDir) {
103
+ const cfgPath = join(credDir, CONFIG_FILE_NAME);
104
+ try {
105
+ const t = String(readJson(cfgPath)?.githubToken || '').trim();
106
+ if (t && /^(gh[pous]_|github_pat_)/.test(t)) return { token: t, source: cfgPath };
107
+ } catch { /* 配置不存在/坏 JSON 跳过 */ }
108
+ }
109
+ return { token: '', source: '' };
110
+ }
111
+
112
+ /* ═══════════════ 账号检查 + SSH 密钥生成(补齐 D34) ═══════════════ */
113
+
114
+ /** Token 脱敏(maskToken:前 4…后 4;过短打 ****)。 */
115
+ export function maskToken(token = '') {
116
+ const t = String(token || '');
117
+ if (t.length < 8) return t ? '****' : '';
118
+ return `${t.slice(0, 4)}…${t.slice(-4)}`;
119
+ }
120
+
121
+ /** 读取 SSH 公钥(彻底收敛:**只读 config.json 的 sshPub 键**,不再回退 *.pub 文件)。 */
122
+ export function readSshPub({ workspaceRoot = '' } = {}) {
123
+ const dir = credentialsDir({ workspaceRoot });
124
+ // 1) config.json sshPub 键(persistSshPub / 设置侧边栏保存的主存)
125
+ try {
126
+ const cfg = join(dir, CONFIG_FILE_NAME);
127
+ const cfgObj = readJson(cfg);
128
+ const pub = String((cfgObj && cfgObj.sshPub) || '').trim();
129
+ if (pub) return { configured: true, pub, file: cfg, fingerprint: pub.length > PUB_FINGERPRINT_MAX_LEN ? `${pub.slice(0, 12)}…${pub.slice(-8)}` : '' };
130
+ } catch { /* 配置不存在/坏 JSON → 视为未配置 */ }
131
+ // 彻底收敛:**不再回退读 *.pub 平铺文件**(凭据只读写 config.json,避免「文件有、
132
+ // json 无」两处状态打架;生成密钥后由 generateSshKey/gen-ssh-key 端点写入 config.json)。
133
+ return { configured: false, pub: '', file: '', fingerprint: '' };
134
+ }
135
+
136
+ /**
137
+ * 脱敏值检测(isMaskedValue):前端回显/日志用的打码串绝不能被当作真凭据写回。
138
+ * 命中 ⇢ 拒绝写入,防止「保存 sshkey 时把脱敏 token 覆盖真实 token」这类污染。
139
+ */
140
+ export function isMaskedValue(v = '') {
141
+ const s = String(v || '');
142
+ return s.includes('…') || s.includes('****') || s.includes('...') || /^ghp_?$/.test(s) || /^gh[pous]_…/.test(s);
143
+ }
144
+
145
+ /**
146
+ * 持久化 GitHub token(persistGithubToken)——**只写 config.json 的 githubToken 键**。
147
+ * 彻底收敛:不再写配置目录 github-token 平铺文件(历史遗留:两处状态打架、
148
+ * 平铺文件残留占位符被误当真凭据)。读取侧同步只认 config.json。
149
+ * @param {string} token GitHub token(ghp_ / github_pat_ 开头)
150
+ * @param {object} [opts] { workspaceRoot }
151
+ * @returns {{ok:boolean, file?:string, error?:string}}
152
+ */
153
+ export function persistGithubToken(token, { workspaceRoot = '' } = {}) {
154
+ const t = String(token || '').trim();
155
+ if (!t) return { ok: false, error: 'token 为空' };
156
+ if (isMaskedValue(t)) return { ok: false, error: 'token 是脱敏值(含 …/****),拒绝写入——请输入完整 token' };
157
+ if (!/^(gh[pous]_|github_pat_)/.test(t)) return { ok: false, error: 'token 格式不对(需要 ghp_ / github_pat_ 开头)' };
158
+ const dirRes = ensureCredentialsDir(workspaceRoot);
159
+ if (!dirRes.ok) return dirRes;
160
+ const cfg = join(dirRes.dir, CONFIG_FILE_NAME);
161
+ const wr = updateJsonAtomic(cfg, (cur) => ({ ...cur, githubToken: t }));
162
+ if (!wr.ok) return { ok: false, error: wr.error || `${CONFIG_FILE_NAME} 写入失败` };
163
+ return { ok: true, file: cfg, config: cfg };
164
+ }
165
+
166
+ /**
167
+ * 持久化 SSH 公钥(persistSshPub)——**只写 config.json 的 sshPub 键**。
168
+ * 彻底收敛:不再写配置目录 *.pub 平铺文件(历史遗留:出现「公钥只落 id_rsa.pub、
169
+ * config.json 里没有」,设置页重启回读为空)。读取侧同步只认 config.json。
170
+ * @param {string} pub 公钥内容(ssh-ed25519 / ssh-rsa / ecdsa 开头)
171
+ * @returns {{ok:boolean, file?:string, error?:string}}
172
+ */
173
+ export function persistSshPub(pub, { workspaceRoot = '' } = {}) {
174
+ const t = String(pub || '').trim();
175
+ if (!t) return { ok: false, error: '公钥为空' };
176
+ if (isMaskedValue(t) && !/^ssh-/.test(t)) return { ok: false, error: '公钥是脱敏值,拒绝写入' };
177
+ if (!/^(ssh-(ed25519|rsa|ecdsa)|ecdsa-sha2-nistp\d+)\s+\S+/.test(t)) {
178
+ return { ok: false, error: '公钥格式不对(需要 ssh-ed25519 / ssh-rsa 开头)' };
179
+ }
180
+ const dirRes = ensureCredentialsDir(workspaceRoot);
181
+ if (!dirRes.ok) return dirRes;
182
+ const cfg = join(dirRes.dir, CONFIG_FILE_NAME);
183
+ const wr = updateJsonAtomic(cfg, (cur) => ({ ...cur, sshPub: t }));
184
+ if (!wr.ok) return { ok: false, error: wr.error || `${CONFIG_FILE_NAME} 写入失败` };
185
+ return { ok: true, file: cfg, config: cfg };
186
+ }
187
+
188
+ /**
189
+ * 持久化 npm token(persistNpmToken)——**只写 config.json 的 npmToken 键**。
190
+ *
191
+ * ⚠️ 原子性铁律:npmToken 与 githubToken **同文件**,必须用 updateJsonAtomic 一次完成「读-改-写」;
192
+ * 若拆成 readJson → writeJsonAtomic 两步,第二次写会把 github 的键整个覆盖掉(用户实测提醒)。
193
+ * 校验口径:空值拒绝 / 拒绝脱敏值(防把 UI 显示的 **** 写回)/ 含空白字符视为粘贴错误;
194
+ * 不校验前缀——自建 registry 的 token 形态各异,过度限制会挡住合法用法。
195
+ * @param {string} token npm token
196
+ * @param {object} [opts] { workspaceRoot }
197
+ * @returns {{ok:boolean, file?:string, error?:string}}
198
+ */
199
+ export function persistNpmToken(token, { workspaceRoot = '' } = {}) {
200
+ const t = String(token || '').trim();
201
+ if (!t) return { ok: false, error: 'token 为空' };
202
+ if (isMaskedValue(t)) return { ok: false, error: 'token 是脱敏值(含 …/****),拒绝写入——请输入完整 token' };
203
+ if (/\s/.test(t)) return { ok: false, error: 'token 含空白字符(疑似粘贴错误)' };
204
+ const dirRes = ensureCredentialsDir(workspaceRoot);
205
+ if (!dirRes.ok) return dirRes;
206
+ const cfg = join(dirRes.dir, CONFIG_FILE_NAME);
207
+ const wr = updateJsonAtomic(cfg, (cur) => ({ ...cur, npmToken: t }));
208
+ if (!wr.ok) return { ok: false, error: wr.error || `${CONFIG_FILE_NAME} 写入失败` };
209
+ return { ok: true, file: cfg, config: cfg };
210
+ }
211
+
212
+ /**
213
+ * 读 npm token(readNpmToken)——只读 npmToken 键,不触碰其它键;未配置返回空串(不抛错)。
214
+ * @param {object} [opts] { workspaceRoot }
215
+ * @returns {string} token 原文(调用方负责脱敏后再展示)
216
+ */
217
+ export function readNpmToken({ workspaceRoot = '' } = {}) {
218
+ try {
219
+ const cfg = join(credentialsDir({ workspaceRoot }), CONFIG_FILE_NAME);
220
+ if (!existsSync(cfg)) return '';
221
+ const j = readJson(cfg) || {};
222
+ return typeof j.npmToken === 'string' ? j.npmToken.trim() : '';
223
+ } catch {
224
+ return '';
225
+ }
226
+ }
227
+
228
+ /**
229
+ * 按邮箱生成 SSH 密钥对(generateSshKey:ssh-keygen -t rsa -b 4096 -C email)。
230
+ * force=true 先改名备份旧密钥(可恢复)再生成;私钥永不离开本机。
231
+ * @param {string} email 邮箱(x@y.z)
232
+ * @param {object} [opts] { workspaceRoot, force }
233
+ * @returns {{ok:boolean, error?:string, email?:string, privateKey?:string, pubFile?:string, pub?:string}}
234
+ */
235
+ export function generateSshKey(email, { workspaceRoot = '', force = false } = {}) {
236
+ const em = String(email || '').trim();
237
+ if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(em)) return { ok: false, error: '邮箱格式不对(需要 x@y.z)' };
238
+ const dirRes = ensureCredentialsDir(workspaceRoot);
239
+ if (!dirRes.ok) return dirRes;
240
+ const dir = dirRes.dir;
241
+ const priv = join(dir, 'id_rsa');
242
+ const pub = join(dir, 'id_rsa.pub');
243
+ if (existsSync(priv) && !force) {
244
+ return { ok: false, error: `私钥已存在 ${priv}(不想覆盖请先备份或传 force)` };
245
+ }
246
+ if (force) {
247
+ const stamp = Date.now();
248
+ for (const f of [priv, pub]) {
249
+ try {
250
+ if (existsSync(f)) renameSync(f, `${f}.bak-${stamp}`);
251
+ } catch { /* 备份失败不阻断生成 */ }
252
+ }
253
+ }
254
+ const r = spawnSync('ssh-keygen', ['-t', 'rsa', '-b', '4096', '-C', em, '-N', '', '-f', priv], {
255
+ encoding: 'utf8',
256
+ timeout: TOKEN_CHECK_TIMEOUT_MS,
257
+ stdio: ['pipe', 'pipe', 'pipe'],
258
+ });
259
+ if (r.status !== 0) {
260
+ return { ok: false, error: `ssh-keygen 失败: ${(r.stderr || r.stdout || '').trim().slice(0, 200)}` };
261
+ }
262
+ let pubLine = '';
263
+ try { pubLine = readFileSync(pub, 'utf8').trim(); } catch { /* 公钥读失败:下面统一报不可读 */ }
264
+ if (!pubLine) return { ok: false, error: '公钥文件生成后不可读' };
265
+ try { chmodSync(priv, 0o600); chmodSync(pub, 0o644); } catch { /* CIFS 卷可能改不了 mode */ }
266
+ // 关键修复:生成后**同步把公钥写入 config.json 的 sshPub 键**——此前只产出
267
+ // id_rsa.pub 文件,config.json 里没有公钥,设置页重启回读为空(「sshkey 没保存 json」的根因)。
268
+ // 私钥仍是文件(ssh 命令必需,不能进 json);公钥以 config.json 为真源。
269
+ let cfgWritten = false;
270
+ try {
271
+ cfgWritten = updateJsonAtomic(join(dir, CONFIG_FILE_NAME), (cur) => ({ ...cur, sshPub: pubLine })).ok;
272
+ } catch { /* 写 config 失败不影响密钥已生成,返回值里标注 */ }
273
+ return { ok: true, email: em, privateKey: priv, pubFile: pub, pub: pubLine, configWritten: cfgWritten };
274
+ }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * GitHub 端点与镜像(快通道)—— **全插件唯一出处**。
3
+ *
4
+ * 为什么集中到这里:插件的 github 访问原本分散在多处各自写死 URL
5
+ * · api.js —— API 基址 GH_API
6
+ * · clone-download.js —— blob API / contents API / raw.githubusercontent 三类 URL
7
+ * · wrapped-git.js —— git 透传(走本地 git 协议)
8
+ * 加"快通道"时若逐处改,必然出现口径漂移(有的走镜像、有的不走)。集中一次,处处复用。
9
+ *
10
+ * 快通道口径(`DSH_GIT_MIRROR_PREFIX`,**默认关**;第三方镜像会看到流量,必须显式开启):
11
+ * ① **web / raw / codeload 类 github.com URL 走镜像** —— 国内镜像(如 gh-proxy.com)
12
+ * 代理的正是这类;实测(群晖 193,2026-10-03)codeload 21KB/s → gh-proxy 12MB/s。
13
+ * ② **api.github.com 不走镜像** —— 镜像一般不代理 API;更重要的是 API 通道是
14
+ * **逐 blob 拉取、为断点续传而设计**的(每个 blob 独立请求、失败只重试那一个),
15
+ * 改基址会破坏可续性与已下进度。故 API 基址保持直连,仅在此收口成单一常量。
16
+ * ③ git 协议类由 git 原生 `url.<base>.insteadOf` 实现,见 mirrorGitConfigEnv()。
17
+ */
18
+
19
+ /** 默认镜像前缀:克隆等**只读**访问默认走 gh-proxy.com(可用环境变量覆盖或关闭)。 */
20
+ export const DEFAULT_MIRROR_PREFIX = 'https://gh-proxy.com/';
21
+ /** 显式关闭镜像的取值(环境变量设为其中之一即走直连)。 */
22
+ const MIRROR_OFF = new Set(['off', 'none', 'no', 'false', '0', '-']);
23
+
24
+ /**
25
+ * 当前镜像前缀(确保以 / 结尾)。
26
+ * 取值顺序:环境变量 DSH_GIT_MIRROR_PREFIX(设为 off/none/no/false/0/- 表示关闭)
27
+ * → 未设置时用 DEFAULT_MIRROR_PREFIX(默认 gh-proxy)。
28
+ * 注意:默认开启**只影响只读请求** —— 写操作与带 token 的请求由 withMirror 的双闸门拦住。
29
+ */
30
+ export function mirrorPrefix() {
31
+ const raw = String(process.env.DSH_GIT_MIRROR_PREFIX ?? '').trim();
32
+ if (MIRROR_OFF.has(raw.toLowerCase())) return '';
33
+ const use = raw || DEFAULT_MIRROR_PREFIX;
34
+ return use.endsWith('/') ? use : use + '/';
35
+ }
36
+
37
+ const MIRRORABLE = ['https://github.com/', 'https://raw.githubusercontent.com/', 'https://codeload.github.com/'];
38
+ // api.github.com **也是可镜像的**(实测 gh-proxy 代理该端点返回 HTTP 200),但只允许**读**:
39
+ // 本插件的 API 通道同时承载写(transport.js 走 Git Data API 推送 blob → tree → commit → ref),
40
+ // 写请求带 token,绝不能经第三方 ⇒ 故镜像策略按「HTTP 方法」而非「主机名」限定。
41
+ const MIRRORABLE_API = ['https://api.github.com/'];
42
+
43
+ /**
44
+ * 按需把 github 的 web/raw/codeload(以及**只读请求**下的 api)URL 改走镜像;其余原样返回。
45
+ *
46
+ * 两道闸门(缺一不可):
47
+ * · `mode === 'write'`(push 等写操作)—— 不镜像(git 层同理,见 mirrorGitConfigEnv);
48
+ * · 非 GET 请求 —— 不镜像(API 写通道带 token)。
49
+ * 为什么只做前缀拼接就够:镜像 URL 形如 https://gh-proxy.com/https://api.github.com/...,
50
+ * 请求模型不变(仍是逐 blob 独立请求、失败只重试那一个),因此**不破坏断点续传与已下进度**。
51
+ *
52
+ * @param {string} url
53
+ * @param {{method?:string, mode?:'read'|'write'}} [opts]
54
+ * @returns {string}
55
+ */
56
+ export function withMirror(url, { method = 'GET', mode = 'read', noMirror = false } = {}) {
57
+ const base = mirrorPrefix();
58
+ if (!base || typeof url !== 'string') return url;
59
+ // noMirror:本次请求**带凭据**(token)⇒ 一律直连——凭据绝不经过第三方镜像。
60
+ if (noMirror || mode === 'write' || String(method).toUpperCase() !== 'GET') return url;
61
+ for (const p of MIRRORABLE.concat(MIRRORABLE_API)) {
62
+ if (url.startsWith(p)) return base + url; // 形如 https://gh-proxy.com/https://github.com/...
63
+ }
64
+ return url;
65
+ }
66
+
67
+ /**
68
+ * 就地把 git 的 url.<mirror><github>.insteadOf 配置注入 env(git 透传/子进程用)。
69
+ * 不设镜像时不动 env。返回同一 env 便于链式调用。
70
+ *
71
+ * **写操作绝不注入**(`mode: 'write'`):insteadOf 是**全局 URL 重写**,一旦注入,
72
+ * 同一条 git 命令链里的 push 也会被改走镜像(实测:注入点在 wrapped-git.js 的两条执行路径上,
73
+ * 对 fetch/push 一视同仁),而镜像是否支持 receive-pack、是否会记录凭据都不可控 ⇒ 写操作直连。
74
+ *
75
+ * @param {object} env
76
+ * @param {{mode?:'read'|'write'}} [opts]
77
+ */
78
+ export function mirrorGitConfigEnv(env, { mode = 'read' } = {}) {
79
+ if (mode === 'write') return env;
80
+ const base = mirrorPrefix();
81
+ if (base) {
82
+ env.GIT_CONFIG_COUNT = '1';
83
+ env.GIT_CONFIG_KEY_0 = `url.${base}https://github.com/.insteadOf`;
84
+ env.GIT_CONFIG_VALUE_0 = 'https://github.com/';
85
+ }
86
+ return env;
87
+ }
88
+
89
+ /** API 基址(**不走镜像**,理由见文件头 ②)。 */
90
+ export const GH_API = 'https://api.github.com';
91
+ /** raw 基址(走镜像)。 */
92
+ export const GH_RAW = 'https://raw.githubusercontent.com';
93
+ /** web 基址(走镜像)。 */
94
+ export const GH_WEB = 'https://github.com';
95
+
96
+ /** blob API URL(逐 blob、可续;不走镜像)。 */
97
+ export function blobApiUrl(owner, repo, sha) {
98
+ return `${GH_API}/repos/${owner}/${repo}/git/blobs/${sha}`;
99
+ }
100
+
101
+ /** contents API URL(不走镜像)。 */
102
+ export function contentsApiUrl(owner, repo, encodedPath, encodedRef) {
103
+ return `${GH_API}/repos/${owner}/${repo}/contents/${encodedPath}?ref=${encodedRef}`;
104
+ }
105
+
106
+ /** raw 文件 URL(走镜像)。 */
107
+ export function rawFileUrl(owner, repo, encodedRef, encodedPath) {
108
+ return withMirror(`${GH_RAW}/${owner}/${repo}/${encodedRef}/${encodedPath}`);
109
+ }
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Git 执行层 · 进程调用
3
+ *
4
+ * 职责:统一的 git 子进程入口(runGit 走 execFileSync 取 stdout;gitRaw 取原始结果
5
+ * 含 exitCode/stderr,供 blob 上传等需要错误细节的场景)。
6
+ * 所有 git 调用都经过此模块,便于统一超时与错误规整,避免各调用点各写一份。
7
+ */
8
+
9
+ import { execFile, execFileSync, spawnSync } from 'node:child_process';
10
+ import { existsSync, statSync } from 'node:fs';
11
+ import { delimiter as pathDelimiter, join } from 'node:path';
12
+
13
+ /* ───────────────────────── git 可执行文件解析 ───────────────────────── */
14
+
15
+ /**
16
+ * 解析 git 可执行文件路径(不假设 PATH 里一定有 git)。
17
+ *
18
+ * 背景(2026-10-03 实测):群晖套件用户(服务用户)的 PATH 里没有 git,而本模块此前
19
+ * 直接 `execFileSync('git', ...)` —— 找不到可执行文件时抛 ENOENT,被 catch 规整成
20
+ * 空 stdout 的失败结果,commit 预检又把「空 stdout」当成「游离 HEAD」,
21
+ * 报出 "HEAD 处于 detached 状态" 这种完全误导的结论(真因是 PATH 缺 git)。
22
+ * 改为显式解析 + 明确的缺失提示,避免同类误诊。
23
+ * 优先级:DSH_GIT_BIN 环境变量 → PATH 各目录 → 常见绝对路径。
24
+ */
25
+ const GIT_CANDIDATES = [
26
+ // POSIX 常见位置
27
+ '/var/packages/git/target/bin/git', '/usr/local/bin/git', '/usr/bin/git', '/bin/git',
28
+ // Windows 常见安装位置(Git for Windows 的 cmd\ 目录;PATH 未配置时兜底)
29
+ 'C:\\Program Files\\Git\\cmd\\git.exe',
30
+ 'C:\\Program Files (x86)\\Git\\cmd\\git.exe',
31
+ ];
32
+
33
+ /**
34
+ * 组装「到哪找 git」的搜索计划(纯函数,便于跨平台单测)。
35
+ *
36
+ * 为什么单独成函数:Windows 的 PATH 用 `;` 分隔、可执行名是 `git.exe` ——
37
+ * 旧实现写死 `split(':')` + 候选名 `git`,在 Windows 上会把整串 PATH 当成一个目录,
38
+ * 于是永远找不到 git,报出「找不到 git 可执行文件」这种**看起来像环境问题**的误导结论
39
+ * (实际是解析方式不对)。
40
+ * @param {string} pathValue PATH 值
41
+ * @param {{delimiter?:string, platform?:string}} [opts] 可注入,便于单测
42
+ * @returns {{dirs:string[], names:string[]}}
43
+ */
44
+ export function gitSearchPlan(pathValue, { delimiter = pathDelimiter, platform = process.platform } = {}) {
45
+ const dirs = String(pathValue || '')
46
+ .split(delimiter)
47
+ .map((d) => d.trim().replace(/[\\/]+$/, ''))
48
+ .filter(Boolean);
49
+ const names = platform === 'win32' ? ['git.exe', 'git.cmd', 'git.bat', 'git'] : ['git'];
50
+ return { dirs, names };
51
+ }
52
+
53
+ let _gitBin;
54
+ export function resolveGitBin() {
55
+ if (_gitBin !== undefined) return _gitBin;
56
+ const envBin = process.env.DSH_GIT_BIN;
57
+ if (envBin) { _gitBin = envBin; return _gitBin; }
58
+ // PATH 分隔符与可执行名按平台取(Windows 是 ';' 与 git.exe)
59
+ const { dirs, names } = gitSearchPlan(process.env.PATH || '');
60
+ for (const dir of dirs) {
61
+ for (const name of names) {
62
+ const p = join(dir, name);
63
+ try { if (existsSync(p) && statSync(p).isFile()) { _gitBin = p; return _gitBin; } } catch { /* 继续找 */ }
64
+ }
65
+ }
66
+ for (const p of GIT_CANDIDATES) {
67
+ try { if (existsSync(p)) { _gitBin = p; return _gitBin; } } catch { /* 继续找 */ }
68
+ }
69
+ _gitBin = '';
70
+ return _gitBin;
71
+ }
72
+
73
+ /** 找不到 git 时的统一提示(调用方原样上抛,不再伪装成业务错误)。 */
74
+ export const GIT_MISSING_MSG = '找不到 git 可执行文件:请把 git 加入 PATH,或用 DSH_GIT_BIN 指定其绝对路径';
75
+
76
+ /* ───────────────────────── 基础:git 执行 ───────────────────────── */
77
+
78
+ /** git 全局配置参数(每次调用前置;safe.directory 防「不信任目录」误伤工作区,quotepath 保持路径可读)。
79
+ * ⚠ 必须 export:透传通道(wrapped-git.js)也要带上,否则同一条 git 命令
80
+ * 「插件内部调用成功、AI 透传调用却因 dubious ownership 失败」(2026-10-03 实测)。 */
81
+ import { mirrorGitConfigEnv } from './endpoints.js'; // ESM 允许 import 置于顶层任意位置,此处靠近使用点便于对照
82
+ /** 会走网络的**只读** git 动词:这些命令注入镜像 insteadOf;push 等写操作**绝不注入**(见 mirrorGitConfigEnv 的 mode)。 */
83
+ export const GIT_READ_VERBS = new Set(['fetch', 'clone', 'pull', 'ls-remote', 'submodule']);
84
+ export const GIT_GLOBAL_ARGS = ['-c', 'safe.directory=*', '-c', 'core.filemode=false', '-c', 'core.quotepath=false'];
85
+
86
+ /** 统一 git 执行(数组参数,零注入面;stderr 保留供排障)。 */
87
+ export function runGit(args, { cwd = '', timeoutMs = 120_000, env = {} } = {}) {
88
+ const base = GIT_GLOBAL_ARGS;
89
+ const bin = resolveGitBin();
90
+ if (!bin) return { ok: false, stdout: '', stderr: GIT_MISSING_MSG };
91
+ // 只读的网络动词注入镜像(与 http 层同口径:默认走 gh-proxy);
92
+ // 写操作(push 等)不在集合里 ⇒ 不注入 ⇒ 推送一律直连(凭据与写入不经第三方)。
93
+ const mirrorEnv = {};
94
+ if (GIT_READ_VERBS.has(String(args[0] || ''))) mirrorGitConfigEnv(mirrorEnv, { mode: 'read' });
95
+ try {
96
+ const out = execFileSync(bin, cwd ? base.concat(['-C', cwd], args) : base.concat(args), {
97
+ encoding: 'utf8',
98
+ timeout: timeoutMs,
99
+ maxBuffer: 16 * 1024 * 1024,
100
+ stdio: ['ignore', 'pipe', 'pipe'],
101
+ // 直通 git 包装器门禁:插件内部 git 调用合法(DSH_GIT_ENFORCE_PASS=1)
102
+ env: { ...process.env, ...mirrorEnv, DSH_GIT_ENFORCE_PASS: '1', ...env },
103
+ });
104
+ return { ok: true, stdout: out.trim(), stderr: '' };
105
+ } catch (e) {
106
+ return { ok: false, stdout: '', stderr: String(e?.stderr || e?.message || e).trim() };
107
+ }
108
+ }
109
+
110
+ /**
111
+ * git 原始字节通道(gitRaw 语义):stdout 保留 Buffer,供 blob 原始内容读取。
112
+ * ⚠️ 禁止用 runGit 读 blob——utf8 解码 + trim 会损坏非 UTF-8 字节/末尾换行(实测:
113
+ * pushViaApi 经 runGit 读 cat-file 上传,17/109 文件 blob sha 与本地不一致,远端内容损坏)。
114
+ * @returns {{status: number|null, stdout: Buffer, stderr: Buffer, error?: string}}
115
+ */
116
+ export function gitRaw(args, { cwd = '', timeoutMs = 600_000 } = {}) {
117
+ const base = GIT_GLOBAL_ARGS;
118
+ const bin = resolveGitBin();
119
+ if (!bin) return { status: null, stdout: Buffer.alloc(0), stderr: Buffer.alloc(0), error: GIT_MISSING_MSG };
120
+ try {
121
+ const r = spawnSync(bin, cwd ? base.concat(['-C', cwd], args) : base.concat(args), {
122
+ encoding: 'buffer',
123
+ maxBuffer: 128 * 1024 * 1024,
124
+ timeout: timeoutMs,
125
+ stdio: ['ignore', 'pipe', 'pipe'],
126
+ env: { ...process.env, DSH_GIT_ENFORCE_PASS: '1' },
127
+ });
128
+ return { status: r.status, stdout: r.stdout || Buffer.alloc(0), stderr: r.stderr || Buffer.alloc(0), ...(r.error ? { error: String(r.error.message || r.error) } : {}) };
129
+ } catch (e) {
130
+ return { status: null, stdout: Buffer.alloc(0), stderr: Buffer.alloc(0), error: String(e?.message || e) };
131
+ }
132
+ }
133
+
134
+ /**
135
+ * 异步版 runGit:与 runGit 参数/返回完全一致,但**不阻塞事件循环**。
136
+ *
137
+ * 新增,用于「列表逐仓并发探测远端」——runGit 走 execFileSync,是同步阻塞的,
138
+ * 在 Promise worker 里调用并不会真正并行(一个 worker 独占事件循环直到子进程结束),
139
+ * 实测 6 仓「并发」仍要 13s(≈ 串行)。改用本函数后各 worker 的子进程才能真正并行等待。
140
+ * 语义与 runGit 保持一致:stdout 同样 trim,失败返回 {ok:false, error} 而不抛。
141
+ */
142
+ export function runGitAsync(args, { cwd = '', timeoutMs = 120_000, env = {} } = {}) {
143
+ const base = GIT_GLOBAL_ARGS;
144
+ const bin = resolveGitBin();
145
+ if (!bin) return Promise.resolve({ ok: false, stdout: '', stderr: GIT_MISSING_MSG });
146
+ // 与 runGit 同口径:只读网络动词注入镜像,push 等写操作不注入(见 GIT_READ_VERBS)。
147
+ // 此前只有同步版注入,异步版仍直连 ⇒ 并发探测远端那类调用绕过镜像。
148
+ const mirrorEnv = {};
149
+ if (GIT_READ_VERBS.has(String(args[0] || ''))) mirrorGitConfigEnv(mirrorEnv, { mode: 'read' });
150
+ return new Promise((resolve) => {
151
+ execFile(bin, cwd ? base.concat(['-C', cwd], args) : base.concat(args), {
152
+ encoding: 'utf8',
153
+ timeout: timeoutMs,
154
+ maxBuffer: 16 * 1024 * 1024,
155
+ // 直通 git 包装器门禁:插件内部 git 调用合法(DSH_GIT_ENFORCE_PASS=1)
156
+ env: { ...process.env, ...mirrorEnv, DSH_GIT_ENFORCE_PASS: '1', ...env },
157
+ }, (err, stdout, stderr) => {
158
+ if (err) { resolve({ ok: false, stdout: '', stderr: String(stderr || err.message || err) }); return; }
159
+ resolve({ ok: true, stdout: String(stdout || '').trim(), stderr: String(stderr || '') });
160
+ });
161
+ });
162
+ }