dsh-config-manager 0.2.3 → 0.3.0

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 (132) hide show
  1. package/README.md +1 -1
  2. package/README.zh-CN.md +1 -1
  3. package/lib/adapters/self.d.ts +44 -4
  4. package/lib/adapters/self.js +63 -3
  5. package/lib/client.d.ts +11 -6
  6. package/lib/client.js +1256 -1185
  7. package/lib/core/analyzer.d.ts +3 -0
  8. package/lib/core/analyzer.js +32 -56
  9. package/lib/core/backup.d.ts +36 -0
  10. package/lib/core/backup.js +125 -3
  11. package/lib/core/import-defaults.d.ts +13 -0
  12. package/lib/core/import-defaults.js +14 -0
  13. package/lib/core/importer.d.ts +10 -1
  14. package/lib/core/importer.js +7 -1
  15. package/lib/core/messages.d.ts +4 -0
  16. package/lib/core/messages.js +8 -0
  17. package/lib/core/model-tools.js +19 -3
  18. package/lib/index.d.ts +1 -1
  19. package/lib/index.js +12 -22
  20. package/lib/routes/import.js +3 -1
  21. package/lib/routes/recovery.js +226 -2
  22. package/lib/routes/sync.js +26 -7
  23. package/lib/security/integrity.d.ts +24 -0
  24. package/lib/security/integrity.js +30 -0
  25. package/lib/security/unverified-file-blocks.d.ts +73 -0
  26. package/lib/security/unverified-file-blocks.js +151 -0
  27. package/lib/sync/autosync-config.d.ts +8 -4
  28. package/lib/sync/autosync-config.js +2 -2
  29. package/lib/sync/autosync-scheduler.d.ts +61 -3
  30. package/lib/sync/autosync-scheduler.js +87 -10
  31. package/lib/sync/config-issue-reporting.d.ts +32 -0
  32. package/lib/sync/config-issue-reporting.js +63 -0
  33. package/lib/sync/gc-skip.d.ts +42 -0
  34. package/lib/sync/gc-skip.js +57 -0
  35. package/lib/sync/git/git-transport.d.ts +56 -2
  36. package/lib/sync/git/git-transport.js +344 -73
  37. package/lib/sync/merge-preview-text.d.ts +11 -0
  38. package/lib/sync/merge-preview-text.js +38 -0
  39. package/lib/sync/s3/s3-transport.d.ts +8 -1
  40. package/lib/sync/s3/s3-transport.js +19 -5
  41. package/lib/sync/session-tombstones.d.ts +53 -0
  42. package/lib/sync/session-tombstones.js +52 -0
  43. package/lib/sync/sync-config.d.ts +55 -5
  44. package/lib/sync/sync-config.js +188 -15
  45. package/lib/sync/sync-engine.d.ts +21 -7
  46. package/lib/sync/sync-engine.js +63 -85
  47. package/lib/sync/webdav/webdav-transport.d.ts +11 -1
  48. package/lib/sync/webdav/webdav-transport.js +22 -6
  49. package/lib/ui/i18n.js +56 -36
  50. package/lib/ui/import-wizard.d.ts +1 -1
  51. package/lib/ui/import-wizard.js +2 -1
  52. package/lib/ui/overview-view.d.ts +6 -2
  53. package/lib/ui/overview-view.js +8 -1
  54. package/lib/ui/report.js +2 -1
  55. package/lib/utils/git-fast-forward.d.ts +7 -2
  56. package/lib/utils/git-fast-forward.js +8 -3
  57. package/package.json +2 -2
  58. package/src/adapters/self.test.ts +126 -85
  59. package/src/adapters/self.ts +73 -6
  60. package/src/client/ConfigManagerSection.tsx +0 -3
  61. package/src/client/common/Icon.tsx +3 -0
  62. package/src/client/common/SectionComposition.tsx +6 -1
  63. package/src/client/common/info-hint-guard.test.ts +7 -5
  64. package/src/client/config-manager.module.css +254 -13
  65. package/src/client/environment/EnvironmentPanel.tsx +57 -47
  66. package/src/client/environment/maintenance/DiskUsageCard.tsx +3 -1
  67. package/src/client/export/ExportView.tsx +3 -1
  68. package/src/client/home/HomePanel.tsx +25 -5
  69. package/src/client/import/ImportWizardView.tsx +1 -3
  70. package/src/client/import/import-wizard-steps.tsx +1 -17
  71. package/src/client/library/ArtifactRow.tsx +13 -2
  72. package/src/client/library/LibraryPanel.tsx +12 -2
  73. package/src/client/locales.ts +53 -34
  74. package/src/client/lucide-icons.d.ts +2 -0
  75. package/src/client/market/MarketPanel.tsx +12 -11
  76. package/src/client/market/market-locales.ts +16 -16
  77. package/src/client/recovery/RollbackCard.tsx +4 -2
  78. package/src/client/recovery/recovery-locales.test.ts +4 -2
  79. package/src/client/recovery/recovery-locales.ts +23 -23
  80. package/src/client/sync/AutosyncCard.tsx +36 -10
  81. package/src/client/sync/SyncChannelEntryCard.tsx +18 -19
  82. package/src/client/sync/SyncPanel.tsx +32 -33
  83. package/src/client/sync/SyncProbeRow.tsx +23 -6
  84. package/src/client/sync/SyncSectionPickerDialog.tsx +2 -2
  85. package/src/client/sync/sync-locales.ts +24 -24
  86. package/src/core/analyzer.ts +37 -56
  87. package/src/core/backup.test.ts +139 -1
  88. package/src/core/backup.ts +145 -4
  89. package/src/core/import-defaults.ts +13 -0
  90. package/src/core/importer.ts +12 -2
  91. package/src/core/integrity-extra-entries.test.ts +205 -0
  92. package/src/core/messages.test.ts +3 -1
  93. package/src/core/messages.ts +8 -0
  94. package/src/core/model-tools.test.ts +33 -0
  95. package/src/core/model-tools.ts +20 -4
  96. package/src/index.ts +12 -21
  97. package/src/routes/import.ts +4 -1
  98. package/src/routes/recovery.test.ts +198 -1
  99. package/src/routes/recovery.ts +194 -1
  100. package/src/routes/sync.ts +27 -8
  101. package/src/security/integrity.ts +37 -0
  102. package/src/security/unverified-file-blocks.ts +192 -0
  103. package/src/sync/autosync-config.ts +9 -5
  104. package/src/sync/autosync-scheduler.test.ts +133 -6
  105. package/src/sync/autosync-scheduler.ts +118 -14
  106. package/src/sync/config-issue-reporting.test.ts +148 -0
  107. package/src/sync/config-issue-reporting.ts +75 -0
  108. package/src/sync/gc-skip.test.ts +66 -0
  109. package/src/sync/gc-skip.ts +64 -0
  110. package/src/sync/git/git-probe.test.ts +6 -1
  111. package/src/sync/git/git-transport.test.ts +351 -14
  112. package/src/sync/git/git-transport.ts +343 -79
  113. package/src/sync/merge-preview-text.ts +37 -0
  114. package/src/sync/s3/s3-delete-index-404.test.ts +26 -1
  115. package/src/sync/s3/s3-transport.ts +23 -4
  116. package/src/sync/session-tombstones.ts +90 -0
  117. package/src/sync/sync-config.test.ts +170 -1
  118. package/src/sync/sync-config.ts +184 -14
  119. package/src/sync/sync-engine.test.ts +238 -0
  120. package/src/sync/sync-engine.ts +79 -83
  121. package/src/sync/webdav/webdav-delete-index-404.test.ts +29 -1
  122. package/src/sync/webdav/webdav-transport.ts +26 -5
  123. package/src/ui/disk-usage-view.test.ts +2 -1
  124. package/src/ui/i18n.test.ts +47 -0
  125. package/src/ui/i18n.ts +58 -38
  126. package/src/ui/import-wizard.test.ts +18 -1
  127. package/src/ui/import-wizard.ts +3 -2
  128. package/src/ui/overview-view.test.ts +9 -0
  129. package/src/ui/overview-view.ts +9 -2
  130. package/src/ui/report.test.ts +4 -3
  131. package/src/ui/report.ts +2 -1
  132. package/src/utils/git-fast-forward.ts +8 -3
