dsh-git-push 0.0.0-stage → 2.8.6

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 (279) hide show
  1. package/.auditignore +30 -0
  2. package/.gitignore +39 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1486 -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 +266 -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 +192 -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 +672 -0
  32. package/lib/app/tools.js +34 -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 +215 -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 +137 -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 +148 -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 +476 -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 +171 -0
  190. package/lib/npm/registry.js +168 -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 +196 -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/cpu-sample.mjs +188 -0
  231. package/scripts/doc-drift.mjs +200 -0
  232. package/scripts/doc-func.mjs +212 -0
  233. package/scripts/doc-tree.mjs +456 -0
  234. package/scripts/doc-version.mjs +220 -0
  235. package/scripts/frontend-preview-check.mjs +124 -0
  236. package/scripts/hot-path-probe-cjs.cjs +71 -0
  237. package/scripts/hot-path-probe-fs-shim.mjs +28 -0
  238. package/scripts/hot-path-probe-fsp-shim.mjs +31 -0
  239. package/scripts/hot-path-probe.mjs +153 -0
  240. package/scripts/module-splitter.py +800 -0
  241. package/scripts/platform-scan.mjs +168 -0
  242. package/scripts/preview-gen.mjs +489 -0
  243. package/scripts/preview-local-runner.mjs +55 -0
  244. package/scripts/preview-server-direct.mjs +116 -0
  245. package/scripts/preview-server.mjs +305 -0
  246. package/scripts/preview-slot-data.mjs +123 -0
  247. package/scripts/probe-recheck.mjs +47 -0
  248. package/scripts/readme-gen.mjs +268 -0
  249. package/scripts/rename-locator.mjs +97 -0
  250. package/scripts/rule-switch.mjs +97 -0
  251. package/scripts/rules-solo-audit.mjs +173 -0
  252. package/scripts/scan-file-io.mjs +713 -0
  253. package/scripts/scan-hardcoded-paths.mjs +125 -0
  254. package/scripts/scan-repos.mjs +167 -0
  255. package/scripts/scan-version.mjs +122 -0
  256. package/scripts/scrub-user-wording.mjs +420 -0
  257. package/scripts/symbol-index.mjs +85 -0
  258. package/scripts/sync-plugin-install.mjs +223 -0
  259. package/scripts/sync-plugin.mjs +279 -0
  260. package/scripts/verify-prestep.mjs +100 -0
  261. package/skills/dev/audit-rule-authoring.md +58 -0
  262. package/skills/dev/dsh-git-push.md +323 -0
  263. package/skills/dev/git-push-live-fix.md +45 -0
  264. package/skills/dsh-repo-index.md +35 -0
  265. package/skills/guide/guide-audit.md +167 -0
  266. package/skills/guide/guide-cli-scripts.md +104 -0
  267. package/skills/guide/guide-clone-repos.md +173 -0
  268. package/skills/guide/guide-commit-push.md +156 -0
  269. package/skills/guide/guide-inject-ui.md +166 -0
  270. package/skills/guide/guide-slash-completion.md +118 -0
  271. package/skills/workflow/README.md +21 -0
  272. package/skills/workflow/git-commit-discipline.md +68 -0
  273. package/skills/workflow/git-project-startup.md +85 -0
  274. package/skills/workflow/git-rebuild-process.md +57 -0
  275. package/skills/workflow/github-operations.md +91 -0
  276. package/skills/workflow/readme-sync-git-md.md +28 -0
  277. package/skills/workflow/task-completion-report.md +73 -0
  278. package/skills/workflow/tool-json-add-ask.md +35 -0
  279. package/skills/workflow/versioning-rule.md +211 -0