@@ -7,8 +7,9 @@
7
7
  * - 加密快照(EncryptedSections 密文载荷,无法平铺为明文 JSON 分区)走「密文单文件」布局:
8
8
  * 整个快照 JSON 提交到 <workDir>/snapshots-encrypted/<id>.json(远端已存密文;
9
9
  * 本地工作副本即远端镜像,不产生额外明文审计副本)。
10
- * - 命令执行走 node:child_process execFile(promise 封装,数组参数无 shell 注入),
11
- * 始终使用系统 PATH 中的 git(固定命令 'git'),可注入 exec 便于测试。
10
+ * - 命令执行走 node:child_process spawn(数组参数无 shell 注入、无 maxBuffer 截断错误),
11
+ * 超时**整棵进程树**一起 kill(issue #122:只 SIGTERM git.exe 会留下 git-remote-https /
12
+ * index-pack 孤儿继续下载);始终使用系统 PATH 中的 git(固定命令 'git'),可注入 exec 便于测试。
12
13
  * - 认证:token 仅从注入的 credentials provider 读取(每次网络操作时 getToken()),
13
14
  * 经 git credential helper(store --file=<临时文件>)传给 git —— token 不进入 argv、
14
15
  * 不进入 repoUrl、不写入任何同步内容/commit message/日志;临时凭据文件用后即删。
@@ -17,15 +18,15 @@
17
18
  * - 契约:同 id 重复 upload = 覆盖(幂等友好:内容无变化时不产生 commit);download 不存在抛错;
18
19
  * delete 不存在视为成功。
19
20
  */
20
- import { execFile } from 'node:child_process';
21
+ import { spawn } from 'node:child_process';
21
22
  import fs from 'node:fs/promises';
22
23
  import os from 'node:os';
23
24
  import path from 'node:path';
24
- import { promisify } from 'node:util';
25
25
  import { createSnapshotFs, joinFs } from '../fs.js';
26
26
  import { readSnapshotFromDir, SNAPSHOT_BLOB_REFS_SUFFIX, SNAPSHOT_KEEP_CONTENT, SNAPSHOT_KEEP_FILE, SNAPSHOT_MANIFEST_FILE, writeSnapshotToDir } from '../layout.js';
27
27
  import { BLOB_SECTIONS, gcBlobs, referencedBlobHashes } from '../blob-store.js';
28
28
  import { deserializeSnapshot, serializeSnapshot } from '../snapshot-json.js';
29
+ import { classifyRepoUrl, isPrivateRepoHost } from '../sync-config.js';
29
30
  import { classifyNetworkErrorText, computeSnapshotMeta, DEFAULT_SYNC_TIMEOUT_MS, isEncryptedSections, SyncTransportError, withSyncRetry, } from '../transport.js';
30
31
  import { parseJsonSafe } from '../../utils/json.js';
31
32
  import { atomicWriteFile } from '../../utils/atomic-write.js';
@@ -35,7 +36,6 @@ import { SECTION_FILE_PREFIXES } from '../../schema/config.js';
35
36
  import { zhMsg } from '../../core/messages.js';
36
37
  import { withWorkdirLock, WorkdirLockError } from '../../utils/workdir-lock.js';
37
38
  import { fastForwardFetchArgs, fastForwardMergeArgs, isMissingRemoteRefError, parseCurrentBranch } from '../../utils/git-fast-forward.js';
38
- const execFileAsync = promisify(execFile);
39
39
  /**
40
40
  * 工作副本自检结果的短 TTL 缓存(`inspectWorkDir`,2026-10-27)。
41
41
  *
@@ -97,10 +97,42 @@ const BLOBS_REL = 'blobs';
97
97
  * 远端分支的顶层出现别的名字 = 这不是本插件的同步仓库,合并它等于把别人的仓库内容搬进工作副本。
98
98
  */
99
99
  const ADOPT_ROOT_ALLOW = new Set([SNAPSHOTS_REL, SNAPSHOTS_ENCRYPTED_REL, BLOBS_REL]);