@@ -0,0 +1,233 @@
1
+ /**
2
+ * Git 执行层 · 账号校验
3
+ *
4
+ * 职责:校验 GitHub token 在线可用性与 SSH 登录信息(在线 ssh -T),输出可读的账号状态块。
5
+ * token 与 SSH **分别**做有效性判断——token 在线校验 /user;SSH 用 id_rsa
6
+ * 直连 ssh.github.com:443 执行 ssh -T,解析返回的 "Hi <login>!" 拿登录名(SSH 也能取登录信息)。
7
+ * 凭据文件 account-status.json 由调用方(HTTP / 工具)负责写入/读取,本模块只做实时探测。
8
+ */
9
+
10
+ import { join } from 'node:path';
11
+ import { spawnSync } from 'node:child_process';
12
+ import { githubFetch } from './api.js';
13
+ import { maskToken, readSshPub, resolveToken, resolveSshKeys } from './credentials.js';
14
+
15
+ /* ───────── 账号校验常量 ───────── */
16
+ const SSH_HANDSHAKE_TIMEOUT_MS = 20_000; // ssh -T 在线握手超时
17
+ const GITHUB_USER_TIMEOUT_MS = 15_000; // GET /user 校验超时
18
+ const DETAIL_MAX_LEN = 120; // 失败详情截断长度
19
+ const SSH_AUTH_FAIL_TEXT = 'SSH 认证失败'; // ssh 校验失败统一文案
20
+
21
+ /**
22
+ * SSH 在线校验:用插件管理的首个私钥直连 ssh.github.com:443 执行 ssh -T。
23
+ * 返回 { valid, login?, detail }——登录名取 "Hi <login>!"(GitHub 对 git 用户返回该问候)。
24
+ * @param {object} [opts] { workspaceRoot }
25
+ */
26
+ export function testSshAuth({ workspaceRoot = '' } = {}) {
27
+ const keys = resolveSshKeys({ workspaceRoot });
28
+ if (!keys.length) return { valid: false, checked: false, login: '', detail: '未找到 SSH 私钥(id_rsa/id_ed25519/id_ecdsa)' };
29
+ for (const { keyPath } of keys) {
30
+ const known = join('/tmp', `dsh-git-push-known-hosts-${process.pid}`);
31
+ // git@ssh.github.com 只接受 git 用户;-T 禁止伪终端,GitHub 返回 "Hi <login>! You've successfully authenticated"
32
+ // 注:spawnSync args 直接作为 argv(不经 shell),keyPath 含空格无需引号——引号反而让 ssh 把
33
+ // 带引号的字符串当文件名;与 push.js 用 shell 字符串 GIT_SSH_COMMAND 不同。
34
+ const r = spawnSync('ssh', ['-i', keyPath, '-p', '443',
35
+ '-o', 'IdentitiesOnly=yes', '-o', 'StrictHostKeyChecking=accept-new',
36
+ '-o', `UserKnownHostsFile=${known}`, '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=10',
37
+ '-T', 'git@ssh.github.com'], { encoding: 'utf8', timeout: SSH_HANDSHAKE_TIMEOUT_MS });
38
+ const out = `${r.stdout || ''}${r.stderr || ''}`;
39
+ const match = out.match(/Hi\s+([A-Za-z0-9._-]+)!/);
40
+ if (match) return { valid: true, checked: true, login: match[1], detail: out.trim() };
41
+ // 权限拒绝 / 超时 / 网络失败 → 无效
42
+ if (!match) {
43
+ const detail = (out || (r.error?.message) || `exit ${r.status}`).trim().slice(0, DETAIL_MAX_LEN);
44
+ return { valid: false, checked: true, login: '', detail };
45
+ }
46
+ }
47
+ return { valid: false, checked: true, login: '', detail: SSH_AUTH_FAIL_TEXT };
48
+ }
49
+
50
+ /**
51
+ * 校验 GitHub 账号与凭据:token 与 SSH **分别**判定有效性。
52
+ * 网络出口:token → api.github.com(githubFetch 硬闸);SSH → ssh.github.com:443(-T 直连)。
53
+ * @param {object} [opts] { workspaceRoot, token, checkSsh }
54
+ * @returns {Promise<object>} { ok, loggedIn, cookieSet, warnLevel, cred, detail, username?, tokenStatus?, sshStatus?, ... }
55
+ */
56
+ export async function checkGithubAccount({ workspaceRoot = '', token = '', checkSsh = true } = {}) {
57
+ const tok = token || resolveToken({ workspaceRoot }).token;
58
+ const ssh = readSshPub({ workspaceRoot });
59
+ const cred = {
60
+ hasToken: !!tok,
61
+ tokenMasked: tok ? maskToken(tok) : '',
62
+ hasSshPub: ssh.configured,
63
+ sshFingerprint: ssh.fingerprint,
64
+ };
65
+
66
+ // token 有效性:在线 /user(成功时保存完整用户档案,供成功分支返回 仓库数/套餐/名字 等)
67
+ let tokenStatus = { valid: false, checked: false, detail: '' };
68
+ let userProfile = null; // token 有效的 /user 响应 { login, public_repos, plan, html_url, ... }
69
+ let apiQuota = null; // API 通道配额(2026-10-02 功能:UI 显示)——/user 响应头的 X-RateLimit-*
70
+ if (tok) {
71
+ const userResp = await githubFetch('/user', { token: tok, timeout: GITHUB_USER_TIMEOUT_MS });
72
+ const ok = Boolean(userResp.status === 200 && userResp.json?.login);
73
+ const raw = String(userResp.json?.message || userResp.error || '');
74
+ // 区分「凭据无效」与「本次没测成」——网络超时/断网时凭据本身可能完全正常,
75
+ // 不能一律报「已失效」(否则用户以为凭据坏了、按钮没用)。timeout 标志供上层文案分支。
76
+ const timedOut = /abort|timeout|timed out|ETIMEDOUT|ENOTFOUND|ECONNRESET|EAI_AGAIN/i.test(raw)
77
+ || Number(userResp.status) === 0;
78
+ tokenStatus = {
79
+ valid: ok,
80
+ checked: true,
81
+ login: ok ? userResp.json.login : '',
82
+ // 数字 id:提交身份要用它拼 GitHub noreply 邮箱
83
+ // (`<id>+<login>@users.noreply.github.com`,见 lib/git/identity.js)
84
+ id: ok ? String(userResp.json.id ?? '') : '',
85
+ timeout: !ok && timedOut,
86
+ detail: ok ? '' : (raw || `HTTP ${userResp.status}`),
87
+ };
88
+ if (ok) {
89
+ userProfile = userResp.json;
90
+ // API 通道配额:/user 响应头带 X-RateLimit-Limit/Remaining/Reset(core 通道)——
91
+ // 取得到才存(代理剥离响应头等场景留空,不阻塞主流程)。
92
+ if (userResp.rateLimit) {
93
+ const rl = userResp.rateLimit;
94
+ const resetAt = Number(rl.reset || 0) * 1000;
95
+ apiQuota = {
96
+ core: { limit: Number(rl.limit || 0), remaining: Number(rl.remaining ?? -1), resetAt: resetAt ? new Date(resetAt).toISOString() : '' },
97
+ checkedAt: new Date().toISOString(),
98
+ };
99
+ }
100
+ }
101
+ }
102
+
103
+ // SSH 有效性:在线 ssh -T(需真有私钥;无私钥仅 .pub 时跳过在线校验,仅记「已配置未验证」)
104
+ let sshStatus = { valid: false, checked: false, login: '', detail: '' };
105
+ if (ssh.configured && checkSsh) {
106
+ const s = testSshAuth({ workspaceRoot });
107
+ // testSshAuth 无私有 key 时返回 checked:false(仅 .pub 时不做在线探测)
108
+ sshStatus = { valid: s.valid, checked: !!s.checked, login: s.login || '', detail: s.detail || (s.valid ? '' : SSH_AUTH_FAIL_TEXT) };
109
+ }
110
+ // 兜底:SSH 不联网校验时,只看是否配置公钥
111
+ if (ssh.configured && !checkSsh) sshStatus = { valid: false, checked: false, login: '', detail: '(未做在线校验)' };
112
+
113
+ // 综合登录态:token 有效 或 SSH 有效,两者任一成立即视为已登录(username 取有效者)
114
+ const tokenValid = tokenStatus.valid;
115
+ const sshValid = sshStatus.valid;
116
+ const username = tokenValid && tokenStatus.login ? tokenStatus.login : (sshValid ? sshStatus.login : '');
117
+
118
+ if (!tok && !ssh.configured) {
119
+ return { ok: true, loggedIn: false, cookieSet: false, warnLevel: 'err', cred, detail: '未配置 Token / SSH 公钥', tokenStatus, sshStatus };
120
+ }
121
+ if (!tokenValid && !sshValid) {
122
+ const msgs = [];
123
+ if (tok) msgs.push(/Bad credentials|401/.test(tokenStatus.detail) ? 'Token 无效(Bad credentials)' : `Token 检测失败: ${tokenStatus.detail}`);
124
+ if (ssh.configured && sshStatus.checked && !sshValid) msgs.push(SSH_AUTH_FAIL_TEXT);
125
+ // 仅配置 SSH 公钥/私钥、无 token,且 SSH 未做在线验证(无法确认有效)→ 保持 warn
126
+ // (SSH 推送仍可能可用),而不是硬 err;有 token 时才按 token 判定 err。
127
+ if (!tok && ssh.configured && !sshStatus.checked) {
128
+ return {
129
+ ok: true, loggedIn: false, cookieSet: true, warnLevel: 'warn', cred,
130
+ detail: '已有 SSH 公钥,但无 Token,无法向 api.github.com 取用户信息(SSH 推送仍可能可用)',
131
+ tokenStatus, sshStatus,
132
+ };
133
+ }
134
+ return {
135
+ ok: true, loggedIn: false, cookieSet: true, warnLevel: 'err', cred,
136
+ detail: msgs.length ? msgs.join(';') : '凭据均无效',
137
+ tokenStatus, sshStatus,
138
+ };
139
+ }
140
+ return {
141
+ ok: true,
142
+ loggedIn: true,
143
+ cookieSet: true,
144
+ warnLevel: 'ok',
145
+ cred,
146
+ username,
147
+ // 补回 token 有效的 /user 档案字段(仓库数/套餐/名字/主页)——
148
+ // 此前成功分支只回 username,前端「公钥仓库数/套餐」恒显示 ?
149
+ userId: userProfile?.id,
150
+ name: userProfile?.name || '',
151
+ profileUrl: userProfile?.html_url || (userProfile ? `https://github.com/${userProfile.login}` : ''),
152
+ publicRepos: userProfile?.public_repos,
153
+ plan: userProfile?.plan?.name || userProfile?.plan || '',
154
+ apiQuota, // API 通道配额(core 通道 rate limit;无响应头时 null)
155
+ tokenStatus,
156
+ sshStatus,
157
+ };
158
+ }
159
+
160
+ /** 账号检查结果格式化为可读块(formatGithubAccountBlock)。 */
161
+ export function formatGithubAccountBlock(r = {}) {
162
+ const L = [];
163
+ const cred = r.cred || {};
164
+ const t = r.tokenStatus || {};
165
+ const s = r.sshStatus || {};
166
+ // 取消单一「已登录 GitHub:X」汇总行——Token 与 SSH 可以是**不同 GitHub 用户**
167
+ // 且各自有效,写唯一用户名会隐藏另一个账号。改为逐条列出各自用户名/掩码/时间与失效原因。
168
+ const fmtAt = (iso) => {
169
+ const tt = Date.parse(String(iso || ''));
170
+ if (!Number.isFinite(tt)) return '';
171
+ const date = new Date(tt); const p = (n) => String(n).padStart(2, '0');
172
+ return `${date.getFullYear()}-${p(date.getMonth() + 1)}-${p(date.getDate())} ${p(date.getHours())}:${p(date.getMinutes())}`;
173
+ };
174
+ const line = (label, present, item, masked) => {
175
+ if (!present) return `⏳ ${label}:未配置`;
176
+ const when = fmtAt(item.checkedAt);
177
+ const who = item.login || masked || '已配置';
178
+ if (item.valid) return `✅ ${label}:${who}${when ? `|校验于 ${when}` : ''}`;
179
+ if (item.timeout) return `⏳ ${label}:${who}|未测成(网络超时,可重试)`;
180
+ if (when) return `❌ ${label}:${who}|失效于 ${when}${item.detail ? `(${item.detail})` : ''}`;
181
+ return `⏳ ${label}:${who}|未校验`;
182
+ };
183
+ if (!r.cookieSet) {
184
+ L.push('❌ 未配置 Token / SSH 公钥(推送将走匿名失败)');
185
+ } else if (r.loggedIn) {
186
+ L.push('✅ 凭据可用');
187
+ if (cred.hasToken || cred.hasSshPub) L.push(`- 公钥仓库数:${r.publicRepos ?? '?'}|套餐:${r.plan || '?'}`);
188
+ L.push(`- ${line('Token', cred.hasToken, t, cred.tokenMasked)}`);
189
+ L.push(`- ${line('SSH 公钥', cred.hasSshPub, s, cred.sshFingerprint)}`);
190
+ } else {
191
+ L.push(`⚠️ 凭据不可用:${r.detail || '凭据缺失或未校验'}`);
192
+ L.push(`- ${line('Token', cred.hasToken, t, cred.tokenMasked)}`);
193
+ L.push(`- ${line('SSH 公钥', cred.hasSshPub, s, cred.sshFingerprint)}`);
194
+ }
195
+ return L.join('\n');
196
+ }
197
+ /** token 配额各通道归一(limit/remaining/重置时刻 ISO)。 */
198
+ function quotaChannel(resources, key) {
199
+ const r = resources && resources[key];
200
+ if (!r) return null;
201
+ return {
202
+ limit: Number(r.limit || 0),
203
+ remaining: Number(r.remaining || 0),
204
+ resetAt: r.reset ? new Date(Number(r.reset) * 1000).toISOString() : '',
205
+ };
206
+ }
207
+
208
+ /**
209
+ * 实时查询 token 的 GitHub API 配额(GET /rate_limit)。
210
+ *
211
+ * 为什么单独走 /rate_limit 而不是复用 /user 响应头:响应头只带 **core 一个通道**,
212
+ * 且只在「在线校验」那一刻才有值——而配额是用户随时想看的当前状态。专用端点
213
+ * 一次返回全部通道(core / search / graphql / code_search),且**不消耗任何配额**。
214
+ *
215
+ * @param {object} [opts] { workspaceRoot, token }
216
+ * @returns {Promise<{ok:boolean, core?, search?, graphql?, codeSearch?, fetchedAt?, error?}>}
217
+ */
218
+ export async function fetchApiQuota({ workspaceRoot = '', token = '' } = {}) {
219
+ const tok = token || resolveToken({ workspaceRoot }).token;
220
+ if (!tok) return { ok: false, error: '未配置 GitHub token(配额按 token 计)' };
221
+ const resp = await githubFetch('/rate_limit', { token: tok, timeout: GITHUB_USER_TIMEOUT_MS });
222
+ if (resp.status !== 200 || !resp.json?.resources) {
223
+ return { ok: false, error: String(resp.json?.message || resp.error || `HTTP ${resp.status}`) };
224
+ }
225
+ return {
226
+ ok: true,
227
+ core: quotaChannel(resp.json.resources, 'core'),
228
+ search: quotaChannel(resp.json.resources, 'search'),
229
+ graphql: quotaChannel(resp.json.resources, 'graphql'),
230
+ codeSearch: quotaChannel(resp.json.resources, 'code_search'),
231
+ fetchedAt: new Date().toISOString(),
232
+ };
233
+ }
package/lib/git/api.js ADDED
@@ -0,0 +1,136 @@
1
+ /**
2
+ * Git 执行层 · GitHub REST
3
+ *
4
+ * 职责:GitHub API 调用(githubFetch 统一带 token 与错误识别)、
5
+ * owner/repo 解析、坏凭据判定、仓库可见性探测。
6
+ */
7
+
8
+ import { runGit } from './exec.js';
9
+
10
+ /* ───────────────────────── 网络:api.github.com 唯一通道 ───────────────────────── */
11
+
12
+ // API 基址统一收口到 endpoints.js(含快通道口径说明);此处转出以保持既有引用不变。
13
+ // 注意:api.github.com **不走镜像**——API 通道是逐 blob、为断点续传设计的。
14
+ import { GH_API, withMirror, mirrorPrefix } from './endpoints.js';
15
+ export { GH_API };
16
+ const VIS_CHECK_TIMEOUT_MS = 30_000; // 仓库可见性探测超时
17
+
18
+ /**
19
+ * 调 api.github.com(唯一网络出口;非该域名直接拒绝,不跟随 302)。
20
+ * @returns {Promise<{status, json, text, error?}>}
21
+ */
22
+ export async function githubFetch(path, { token = '', method = 'GET', body, timeout = 60_000, headers: extraHeaders } = {}) {
23
+ const direct = /^https?:\/\//i.test(path) ? path : `${GH_API}${path.startsWith('/') ? path : `/${path}`}`;
24
+ // 只读请求可走镜像(前缀拼接,请求模型不变 ⇒ 逐 blob 可续性不受影响);
25
+ // 两道限制:写请求(method 非 GET)原样直连;**带 token 的请求**(私仓)也一律直连
26
+ // —— 凭据绝不经过第三方镜像。
27
+ const url = withMirror(direct, { method, noMirror: !!token });
28
+ // 离线开关(单测/无外网环境网络隔离)——设 DSH_GIT_PUSH_OFFLINE=1 时
29
+ // 所有 GitHub API 调用快速失败,测试不用真实网络(否则假 token 的 /user 会等满超时挂起)。
30
+ if (process.env.DSH_GIT_PUSH_OFFLINE === '1') {
31
+ return { status: 0, json: null, text: '', buffer: Buffer.alloc(0), error: 'offline (DSH_GIT_PUSH_OFFLINE=1)' };
32
+ }
33
+ let host = '';
34
+ try { host = new URL(url).hostname; } catch { return { status: 0, json: null, text: '', buffer: Buffer.alloc(0), error: `非法 URL: ${url}` }; }
35
+ // 白名单放行两种 host:直连的 api.github.com,以及「镜像前缀 + api.github.com」。
36
+ // 后者形如 https://gh-proxy.com/https://api.github.com/...,host 是镜像站——
37
+ // 若不同步放宽这里,开了镜像后所有 API 调用会被**自己**拒掉(改一处必须同改消费方)。
38
+ // 安全性由 withMirror 的双闸门保证:只有 GET 才会被改写成镜像 URL,
39
+ // 故能走到这里的非 api.github.com 请求必然是只读的。
40
+ const mp = mirrorPrefix();
41
+ const mirrorOk = !!mp && url.startsWith(`${mp}${GH_API}/`);
42
+ if (host !== 'api.github.com' && !mirrorOk) {
43
+ return { status: 0, json: null, text: '', buffer: Buffer.alloc(0), error: `拒绝非 api.github.com 请求: ${host}` };
44
+ }
45
+ const headers = {
46
+ Accept: 'application/vnd.github+json',
47
+ 'User-Agent': 'dsh-git-push',
48
+ ...(token ? { Authorization: `Bearer ${token}` } : {}),
49
+ ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),
50
+ ...(extraHeaders || {}),
51
+ };
52
+ // 单次尝试。注意:本模块用**返回值**表达 HTTP 错误(5xx 不会抛异常)⇒ 失败判据必须同时覆盖两类:
53
+ // 抛出(网络/DNS/超时)与「返回 status 0 或 >=500」。
54
+ const attempt = async (target) => {
55
+ const resp = await fetch(target, {
56
+ method, headers,
57
+ body: body !== undefined ? JSON.stringify(body) : undefined,
58
+ signal: AbortSignal.timeout(timeout),
59
+ redirect: 'manual', // 防 tarball 302 跳到 codeload.github.com
60
+ });
61
+ if (resp.status >= 300 && resp.status < 400) {
62
+ return { status: resp.status, json: null, text: '', buffer: Buffer.alloc(0), error: `api.github.com 重定向(拒绝跟随): ${resp.headers.get('location') || ''}` };
63
+ }
64
+ // 先读 arrayBuffer:JSON 接口 toString utf8;clone 二进制用 buffer / base64,避免 text() UTF-8 损坏
65
+ const buffer = Buffer.from(await resp.arrayBuffer());
66
+ const text = buffer.toString('utf8');
67
+ let json = null;
68
+ try { json = text ? JSON.parse(text) : null; } catch { /* 非 JSON(raw blob) */ }
69
+ // rate limit 头透传(2026-10-02 功能:UI 显示 API 通道配额)——GitHub 每次响应带
70
+ // X-RateLimit-Limit/Remaining/Reset(core 通道);取得到才返回,取不到不阻塞主流程。
71
+ const rateLimit = {};
72
+ for (const h of ['x-ratelimit-limit', 'x-ratelimit-remaining', 'x-ratelimit-reset']) {
73
+ const v = resp.headers.get(h);
74
+ if (v != null) rateLimit[h.replace('x-ratelimit-', '')] = v;
75
+ }
76
+ return { status: resp.status, json, text, buffer, rateLimit: Object.keys(rateLimit).length ? rateLimit : undefined };
77
+ };
78
+ const fail = (e) => ({ status: 0, json: null, text: '', buffer: Buffer.alloc(0), error: String(e?.message || e) });
79
+
80
+ const first = await attempt(url).catch(fail);
81
+ // 镜像回退(设计决策:默认走 gh-proxy,但**代理不可用时不能让整体失败**)⇒ 直连重试一次。
82
+ // 回退条件 = 本次真的走了镜像,且失败属于「**代理这一跳**的问题」:
83
+ // 网络/超时(status 0)、服务端故障(>=500)、以及**代理侧限流/拒绝**(403/429)。
84
+ // 后者是镜像站共享出口 IP 的常见答复(真实事故:经镜像的 API 请求拿到 403,而直连同时是 200),
85
+ // 并非仓库的真实答案;真实 403/404 会由直连再次给出,语义不会丢。
86
+ // 不回退:其余 4xx(404/401 等)——那是远端给出的真实答案,换直连只会白跑一次。
87
+ const mirrored = url !== direct;
88
+ const proxySideFailure = first.status === 0 || first.status >= 500 || first.status === 403 || first.status === 429;
89
+ if (!mirrored || !proxySideFailure) return first;
90
+ const second = await attempt(direct).catch(fail);
91
+ // 直连网络不可用(status 0)而镜像有明确 HTTP 码时,保留信息更丰富的那个(便于调用方看到真实状态)。
92
+ return second.status === 0 && first.status !== 0 ? first : second;
93
+ }
94
+
95
+ /** 从 origin / URL / owner-repo 解析 GitHub owner+repo(只解析字符串,不访问 github.com)。 */
96
+ export function parseGithubOwnerRepo(originUrl) {
97
+ const s = String(originUrl || '').trim();
98
+ if (!s) return null;
99
+ const patterns = [
100
+ /api\.github\.com\/repos\/([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?\s*$/i,
101
+ /(?:git@|https?:\/\/)(?:[^@/\s]+@)?(?:ssh\.)?github\.com(?::443)?[:/]([\w.-]+)\/([\w.-]+?)(?:\.git)?\s*$/i,
102
+ /^ssh:\/\/git@ssh\.github\.com:443\/([\w.-]+)\/([\w.-]+?)(?:\.git)?\s*$/i,
103
+ /^([\w.-]+)\/([\w.-]+?)$/,
104
+ ];
105
+ for (const re of patterns) {
106
+ const match = s.match(re);
107
+ if (match) return { owner: match[1], repo: match[2].replace(/\.git$/i, '') };
108
+ }
109
+ return null;
110
+ }
111
+
112
+ /** token 失效判定(401 / Bad credentials)。 */
113
+ export function isBadCredentials(reason = '') {
114
+ return /Bad credentials|credential|401\b/i.test(String(reason || ''));
115
+ }
116
+
117
+ /**
118
+ * 探测 GitHub 仓库可见性(GET /repos/{owner}/{repo},走 api.github.com 不跟随 302)。
119
+ * 用于私有库豁免:private 仓库敏感字段入库风险由可见性兜底,自动 .gitignore 只扫描不写。
120
+ * @returns {{visibility:'private'|'public'|'unknown', owner?, repo?, private?, reason?}}
121
+ */
122
+ export async function detectRepoVisibility({ repoPath = '', token = '' } = {}) {
123
+ try {
124
+ const originUrl = repoPath ? runGit(['remote', 'get-url', 'origin'], { cwd: repoPath }).stdout : '';
125
+ const pr = parseGithubOwnerRepo(originUrl);
126
+ if (!pr) return { visibility: 'unknown', reason: '无 github origin' };
127
+ const visRes = await githubFetch(`/repos/${pr.owner}/${pr.repo}`, { token, timeout: VIS_CHECK_TIMEOUT_MS });
128
+ if (visRes.status === 200) {
129
+ const json = visRes.json || {};
130
+ return { visibility: json.private ? 'private' : 'public', owner: pr.owner, repo: pr.repo, private: !!json.private };
131
+ }
132
+ return { visibility: 'unknown', reason: visRes.error || `GitHub API ${visRes.status}` };
133
+ } catch (e) {
134
+ return { visibility: 'unknown', reason: String(e?.message || e) };
135
+ }
136
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * 兼容壳(审计↔git 边界澄清第一期,2026-10-13):
3
+ * 实现已迁至 lib/core/atomic-json.js,本文件只做一行再导出,让既有消费方零改动。
4
+ * 新代码请直接 import '../core/atomic-json.js'。
5
+ */
6
+ export * from '../core/atomic-json.js';
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Git 执行层 · 目录浏览(账号卡片「手动指定路径」的路径选择器后端)
3
+ *
4
+ * 对接前端 PathPicker 弹窗:GET /api/git-push/browse?path=<dir> → { path, parent, dirs }。
5
+ * 结构对齐 gamebanana-mods-downloader/server/public/path-picker.js 的 /api/browse 契约。
6
+ */
7
+
8
+ import { existsSync, readdirSync, statSync } from 'node:fs';
9
+ import { dirname, isAbsolute, resolve } from 'node:path';
10
+
11
+ /**
12
+ * 浏览目录:列出直接子目录 + 上级目录。
13
+ * @param {string} [p] 目标路径(空 = 用 root)
14
+ * @param {object} [opts] { root } 默认根(空 p 且无 root 时用 process.cwd())
15
+ * @returns {{ok:boolean, path?, parent?, dirs?, error?}}
16
+ */
17
+ export function browseDir(p = '', { root = '' } = {}) {
18
+ const raw = String(p || '').trim();
19
+ let start;
20
+ if (!raw) {
21
+ start = root ? resolve(root) : resolve('.');
22
+ } else {
23
+ start = isAbsolute(raw) ? resolve(raw) : resolve(String(root || ''), raw);
24
+ }
25
+ if (!existsSync(start)) return { ok: false, error: `目录不存在: ${start}` };
26
+ let st;
27
+ try { st = statSync(start); } catch { return { ok: false, error: `无法读取: ${start}` }; }
28
+ if (!st.isDirectory()) return { ok: false, error: `不是目录: ${start}` };
29
+ let dirs = [];
30
+ try {
31
+ dirs = readdirSync(start, { withFileTypes: true })
32
+ .filter((e) => e.isDirectory())
33
+ .map((e) => e.name)
34
+ .sort((a, b) => a.localeCompare(b, 'zh-CN'));
35
+ } catch { /* 无权限等:返回空列表 */ }
36
+ const parent = start !== '/' ? dirname(start) : null;
37
+ return { ok: true, path: start, parent, dirs };
38
+ }