100
+ /**
101
+ * 同步仓库只在这三个顶层目录里写内容 ⇒ partial clone 的 sparse-checkout 面与它同源(issue #122)。
102
+ * 远端仓库比同步内容大几个数量级时(报告者现场:1.8 GB 仓库 / 6 MB 内容),全量 clone 与全量 fetch
103
+ * 都要拉完整对象图,而工作副本真正需要的只有这三个目录。
104
+ */
105
+ const SYNC_ROOT_DIRS = [...ADOPT_ROOT_ALLOW];
106
+ /**
107
+ * 走网络的 git 子命令:一律附加低速上限(issue #122)。
108
+ *
109
+ * 为什么必须显式设:git 的默认 http 低速门限极宽松,链路被限速/黑洞时一条 fetch 能安静地耗到
110
+ * timeoutMs(120 s),再乘上重试次数 = 用户看到的就是「永久停在正在检查远端变更」。
111
+ * 30 s 内平均速率低于 1 KB/s 即明确失败,交给既有分类器判 timeout(瞬时、可重试)。
112
+ */
113
+ const NETWORK_SUBCOMMANDS = new Set(['clone', 'fetch', 'push', 'ls-remote', 'pull']);
114
+ const LOW_SPEED_ARGS = ['-c', 'http.lowSpeedLimit=1000', '-c', 'http.lowSpeedTime=30'];
115
+ /**
116
+ * 协议护栏(SEC-12):**所有** git 子进程恒带,与「这条命令走不走网络」无关。
117
+ *
118
+ * 为什么恒带而不是只给网络命令:危险的不只是远端协议本身 —— `ext::sh -c ...` / `file://`
119
+ * 这类地址在 clone/fetch 之外还能经 `remote set-url`、配置重载等路径被触发,而本插件的 repoUrl
120
+ * 来自用户可编辑的 sync-config.json 与可导入的配置包。把 `ext` 与 `file` 传输整体关掉,
121
+ * 就等于「repoUrl 无论被改成什么,都只能走 http/https/ssh 三种真协议」。
122
+ */
123
+ const PROTOCOL_GUARD_ARGS = ['-c', 'protocol.ext.allow=never'];
124
+ /** 网络仓库额外禁 file 传输(本地目录仓库是显式支持的用法,不能一刀切禁掉)。 */
125
+ const FILE_PROTOCOL_GUARD_ARGS = ['-c', 'protocol.file.allow=never'];
126
+ /** 报错/日志里回显的地址占位符:不带真实 repoUrl(脱敏由上层的 mask() 负责)。 */
127
+ const REPO_URL_PLACEHOLDER = '[REPO_URL]';
100
128
  const DEFAULT_AUTHOR = { name: 'DSH Config Sync', email: 'sync@dsh.local' };
101
129
  const DEFAULT_CREDENTIAL_USERNAME = 'oauth2';
102
130
  /** 快照 id 安全字符集:字母数字开头,仅 . _ -;防路径穿越与 commit message 注入 */
103
131
  const SAFE_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
132
+ /** git 对象 id(sha1 40 位 / sha256 64 位)—— ls-remote 输出与 rev-parse 结果共用同一判定 */
133
+ const SHA_RE = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/;
134
+ /** 老 git 不认新选项(partial clone 需 ≥2.19、cone sparse-checkout 需 ≥2.25):据此回落全量 clone */
135
+ const UNSUPPORTED_GIT_OPTION_RE = /unknown option|unrecognized argument|unknown switch|is not a git command|unsupported/i;
104
136
  /**
105
137
  * SSH 主机密钥校验失败(issue #79):git 只回一句 `Host key verification failed`,
106
138
  * 用户拿不到任何可操作信息(要不要信任?怎么写 known_hosts?)。识别后换成可操作文案。
@@ -112,41 +144,132 @@ const SSH_HOST_KEY_RE = /host key verification failed|remote host identification
112
144
  * 这类失败与网络无关,必须给「改回地址或重建工作副本」的出口,而不是只丢一句原始 stderr。
113
145
  */
114
146
  const DIVERGED_HISTORY_RE = /refusing to merge unrelated histories|unrelated histories|not possible to fast-forward/i;
115
- const defaultExec = async (cmd, args, opts) => {
147
+ /** 超时 kill 之后等 stdio 关闭的宽限:逃出进程组的孙进程可能一直握着管道(issue #122) */
148
+ const EXEC_KILL_GRACE_MS = 5_000;
149
+ /** 单条命令累计输出上限(与旧 execFile maxBuffer 同口径,超限即 kill) */
150
+ const EXEC_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
151
+ /**
152
+ * 默认 git 执行器:spawn + **进程树** kill(issue #122)。
153
+ *
154
+ * 为什么不再用 execFile:它的 timeout 只对 git.exe 自己发 SIGTERM,而真正在下包的是 git.exe 的子进程
155
+ * (git-remote-https / git index-pack)。父进程被杀、孙进程继续写 tmp_pack_*,管道不关闭 ⇒ execFile 的
156
+ * promise 连超时错误都可能不返回 ⇒ 上层「正在检查远端变更...」永久挂起,下一轮重试再起一份,最终 N 份
157
+ * 并发下载同一个 pack。
158
+ * 这里改为:POSIX 上 detached 起独立进程组,超时对**整组**发 SIGKILL;Windows 上 `taskkill /T /F`;
159
+ * 无论 kill 是否成功,宽限期到点都带着已收集输出收尾 —— 绝不把「管道没关」变成上层无限等待。
160
+ *
161
+ * 导出仅供测试直接验证「超时 + 进程树 kill + 有界收尾」(issue #122 的验收面)。
162
+ */
163
+ export const defaultGitExec = async (cmd, args, opts) => await new Promise((resolve) => {
164
+ const isWin = process.platform === 'win32';
165
+ // issue #120:credential helper 走 shell 且本机没有可用 shell 时,改用 env 注入认证头重试 ——
166
+ // 追加在继承的 process.env 上(env 缺省 = 完全继承,不改变既有行为)
167
+ const env = opts.env === undefined ? undefined : { ...process.env, ...opts.env };
168
+ let stdout = '';
169
+ let stderr = '';
170
+ let bytes = 0;
171
+ let settled = false;
172
+ let timedOut = false;
173
+ let overflow = false;
174
+ let timer = null;
175
+ let graceTimer = null;
176
+ let child = null;
177
+ const settle = (code) => {
178
+ if (settled)
179
+ return;
180
+ settled = true;
181
+ if (timer !== null)
182
+ clearTimeout(timer);
183
+ if (graceTimer !== null)
184
+ clearTimeout(graceTimer);
185
+ let text = stderr;
186
+ if (code !== 0) {
187
+ if (overflow && !/exceed/i.test(text))
188
+ text = `${text}\noutput exceeded ${String(EXEC_MAX_OUTPUT_BYTES)} bytes`;
189
+ if (text.trim() === '')
190
+ text = `git ${args[0] ?? ''} exited with code ${String(code)}`;
191
+ // 超时在 git 的 stderr 里常常是空的:补一句可判定的文字,让 transport.ts 的统一分类器
192
+ // 把它识别成 timeout(瞬时、可重试),而不是 unknown。
193
+ if (timedOut && !/timed out|timeout/i.test(text)) {
194
+ text = `git command timed out after ${String(opts.timeoutMs ?? 0)}ms: ${text}`;
195
+ }
196
+ }
197
+ resolve({ stdout, stderr: text, code });
198
+ };
199
+ const killTree = () => {
200
+ const pid = child?.pid;
201
+ if (pid === undefined)
202
+ return;
203
+ if (isWin) {
204
+ // 只 SIGTERM git.exe 会留下 git-remote-https / index-pack 孤儿(issue #122)⇒ 整棵树强杀
205
+ try {
206
+ spawn('taskkill', ['/pid', String(pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' })
207
+ .on('error', () => { });
208
+ }
209
+ catch { /* 同上 */ }
210
+ return;
211
+ }
212
+ try {
213
+ process.kill(-pid, 'SIGKILL'); // 负 pid = 整个进程组(detached 起的子进程是组长)
214
+ }
215
+ catch {
216
+ try {
217
+ child?.kill('SIGKILL');
218
+ }
219
+ catch { /* 已退出 */ }
220
+ }
221
+ };
116
222
  try {
117
- const { stdout, stderr } = await execFileAsync(cmd, args, {
118
- cwd: opts.cwd,
119
- timeout: opts.timeoutMs,
120
- maxBuffer: 16 * 1024 * 1024,
223
+ child = spawn(cmd, args, {
224
+ ...(opts.cwd === undefined ? {} : { cwd: opts.cwd }),
225
+ ...(env === undefined ? {} : { env }),
121
226
  windowsHide: true,
122
- encoding: 'utf8',
123
- // issue #120:credential helper 走 shell 且本机没有可用 shell 时,改用 env 注入认证头重试 ——
124
- // 追加在继承的 process.env 上(env 缺省 = 完全继承,不改变既有行为)
125
- env: opts.env === undefined ? undefined : { ...process.env, ...opts.env },
227
+ // POSIX:独立进程组,超时才可能连孙进程一起杀;Windows 用 taskkill /T
228
+ detached: !isWin,
229
+ stdio: ['ignore', 'pipe', 'pipe'],
126
230
  });
127
- return { stdout: String(stdout), stderr: String(stderr), code: 0 };
128
231
  }
129
232
  catch (err) {
130
- const e = err;
131
- const detail = String(e.stderr ?? '') !== '' ? String(e.stderr) : (err instanceof Error ? err.message : String(err));
132
- // 超时(execFile 到点 kill)在 git 的 stderr 里常常是空的:补一句可判定的文字,
133
- // 让 transport.ts 的统一分类器把它识别成 timeout(瞬时、可重试),而不是 unknown。
134
- const timedOut = e.killed === true || e.signal === 'SIGTERM' || e.code === 'ETIMEDOUT';
135
- const stderr = timedOut && !/timed out|timeout/i.test(detail)
136
- ? `git command timed out after ${String(opts.timeoutMs ?? 0)}ms: ${detail}`
137
- : detail;
138
- return {
139
- stdout: String(e.stdout ?? ''),
140
- stderr,
141
- code: typeof e.code === 'number' ? e.code : 1,
142
- };
233
+ resolve({ stdout: '', stderr: err instanceof Error ? err.message : String(err), code: 1 });
234
+ return;
143
235
  }
144
- };
236
+ const collect = (sink) => (chunk) => {
237
+ bytes += chunk.length;
238
+ if (bytes > EXEC_MAX_OUTPUT_BYTES) {
239
+ if (!overflow) {
240
+ overflow = true;
241
+ killTree();
242
+ }
243
+ return;
244
+ }
245
+ if (sink === 'out')
246
+ stdout += chunk.toString('utf8');
247
+ else
248
+ stderr += chunk.toString('utf8');
249
+ };
250
+ child.stdout?.on('data', collect('out'));
251
+ child.stderr?.on('data', collect('err'));
252
+ child.on('error', (err) => {
253
+ stderr = stderr === '' ? err.message : stderr;
254
+ settle(1);
255
+ });
256
+ child.on('close', (code) => { settle(typeof code === 'number' ? code : 1); });
257
+ if (opts.timeoutMs !== undefined) {
258
+ timer = setTimeout(() => {
259
+ timedOut = true;
260
+ killTree();
261
+ // 进程树 kill 之后管道仍可能被握着(逃出进程组的孙进程)⇒ 宽限期到点强制收尾
262
+ graceTimer = setTimeout(() => { settle(1); }, EXEC_KILL_GRACE_MS);
263
+ }, Math.max(1, opts.timeoutMs));
264
+ }
265
+ });
145
266
  /** 实现 SyncTransport 的 git 通道。所有操作前 ensureRepo() 保证工作副本就绪,网络命令带凭据。 */
146
267
  export class GitTransport {
147
268
  type = 'git';
148
269
  o;
149
270
  repoReady = false;
271
+ /** 该工作副本是否 partial clone(remote.origin.promisor);null = 尚未判定(issue #122) */
272
+ partialClone = null;
150
273
  /**
151
274
  * 工作副本锁的可重入深度:list/upload/download/delete 都会经 ensureRepo → reconcileOrigin,
152
275
  * rebuildWorkDir → adoptRemoteHistory 也各自嵌套;外层入口持锁,内层直接跑。
@@ -161,6 +284,8 @@ export class GitTransport {
161
284
  */
162
285
  readErrors = [];
163
286
  msg;
287
+ /** repoUrl 是否为网络地址(本地目录仓库 == false):决定要不要额外禁 file 传输(SEC-12)。 */
288
+ networkRepo;
164
289
  constructor(options) {
165
290
  if (typeof options.repoUrl !== 'string' || options.repoUrl.length === 0) {
166
291
  throw new GitTransportError(zhMsg('sync.git.repoUrlRequired'));
@@ -173,6 +298,16 @@ export class GitTransport {
173
298
  throw new GitTransportError(zhMsg('sync.git.credentialsRequired'));
174
299
  }
175
300
  this.msg = options.msg ?? zhMsg;
301
+ // SEC-12:repoUrl 来自用户可编辑配置与可导入配置包 —— 构造期就收成「只能是真网络地址或本地目录」,
302
+ // 环回/私网/链路本地一律拒(把家目录配置推到 localhost 上的抓取器是最省事的外泄方式)。
303
+ // **已知行为变更**:局域网 NAS / 内网 git 服务器作为同步目标此后会被拒绝(见 sync-config.ts
304
+ // 的 isPrivateRepoHost 注释里的取舍说明),这是有意的安全收紧,不是回归。
305
+ // 地址本体不回显进错误(占位符代替),脱敏仍由 mask() 兜底。
306
+ const repoShape = classifyRepoUrl(options.repoUrl);
307
+ if (repoShape === null || (repoShape.kind !== 'local' && isPrivateRepoHost(repoShape.host))) {
308
+ throw new GitTransportError(this.msg('sync.git.repoUrlInvalid', { url: REPO_URL_PLACEHOLDER }));
309
+ }
310
+ this.networkRepo = repoShape.kind !== 'local';
176
311
  this.o = {
177
312
  repoUrl: options.repoUrl,
178
313
  workDir: options.workDir,
@@ -180,7 +315,7 @@ export class GitTransport {
180
315
  gitBin: 'git',
181
316
  timeoutMs: options.timeoutMs ?? DEFAULT_SYNC_TIMEOUT_MS,
182
317
  retry: options.retry ?? {},
183
- exec: options.exec ?? defaultExec,
318
+ exec: options.exec ?? defaultGitExec,
184
319
  author: options.author ?? DEFAULT_AUTHOR,
185
320
  credentialUsername: options.credentialUsername ?? DEFAULT_CREDENTIAL_USERNAME,
186
321
  };
@@ -385,12 +520,12 @@ export class GitTransport {
385
520
  async checkIsPrivate() {
386
521
  if (this.privateHint !== null)
387
522
  return this.privateHint;
388
- const anon = await this.runGit(['ls-remote', this.o.repoUrl], { allowNonZero: true, cwd: undefined });
523
+ const anon = await this.runGit(['ls-remote', '--', this.o.repoUrl], { allowNonZero: true, cwd: undefined });
389
524
  if (anon.code === 0) {
390
525
  this.privateHint = false;
391
526
  return false;
392
527
  }
393
- const authed = await this.runGit(['ls-remote', this.o.repoUrl], { allowNonZero: true, cwd: undefined, withCredential: true });
528
+ const authed = await this.runGit(['ls-remote', '--', this.o.repoUrl], { allowNonZero: true, cwd: undefined, withCredential: true });
394
529
  if (authed.code === 0) {
395
530
  this.privateHint = true;
396
531
  return true;
@@ -489,13 +624,93 @@ export class GitTransport {
489
624
  await withSyncRetry(async () => {
490
625
  if (await fsx.exists(gitDir))
491
626
  return;
492
- await this.runGit(['clone', this.o.repoUrl, '.'], { cwd: this.o.workDir, withCredential: true });
627
+ await this.cloneIntoWorkDir();
493
628
  }, this.o.retry);
494
629
  // 仓库级提交身份(写入远端历史,可经 author 选项覆盖;不改全局配置)
495
630
  await this.runGit(['config', 'user.name', this.o.author.name]);
496
631
  await this.runGit(['config', 'user.email', this.o.author.email]);
497
632
  this.repoReady = true;
498
633
  }
634
+ /**
635
+ * 首次 clone(issue #122):partial clone + sparse-checkout,只落地同步内容。
636
+ *
637
+ * 为什么:同步仓库可能比同步内容大几个数量级(报告者现场 1.8 GB 仓库 / 6 MB 内容)。此前 `git clone`
638
+ * 全量落地,之后每次 fetch 还要拉完整对象图 ⇒ 一次「检查远端变更」就下几百 MB。
639
+ * `--filter=blob:none` 只取 commit+tree,`--no-checkout` 先不落地任何文件,
640
+ * `sparse-checkout set --cone <三个目录>` 之后 checkout 只 materialize 这三个目录的 blob。
641
+ *
642
+ * 老 git 不认这些选项(unknown option)时回落全量 clone —— 行为与修复前完全一致,绝不因优化失败。
643
+ */
644
+ async cloneIntoWorkDir() {
645
+ const cwd = this.o.workDir;
646
+ this.partialClone = null; // reclone 后重新判定(配置可能变)
647
+ const filteredArgs = ['clone', '--filter=blob:none', '--no-checkout', '--', this.o.repoUrl, '.'];
648
+ const filtered = await this.runGit(filteredArgs, { cwd, withCredential: true, allowNonZero: true });
649
+ if (filtered.code !== 0) {
650
+ if (!UNSUPPORTED_GIT_OPTION_RE.test(filtered.stderr + ' ' + filtered.stdout)) {
651
+ // 真实失败(网络 / 鉴权 / 超时):沿用既有分类与文案(含 issue #120 的凭据通道判定)
652
+ this.raiseGitFailure(filteredArgs, filtered, await this.readTokenOnce(), false);
653
+ }
654
+ // 老 git:回落全量 clone(全量 clone 自带 checkout)
655
+ await clearDirContents(cwd);
656
+ await this.runGit(['clone', '--', this.o.repoUrl, '.'], { cwd, withCredential: true });
657
+ return;
658
+ }
659
+ const branch = await this.currentBranch();
660
+ const head = await this.runGit(['rev-parse', '--verify', '--quiet', 'HEAD'], { allowNonZero: true });
661
+ if (head.code !== 0)
662
+ return; // 空仓库:没有可 checkout 的树,后续 push 会建分支
663
+ const target = branch === '' ? 'HEAD' : branch;
664
+ const sparse = await this.runGit(['sparse-checkout', 'set', '--cone', ...SYNC_ROOT_DIRS], { allowNonZero: true });
665
+ if (sparse.code !== 0) {
666
+ // 老 git 没有 cone 模式:宁可全量落地(修复前行为),也不留下一个空工作树
667
+ await this.runGit(['checkout', target], { allowNonZero: true });
668
+ return;
669
+ }
670
+ // checkout 失败必须可见(空工作树会让上层以为「远端没有快照」)
671
+ await this.runGit(['checkout', target]);
672
+ }
673
+ /**
674
+ * 该工作副本是不是 partial clone(`remote.origin.promisor=true`)。
675
+ *
676
+ * 只有 partial clone 才能给 fetch 加 `--filter=blob:none`:对普通全量副本加过滤会让后续 checkout
677
+ * 拿到缺失的 blob。存量副本(1.8 GB 那种)因此只受益于 ls-remote 短路与 `--no-tags`,不会被改坏。
678
+ */
679
+ async isPartialClone() {
680
+ if (this.partialClone !== null)
681
+ return this.partialClone;
682
+ const res = await this.runGit(['config', '--get', 'remote.origin.promisor'], { allowNonZero: true });
683
+ this.partialClone = res.code === 0 && res.stdout.trim() === 'true';
684
+ return this.partialClone;
685
+ }
686
+ /** 拉取姿态:partial clone 保持 blob 过滤;同步仓库不需要 tag(issue #122) */
687
+ async fetchOptionFlags() {
688
+ const flags = [];
689
+ if (await this.isPartialClone())
690
+ flags.push('--filter=blob:none');
691
+ flags.push('--no-tags');
692
+ return flags;
693
+ }
694
+ /** 远端分支当前的 sha(ls-remote 只取一行 refs);读不到 → null(短路是优化,失败一律回落正常 fetch) */
695
+ async lsRemoteBranchSha(branch) {
696
+ const res = await this.runGit(['ls-remote', '--heads', 'origin', `refs/heads/${branch}`], { withCredential: true, allowNonZero: true });
697
+ if (res.code !== 0)
698
+ return null;
699
+ for (const line of res.stdout.split('\n')) {
700
+ const [sha, ref] = line.trim().split('\t');
701
+ if (ref === `refs/heads/${branch}` && sha !== undefined && SHA_RE.test(sha))
702
+ return sha;
703
+ }
704
+ return null;
705
+ }
706
+ /** 解析引用指向的 sha;读不到 / 不是 sha → null */
707
+ async revParseSha(ref) {
708
+ const res = await this.runGit(['rev-parse', '--verify', '--quiet', ref], { allowNonZero: true });
709
+ if (res.code !== 0)
710
+ return null;
711
+ const sha = res.stdout.trim();
712
+ return SHA_RE.test(sha) ? sha : null;
713
+ }
499
714
  /**
500
715
  * 让工作副本的 origin 与配置的 repoUrl 保持一致(issue #79)。
501
716
  *
@@ -508,15 +723,16 @@ export class GitTransport {
508
723
  const current = await this.runGit(['remote', 'get-url', 'origin'], { allowNonZero: true });
509
724
  const origin = current.code === 0 ? current.stdout.trim() : '';
510
725
  if (current.code !== 0) {
511
- await this.runGit(['remote', 'add', 'origin', this.o.repoUrl]);
726
+ await this.runGit(['remote', 'add', 'origin', '--', this.o.repoUrl]);
512
727
  }
513
728
  else if (origin !== '' && origin !== this.o.repoUrl) {
514
- await this.runGit(['remote', 'set-url', 'origin', this.o.repoUrl]);
729
+ await this.runGit(['remote', 'set-url', 'origin', '--', this.o.repoUrl]);
730
+ this.partialClone = null; // 换了远端 ⇒ promisor 判定失效(issue #122)
515
731
  }
516
732
  const push = await this.runGit(['remote', 'get-url', '--push', 'origin'], { allowNonZero: true });
517
733
  const pushUrl = push.code === 0 ? push.stdout.trim() : '';
518
734
  if (pushUrl !== '' && pushUrl !== this.o.repoUrl) {
519
- await this.runGit(['remote', 'set-url', '--push', 'origin', this.o.repoUrl]);
735
+ await this.runGit(['remote', 'set-url', '--push', 'origin', '--', this.o.repoUrl]);
520
736
  }
521
737
  }
522
738
  /**
@@ -615,8 +831,9 @@ export class GitTransport {
615
831
  return {
616
832
  path: this.o.workDir,
617
833
  exists: true,
618
- origin: origin === '' ? null : origin,
619
- pushUrl: pushRaw === '' ? null : pushRaw,
834
+ // RV1-F8:这两个字段会进 GET /sync/status 的响应 → 剥掉可能存在的 userinfo token
835
+ origin: origin === '' ? null : this.bareUrl(origin),
836
+ pushUrl: pushRaw === '' ? null : this.bareUrl(pushRaw),
620
837
  // 读不出 origin(null)→ 不算 match(状态接口据此提示「工作副本地址未知」)
621
838
  match: origin === this.o.repoUrl && (pushRaw === '' || pushRaw === this.o.repoUrl),
622
839
  ahead,
@@ -701,7 +918,7 @@ export class GitTransport {
701
918
  }
702
919
  // fetch 是网络操作(幂等读)→ 允许有限指数退避重试
703
920
  await withSyncRetry(async () => {
704
- await this.runGit(['fetch', 'origin'], { withCredential: true });
921
+ await this.runGit(['fetch', ...(await this.fetchOptionFlags()), 'origin'], { withCredential: true });
705
922
  }, this.o.retry);
706
923
  const remoteRef = `refs/remotes/origin/${branch}`;
707
924
  const refRes = await this.runGit(['rev-parse', '--verify', '--quiet', remoteRef], { allowNonZero: true });
@@ -758,6 +975,12 @@ export class GitTransport {
758
975
  const branch = await this.currentBranch();
759
976
  if (branch === '')
760
977
  return; // detached HEAD:没有 upstream 概念(与原「no tracking information」同姿态跳过)
978
+ // issue #122:稳态(远端没变)时**连 fetch 都不发**。一次 ls-remote 只回一行 refs(~1 KB),
979
+ // 而 fetch 即使没有新内容也要协商 refs、且远端仓库远大于同步内容时要遍历完整对象图
980
+ // (报告者现场:1.8 GB 仓库 / 6 MB 内容 ⇒ 一次「检查远端变更」卡死)。
981
+ // 跳过条件必须两个同时成立:远端 sha == 本地远端跟踪引用(没有新对象可拉)**且** HEAD == 该 sha
982
+ // (本地已合并)。只比 refs 就跳过 merge 会漏掉「上次 fetch 成功、merge 没跑完」的副本 ——
983
+ // 那种副本没有新对象可拉,但必须继续本地 merge。
761
984
  // **不再用 `git pull --ff-only`**:它是「fetch 写 FETCH_HEAD + 读 FETCH_HEAD 合并」的两步动作,
762
985
  // 并发驱动同一个工作副本时 FETCH_HEAD 会留下多行 for-merge 记录,随后每个 pull 都以
763
986
  // `fatal: Cannot fast-forward to multiple branches.` 失败(本机 5 并发实测全败),
@@ -765,13 +988,21 @@ export class GitTransport {
765
988
  // 显式 refspec fetch + 显式远端跟踪分支 merge 完全不读 FETCH_HEAD(同样 5 并发实测全成功),
766
989
  // 语义与 ff-only pull 一致:能快进就快进,不能快进就报「历史分叉」。
767
990
  // 参数与判定在 utils/git-fast-forward.ts(market 侧共用同一份实现)。
768
- const fetched = await this.runGit(fastForwardFetchArgs(branch), { withCredential: true, allowNonZero: true });
769
- if (fetched.code !== 0) {
770
- const combined = fetched.stderr + ' ' + fetched.stdout;
771
- // 远端还没有这个分支(全新空仓库 / 分支被改名)→ 与「无 upstream」一样静默跳过
772
- if (isMissingRemoteRefError(combined))
773
- return;
774
- await this.throwPullFailure(combined, fetched.stderr);
991
+ const remoteSha = await this.lsRemoteBranchSha(branch);
992
+ const localSha = await this.revParseSha(`refs/remotes/origin/${branch}`);
993
+ if (remoteSha !== null && remoteSha === localSha) {
994
+ if (await this.revParseSha('HEAD') === remoteSha)
995
+ return; // 已是最新:零 fetch、零 merge
996
+ }
997
+ else {
998
+ const fetched = await this.runGit(fastForwardFetchArgs(branch, await this.fetchOptionFlags()), { withCredential: true, allowNonZero: true });
999
+ if (fetched.code !== 0) {
1000
+ const combined = fetched.stderr + ' ' + fetched.stdout;
1001
+ // 远端还没有这个分支(全新空仓库 / 分支被改名)→ 与「无 upstream」一样静默跳过
1002
+ if (isMissingRemoteRefError(combined))
1003
+ return;
1004
+ await this.throwPullFailure(combined, fetched.stderr);
1005
+ }
775
1006
  }
776
1007
  const merged = await this.runGit(fastForwardMergeArgs(branch), { allowNonZero: true });
777
1008
  if (merged.code === 0)
@@ -812,6 +1043,12 @@ export class GitTransport {
812
1043
  */
813
1044
  async runGit(args, opts = {}) {
814
1045
  const cwd = opts.cwd === undefined ? this.o.workDir : opts.cwd;
1046
+ // 网络子命令一律带低速上限:真卡住在 30 s 内明确失败,而不是耗满 timeoutMs(issue #122)
1047
+ const networkArgs = NETWORK_SUBCOMMANDS.has(args[0] ?? '') ? [...LOW_SPEED_ARGS] : [];
1048
+ // SEC-12:协议护栏恒带(见 PROTOCOL_GUARD_ARGS);网络仓库再额外禁 file 传输。
1049
+ const guardArgs = this.networkRepo
1050
+ ? [...PROTOCOL_GUARD_ARGS, ...FILE_PROTOCOL_GUARD_ARGS]
1051
+ : [...PROTOCOL_GUARD_ARGS];
815
1052
  let extra = [];
816
1053
  let token = null;
817
1054
  let cleanup = null;
@@ -831,7 +1068,7 @@ export class GitTransport {
831
1068
  // 而目录里原本就有别的内容时宁可放弃重试,也绝不删用户文件。
832
1069
  const cloneTargetWasEmpty = args[0] === 'clone' ? await isEmptyDir(cwd) : false;
833
1070
  try {
834
- let result = await this.o.exec(this.o.gitBin, [...extra, ...args], { cwd, timeoutMs: this.o.timeoutMs });
1071
+ let result = await this.o.exec(this.o.gitBin, [...extra, ...guardArgs, ...networkArgs, ...args], { cwd, timeoutMs: this.o.timeoutMs });
835
1072
  // issue #120:credential helper 必须经 shell 执行(值里不含空格也一样,git 统一拼成
836
1073
  // `sh -c 'git <helper> ...'`),而 Android 上 git 二进制的 GIT_SHELL_PATH 指向 App 沙箱里
837
1074
  // 不存在的 Termux sh;`core.askpass` 又要 exec 权限(Android 10+ 对 targetSdk ≥ 29 禁执行应用
@@ -842,33 +1079,11 @@ export class GitTransport {
842
1079
  if (Object.keys(headerEnv).length > 0 && (args[0] !== 'clone' || cloneTargetWasEmpty)) {
843
1080
  if (args[0] === 'clone')
844
1081
  await clearDirContents(cwd);
845
- result = await this.o.exec(this.o.gitBin, args, { cwd, timeoutMs: this.o.timeoutMs, env: headerEnv });
1082
+ result = await this.o.exec(this.o.gitBin, [...guardArgs, ...networkArgs, ...args], { cwd, timeoutMs: this.o.timeoutMs, env: headerEnv });
846
1083
  }
847
1084
  }
848
1085
  if (result.code !== 0 && !opts.allowNonZero) {
849
- const combined = result.stderr + ' ' + result.stdout;
850
- // 统一分类(超时 / 网络 / 鉴权 / 5xx…):上层可据 kind / retryable 分流,不必解析 message
851
- const classified = classifyNetworkErrorText(combined);
852
- // issue #79:SSH 主机密钥校验失败 → 换成「怎么信任该主机」的可操作说明(绝不自动信任)
853
- if (SSH_HOST_KEY_RE.test(combined)) {
854
- throw new GitTransportError(this.hostKeyMessage(), { kind: 'auth', retryable: false });
855
- }
856
- // 推送 + 鉴权失败:git 原文只说「认证失败」——换成能照做的说明(令牌失效 / 无写权限 / 远端禁用了密码推送)
857
- // issue #115:clone 的鉴权失败原文(remote: Write access to repository not granted / 403)读不出「缺哪种权限」,
858
- // 换成点名 Contents: Read and write 的说明 —— 否则用户只会以为令牌坏了(细粒度 PAT 常只勾了 Administration)
859
- // issue #120:helper 根本没能执行时,「请确认令牌有效」是错误指引(令牌可能是好的)——
860
- // 这类失败必须点名平台原因,排在 push/clone 的鉴权文案之前。
861
- const credentialBlocked = isCredentialExecFailure(combined);
862
- const message = credentialBlocked
863
- ? this.msg('sync.git.credentialHelperBlocked', { err: this.mask(result.stderr, token) })
864
- : opts.requirePushToken === true && classified.kind === 'auth'
865
- ? this.msg('sync.git.pushAuthFailed', { err: this.mask(result.stderr, token) })
866
- : args[0] === 'clone' && classified.kind === 'auth'
867
- ? this.msg('sync.git.cloneAuthFailed', { err: this.mask(result.stderr, token) })
868
- : this.msg('sync.git.cmdFailed', { args: args.join(' '), code: String(result.code), err: this.mask(result.stderr, token) });
869
- // 归类同样不能交给原文:`cannot exec ...: No such file or directory` 里的 ENOENT 会被判成
870
- // notfound(「仓库不存在」),而真实原因是凭据通道不可用 → 钉成 auth(非瞬时、别重试)。
871
- throw new GitTransportError(message, credentialBlocked ? { kind: 'auth', retryable: false } : classified);
1086
+ this.raiseGitFailure(args, result, token, opts.requirePushToken === true);
872
1087
  }
873
1088
  return result;
874
1089
  }
@@ -877,13 +1092,44 @@ export class GitTransport {
877
1092
  throw err;
878
1093
  // 注入的 exec 实现可能直接抛错(默认实现只返回非零 code)——同样归一为带分类的传输层错误
879
1094
  const detail = err instanceof Error ? err.message : String(err);
880
- throw new GitTransportError(this.msg('sync.git.cmdFailed', { args: args.join(' '), code: 'exec', err: this.mask(detail, token) }), { ...classifyNetworkErrorText(detail), cause: err });
1095
+ throw new GitTransportError(
1096
+ // argv 里含 repoUrl 原文(clone/ls-remote/remote set-url -- <url>)→ 必须经 mask 才进文案
1097
+ this.msg('sync.git.cmdFailed', { args: this.mask(args.join(' '), token), code: 'exec', err: this.mask(detail, token) }), { ...classifyNetworkErrorText(detail), cause: err });
881
1098
  }
882
1099
  finally {
883
1100
  if (cleanup)
884
1101
  await cleanup();
885
1102
  }
886
1103
  }
1104
+ /**
1105
+ * 把「git 退出非零」归一成可操作错误(runGit 与 clone 回落共用同一套文案与分类)。
1106
+ * token 只用于脱敏,绝不进 message。
1107
+ */
1108
+ raiseGitFailure(args, result, token, requirePushToken) {
1109
+ const combined = result.stderr + ' ' + result.stdout;
1110
+ // 统一分类(超时 / 网络 / 鉴权 / 5xx…):上层可据 kind / retryable 分流,不必解析 message
1111
+ const classified = classifyNetworkErrorText(combined);
1112
+ // issue #79:SSH 主机密钥校验失败 → 换成「怎么信任该主机」的可操作说明(绝不自动信任)
1113
+ if (SSH_HOST_KEY_RE.test(combined)) {
1114
+ throw new GitTransportError(this.hostKeyMessage(), { kind: 'auth', retryable: false });
1115
+ }
1116
+ // 推送 + 鉴权失败:git 原文只说「认证失败」——换成能照做的说明(令牌失效 / 无写权限 / 远端禁用了密码推送)
1117
+ // issue #115:clone 的鉴权失败原文(remote: Write access to repository not granted / 403)读不出「缺哪种权限」,
1118
+ // 换成点名 Contents: Read and write 的说明 —— 否则用户只会以为令牌坏了(细粒度 PAT 常只勾了 Administration)
1119
+ // issue #120:helper 根本没能执行时,「请确认令牌有效」是错误指引(令牌可能是好的)——
1120
+ // 这类失败必须点名平台原因,排在 push/clone 的鉴权文案之前。
1121
+ const credentialBlocked = isCredentialExecFailure(combined);
1122
+ const message = credentialBlocked
1123
+ ? this.msg('sync.git.credentialHelperBlocked', { err: this.mask(result.stderr, token) })
1124
+ : requirePushToken && classified.kind === 'auth'
1125
+ ? this.msg('sync.git.pushAuthFailed', { err: this.mask(result.stderr, token) })
1126
+ : args[0] === 'clone' && classified.kind === 'auth'
1127
+ ? this.msg('sync.git.cloneAuthFailed', { err: this.mask(result.stderr, token) })
1128
+ : this.msg('sync.git.cmdFailed', { args: this.mask(args.join(' '), token), code: String(result.code), err: this.mask(result.stderr, token) });
1129
+ // 归类同样不能交给原文:`cannot exec ...: No such file or directory` 里的 ENOENT 会被判成
1130
+ // notfound(「仓库不存在」),而真实原因是凭据通道不可用 → 钉成 auth(非瞬时、别重试)。
1131
+ throw new GitTransportError(message, credentialBlocked ? { kind: 'auth', retryable: false } : classified);
1132
+ }
887
1133
  /**
888
1134
  * 为网络命令构造 credential helper 参数:
889
1135
  * 仅 http(s) 远端需要 token;本地路径 / ssh 走 git 原生认证(密钥),不调用 provider。
@@ -927,7 +1173,8 @@ export class GitTransport {
927
1173
  return u.port ? `${u.hostname}:${u.port}` : u.hostname;
928
1174
  }
929
1175
  catch {
930
- throw new GitTransportError(this.msg('sync.git.repoUrlInvalid', { url: this.o.repoUrl }));
1176
+ // RV1-F8:回显一律占位符 —— repoUrl 可能带 userinfo token,错误消息会进日志/响应/issue 截图
1177
+ throw new GitTransportError(this.msg('sync.git.repoUrlInvalid', { url: REPO_URL_PLACEHOLDER }));
931
1178
  }
932
1179
  }
933
1180
  /** 读取一次 token(错误消息脱敏用);非 http(s) 场景返回空 */
@@ -941,6 +1188,30 @@ export class GitTransport {
941
1188
  return null;
942
1189
  }
943
1190
  }
1191
+ /**
1192
+ * 回传体里的地址(工作副本自检的 origin / pushUrl)脱敏:只剥「凭据段」,其余原样保留。
1193
+ *
1194
+ * 为什么不整串换占位符:状态面板要显示「工作副本现在指向哪个远端」,用户靠 host/path 判断是否
1195
+ * 已跟随配置。为什么不一律剥 userinfo:`ssh://git@host` 里的 `git` 是 ssh 登录名(标准写法),
1196
+ * 剥掉会让用户认不出自己的远端 —— 与 validateRepoUrl 的口径保持一致(只有 password 位是凭据)。
1197
+ */
1198
+ bareUrl(url) {
1199
+ try {
1200
+ const parsed = new URL(url);
1201
+ const scheme = parsed.protocol.replace(/:$/, '').toLowerCase();
1202
+ const keepSshUser = scheme === 'ssh' && parsed.password === '';
1203
+ const dirty = parsed.password !== '' || (parsed.username !== '' && !keepSshUser);
1204
+ if (!dirty)
1205
+ return url;
1206
+ parsed.username = '';
1207
+ parsed.password = '';
1208
+ return parsed.toString();
1209
+ }
1210
+ catch {
1211
+ // 解析不了(scp 式 `git@host:path` 或本机路径):`git@` 是登录名不是凭据,原样返回
1212
+ return url;
1213
+ }
1214
+ }
944
1215
  /** 错误/日志脱敏:token(原文与 URL 编码两种形态)与 repoUrl 一律替换 */
945
1216
  mask(text, token) {
946
1217
  let out = text.split(this.o.repoUrl).join('[REPO_URL]');
@@ -0,0 +1,11 @@
1
+ /** 单侧预览文本上限(2 KiB **字符**预算):超出截断并追加省略号。 */
2
+ export declare const MERGE_PREVIEW_TEXT_LIMIT = 2048;
3
+ /**
4
+ * 预览文本统一出口:先 redact(敏感值绝不回传浏览器),再截断到 2 KiB。
5
+ *
6
+ * 顺序恒为「先 redact 再截断」:反过来会把跨边界的敏感值切成半个形状,让脱敏匹配不到它
7
+ * (等于把秘密截一半发出去)。redact 之后的剩余文本已不含秘密形状,截断才安全。
8
+ */
9
+ export declare function finalizePreviewText(text: string): string;
10
+ /** 把任意冲突侧值转成**可读字符串**;二进制只回传形状与字节数,绝不回传原始值对象。 */
11
+ export declare function previewTextOf(value: unknown): string;