dsh-config-manager 0.2.4 → 0.3.1

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 (136) 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 +1254 -1183
  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 +10 -0
  36. package/lib/sync/git/git-transport.js +72 -14
  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/oss4-verify.js +21 -6
  40. package/lib/sync/s3/s3-providers.d.ts +13 -0
  41. package/lib/sync/s3/s3-providers.js +6 -0
  42. package/lib/sync/s3/s3-transport.d.ts +30 -1
  43. package/lib/sync/s3/s3-transport.js +108 -23
  44. package/lib/sync/session-tombstones.d.ts +53 -0
  45. package/lib/sync/session-tombstones.js +52 -0
  46. package/lib/sync/sync-config.d.ts +55 -5
  47. package/lib/sync/sync-config.js +188 -15
  48. package/lib/sync/sync-engine.d.ts +21 -7
  49. package/lib/sync/sync-engine.js +63 -85
  50. package/lib/sync/webdav/webdav-transport.d.ts +11 -1
  51. package/lib/sync/webdav/webdav-transport.js +22 -6
  52. package/lib/ui/i18n.js +56 -36
  53. package/lib/ui/import-wizard.d.ts +1 -1
  54. package/lib/ui/import-wizard.js +2 -1
  55. package/lib/ui/overview-view.d.ts +6 -2
  56. package/lib/ui/overview-view.js +8 -1
  57. package/lib/ui/report.js +2 -1
  58. package/package.json +2 -2
  59. package/src/adapters/self.test.ts +126 -85
  60. package/src/adapters/self.ts +73 -6
  61. package/src/client/ConfigManagerSection.tsx +0 -3
  62. package/src/client/common/Icon.tsx +3 -0
  63. package/src/client/common/SectionComposition.tsx +6 -1
  64. package/src/client/common/info-hint-guard.test.ts +7 -5
  65. package/src/client/config-manager.module.css +254 -13
  66. package/src/client/environment/EnvironmentPanel.tsx +57 -47
  67. package/src/client/environment/maintenance/DiskUsageCard.tsx +3 -1
  68. package/src/client/export/ExportView.tsx +3 -1
  69. package/src/client/home/HomePanel.tsx +25 -5
  70. package/src/client/import/ImportWizardView.tsx +1 -3
  71. package/src/client/import/import-wizard-steps.tsx +1 -17
  72. package/src/client/library/ArtifactRow.tsx +13 -2
  73. package/src/client/library/LibraryPanel.tsx +12 -2
  74. package/src/client/locales.ts +53 -34
  75. package/src/client/lucide-icons.d.ts +2 -0
  76. package/src/client/market/MarketPanel.tsx +12 -11
  77. package/src/client/market/market-locales.ts +16 -16
  78. package/src/client/recovery/RollbackCard.tsx +4 -2
  79. package/src/client/recovery/recovery-locales.test.ts +4 -2
  80. package/src/client/recovery/recovery-locales.ts +23 -23
  81. package/src/client/sync/AutosyncCard.tsx +36 -10
  82. package/src/client/sync/SyncChannelEntryCard.tsx +18 -19
  83. package/src/client/sync/SyncPanel.tsx +32 -33
  84. package/src/client/sync/SyncProbeRow.tsx +23 -6
  85. package/src/client/sync/SyncSectionPickerDialog.tsx +2 -2
  86. package/src/client/sync/sync-locales.ts +24 -24
  87. package/src/core/analyzer.ts +37 -56
  88. package/src/core/backup.test.ts +139 -1
  89. package/src/core/backup.ts +145 -4
  90. package/src/core/import-defaults.ts +13 -0
  91. package/src/core/importer.ts +12 -2
  92. package/src/core/integrity-extra-entries.test.ts +205 -0
  93. package/src/core/messages.test.ts +3 -1
  94. package/src/core/messages.ts +8 -0
  95. package/src/core/model-tools.test.ts +33 -0
  96. package/src/core/model-tools.ts +20 -4
  97. package/src/index.ts +12 -21
  98. package/src/routes/import.ts +4 -1
  99. package/src/routes/recovery.test.ts +198 -1
  100. package/src/routes/recovery.ts +194 -1
  101. package/src/routes/sync.ts +27 -8
  102. package/src/security/integrity.ts +37 -0
  103. package/src/security/unverified-file-blocks.ts +192 -0
  104. package/src/sync/autosync-config.ts +9 -5
  105. package/src/sync/autosync-scheduler.test.ts +133 -6
  106. package/src/sync/autosync-scheduler.ts +118 -14
  107. package/src/sync/config-issue-reporting.test.ts +148 -0
  108. package/src/sync/config-issue-reporting.ts +75 -0
  109. package/src/sync/gc-skip.test.ts +66 -0
  110. package/src/sync/gc-skip.ts +64 -0
  111. package/src/sync/git/git-probe.test.ts +3 -2
  112. package/src/sync/git/git-transport.test.ts +168 -7
  113. package/src/sync/git/git-transport.ts +70 -14
  114. package/src/sync/merge-preview-text.ts +37 -0
  115. package/src/sync/s3/oss4-verify.ts +22 -6
  116. package/src/sync/s3/s3-conditional-write.test.ts +153 -3
  117. package/src/sync/s3/s3-delete-index-404.test.ts +26 -1
  118. package/src/sync/s3/s3-providers.ts +20 -0
  119. package/src/sync/s3/s3-transport.oss4-server.test.ts +48 -0
  120. package/src/sync/s3/s3-transport.ts +121 -21
  121. package/src/sync/session-tombstones.ts +90 -0
  122. package/src/sync/sync-config.test.ts +170 -1
  123. package/src/sync/sync-config.ts +184 -14
  124. package/src/sync/sync-engine.test.ts +238 -0
  125. package/src/sync/sync-engine.ts +79 -83
  126. package/src/sync/webdav/webdav-delete-index-404.test.ts +29 -1
  127. package/src/sync/webdav/webdav-transport.ts +26 -5
  128. package/src/ui/disk-usage-view.test.ts +2 -1
  129. package/src/ui/i18n.test.ts +47 -0
  130. package/src/ui/i18n.ts +58 -38
  131. package/src/ui/import-wizard.test.ts +18 -1
  132. package/src/ui/import-wizard.ts +3 -2
  133. package/src/ui/overview-view.test.ts +9 -0
  134. package/src/ui/overview-view.ts +9 -2
  135. package/src/ui/report.test.ts +4 -3
  136. package/src/ui/report.ts +2 -1
@@ -0,0 +1,57 @@
1
+ /**
2
+ * 本轮 blob GC 的放弃码(SYN-04)。**机器可判定**,文案由上层按码翻译(字典键由 Lead 统一加):
3
+ * 通道没有 logger,`delete()` 还会吞掉 GC 抛出的异常,所以「本轮为什么没回收」只能靠这个码如实外露。
4
+ * 三态同义:拿不到引用者内容 = 无法证明「没人引用」⇒ 本轮整轮放弃,绝不按残集删除。
5
+ *
6
+ * 单一来源:webdav / s3 两个通道都从这里导入(此前各写一份同名常量,改一侧不炸另一侧 =
7
+ * 静默漂移;本模块不 import 任何 transport,所以不存在环)。
8
+ */
9
+ export const GC_SKIP_REFERENCE_MISSING = 'gc-skip-reference-missing';
10
+ export const GC_SKIP_REFERENCE_UNREADABLE = 'gc-skip-reference-unreadable';
11
+ export const GC_SKIP_SNAPSHOT_UNPARSABLE = 'gc-skip-snapshot-unparsable';
12
+ /**
13
+ * SYN-04b:通道「本轮 GC 放弃码」的读取与冒泡(从 sync-engine.ts 下沉,行为逐字不变)。
14
+ *
15
+ * 为什么放在独立模块:SYN-04 之后 webdav/s3 遇到「引用快照 404 / 读不出」会**放弃本轮 blob GC**
16
+ * (绝不在「证明不了没人引用」时删 blob),而通道层没有 logger、delete() 又把 GC 异常吃掉
17
+ * ⇒ 放弃只能靠 transport 的只读字段外露。字段形态是 getter(见 webdav/s3 transport 的
18
+ * `get lastGcSkip()`),这里按 unknown 读、只接受非空字符串,getter 抛错也不影响 push。
19
+ *
20
+ * 判据(缺一不可,全部当「没有放弃码」):字段缺失 / null / 非字符串 / 空串 / getter 抛错。
21
+ * 读不到 ≠ 没有放弃:通道没这个能力时本来就不该冒泡告警,所以两者在调用侧合并处理。
22
+ */
23
+ export function readGcSkipCode(transport) {
24
+ try {
25
+ const raw = transport?.lastGcSkip;
26
+ return typeof raw === 'string' && raw !== '' ? raw : null;
27
+ }
28
+ catch {
29
+ return null;
30
+ }
31
+ }
32
+ /**
33
+ * SYN-04b:放弃码 → 一条 warning 文本。
34
+ *
35
+ * 码必须同时以**明文**出现:core 目录的翻译器对未知键回退键名本身({code} 插值随之丢失),
36
+ * 而文案键由上层统一补字典 —— 在补键之前,只发出裸键名等于「报了但看不出来」,日志也无法 grep。
37
+ */
38
+ export function gcSkipWarning(msg, code) {
39
+ const text = msg('sync.gcSkipped', { code });
40
+ return text.includes(code) ? text : text + ': ' + code;
41
+ }
42
+ /**
43
+ * SYN-04b:把通道的 GC 放弃码冒泡成一条 warning(`state` 保证同一轮只报一次)。
44
+ *
45
+ * 语义边界:放弃 GC **不是** push 失败 —— 快照本身已上传/已删除,只是这一轮的孤儿 blob
46
+ * 没被回收(磁盘/远端会多留几份文件)。所以它进 warnings、不进 ok,与 prune 既有语义一致。
47
+ */
48
+ export function reportGcSkipOnce(transport, msg, warnings, state) {
49
+ if (state.done)
50
+ return;
51
+ const code = readGcSkipCode(transport);
52
+ if (code === null)
53
+ return;
54
+ state.done = true;
55
+ warnings.push(gcSkipWarning(msg, code));
56
+ }
57
+ //# sourceMappingURL=gc-skip.js.map
@@ -109,6 +109,8 @@ export declare class GitTransport implements SyncTransport {
109
109
  */
110
110
  private readErrors;
111
111
  private readonly msg;
112
+ /** repoUrl 是否为网络地址(本地目录仓库 == false):决定要不要额外禁 file 传输(SEC-12)。 */
113
+ private readonly networkRepo;
112
114
  constructor(options: GitTransportOptions);
113
115
  /** 最近一次 checkIsPrivate() 的结果;null = 尚未检查 */
114
116
  get isPrivateHint(): boolean | null;
@@ -283,6 +285,14 @@ export declare class GitTransport implements SyncTransport {
283
285
  private repoHost;
284
286
  /** 读取一次 token(错误消息脱敏用);非 http(s) 场景返回空 */
285
287
  private readTokenOnce;
288
+ /**
289
+ * 回传体里的地址(工作副本自检的 origin / pushUrl)脱敏:只剥「凭据段」,其余原样保留。
290
+ *
291
+ * 为什么不整串换占位符:状态面板要显示「工作副本现在指向哪个远端」,用户靠 host/path 判断是否
292
+ * 已跟随配置。为什么不一律剥 userinfo:`ssh://git@host` 里的 `git` 是 ssh 登录名(标准写法),
293
+ * 剥掉会让用户认不出自己的远端 —— 与 validateRepoUrl 的口径保持一致(只有 password 位是凭据)。
294
+ */
295
+ private bareUrl;
286
296
  /** 错误/日志脱敏:token(原文与 URL 编码两种形态)与 repoUrl 一律替换 */
287
297
  private mask;
288
298
  /**
@@ -26,6 +26,7 @@ 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';
@@ -111,6 +112,19 @@ const SYNC_ROOT_DIRS = [...ADOPT_ROOT_ALLOW];
111
112
  */
112
113
  const NETWORK_SUBCOMMANDS = new Set(['clone', 'fetch', 'push', 'ls-remote', 'pull']);
113
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]';
114
128
  const DEFAULT_AUTHOR = { name: 'DSH Config Sync', email: 'sync@dsh.local' };
115
129
  const DEFAULT_CREDENTIAL_USERNAME = 'oauth2';
116
130
  /** 快照 id 安全字符集:字母数字开头,仅 . _ -;防路径穿越与 commit message 注入 */
@@ -270,6 +284,8 @@ export class GitTransport {
270
284
  */
271
285
  readErrors = [];
272
286
  msg;
287
+ /** repoUrl 是否为网络地址(本地目录仓库 == false):决定要不要额外禁 file 传输(SEC-12)。 */
288
+ networkRepo;
273
289
  constructor(options) {
274
290
  if (typeof options.repoUrl !== 'string' || options.repoUrl.length === 0) {
275
291
  throw new GitTransportError(zhMsg('sync.git.repoUrlRequired'));
@@ -282,6 +298,16 @@ export class GitTransport {
282
298
  throw new GitTransportError(zhMsg('sync.git.credentialsRequired'));
283
299
  }
284
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';
285
311
  this.o = {
286
312
  repoUrl: options.repoUrl,
287
313
  workDir: options.workDir,
@@ -494,12 +520,12 @@ export class GitTransport {
494
520
  async checkIsPrivate() {
495
521
  if (this.privateHint !== null)
496
522
  return this.privateHint;
497
- 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 });
498
524
  if (anon.code === 0) {
499
525
  this.privateHint = false;
500
526
  return false;
501
527
  }
502
- 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 });
503
529
  if (authed.code === 0) {
504
530
  this.privateHint = true;
505
531
  return true;
@@ -618,7 +644,7 @@ export class GitTransport {
618
644
  async cloneIntoWorkDir() {
619
645
  const cwd = this.o.workDir;
620
646
  this.partialClone = null; // reclone 后重新判定(配置可能变)
621
- const filteredArgs = ['clone', '--filter=blob:none', '--no-checkout', this.o.repoUrl, '.'];
647
+ const filteredArgs = ['clone', '--filter=blob:none', '--no-checkout', '--', this.o.repoUrl, '.'];
622
648
  const filtered = await this.runGit(filteredArgs, { cwd, withCredential: true, allowNonZero: true });
623
649
  if (filtered.code !== 0) {
624
650
  if (!UNSUPPORTED_GIT_OPTION_RE.test(filtered.stderr + ' ' + filtered.stdout)) {
@@ -627,7 +653,7 @@ export class GitTransport {
627
653
  }
628
654
  // 老 git:回落全量 clone(全量 clone 自带 checkout)
629
655
  await clearDirContents(cwd);
630
- await this.runGit(['clone', this.o.repoUrl, '.'], { cwd, withCredential: true });
656
+ await this.runGit(['clone', '--', this.o.repoUrl, '.'], { cwd, withCredential: true });
631
657
  return;
632
658
  }
633
659
  const branch = await this.currentBranch();
@@ -697,16 +723,16 @@ export class GitTransport {
697
723
  const current = await this.runGit(['remote', 'get-url', 'origin'], { allowNonZero: true });
698
724
  const origin = current.code === 0 ? current.stdout.trim() : '';
699
725
  if (current.code !== 0) {
700
- await this.runGit(['remote', 'add', 'origin', this.o.repoUrl]);
726
+ await this.runGit(['remote', 'add', 'origin', '--', this.o.repoUrl]);
701
727
  }
702
728
  else if (origin !== '' && origin !== this.o.repoUrl) {
703
- await this.runGit(['remote', 'set-url', 'origin', this.o.repoUrl]);
729
+ await this.runGit(['remote', 'set-url', 'origin', '--', this.o.repoUrl]);
704
730
  this.partialClone = null; // 换了远端 ⇒ promisor 判定失效(issue #122)
705
731
  }
706
732
  const push = await this.runGit(['remote', 'get-url', '--push', 'origin'], { allowNonZero: true });
707
733
  const pushUrl = push.code === 0 ? push.stdout.trim() : '';
708
734
  if (pushUrl !== '' && pushUrl !== this.o.repoUrl) {
709
- await this.runGit(['remote', 'set-url', '--push', 'origin', this.o.repoUrl]);
735
+ await this.runGit(['remote', 'set-url', '--push', 'origin', '--', this.o.repoUrl]);
710
736
  }
711
737
  }
712
738
  /**
@@ -805,8 +831,9 @@ export class GitTransport {
805
831
  return {
806
832
  path: this.o.workDir,
807
833
  exists: true,
808
- origin: origin === '' ? null : origin,
809
- 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),
810
837
  // 读不出 origin(null)→ 不算 match(状态接口据此提示「工作副本地址未知」)
811
838
  match: origin === this.o.repoUrl && (pushRaw === '' || pushRaw === this.o.repoUrl),
812
839
  ahead,
@@ -1018,6 +1045,10 @@ export class GitTransport {
1018
1045
  const cwd = opts.cwd === undefined ? this.o.workDir : opts.cwd;
1019
1046
  // 网络子命令一律带低速上限:真卡住在 30 s 内明确失败,而不是耗满 timeoutMs(issue #122)
1020
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];
1021
1052
  let extra = [];
1022
1053
  let token = null;
1023
1054
  let cleanup = null;
@@ -1037,7 +1068,7 @@ export class GitTransport {
1037
1068
  // 而目录里原本就有别的内容时宁可放弃重试,也绝不删用户文件。
1038
1069
  const cloneTargetWasEmpty = args[0] === 'clone' ? await isEmptyDir(cwd) : false;
1039
1070
  try {
1040
- let result = await this.o.exec(this.o.gitBin, [...extra, ...networkArgs, ...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 });
1041
1072
  // issue #120:credential helper 必须经 shell 执行(值里不含空格也一样,git 统一拼成
1042
1073
  // `sh -c 'git <helper> ...'`),而 Android 上 git 二进制的 GIT_SHELL_PATH 指向 App 沙箱里
1043
1074
  // 不存在的 Termux sh;`core.askpass` 又要 exec 权限(Android 10+ 对 targetSdk ≥ 29 禁执行应用
@@ -1048,7 +1079,7 @@ export class GitTransport {
1048
1079
  if (Object.keys(headerEnv).length > 0 && (args[0] !== 'clone' || cloneTargetWasEmpty)) {
1049
1080
  if (args[0] === 'clone')
1050
1081
  await clearDirContents(cwd);
1051
- result = await this.o.exec(this.o.gitBin, [...networkArgs, ...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 });
1052
1083
  }
1053
1084
  }
1054
1085
  if (result.code !== 0 && !opts.allowNonZero) {
@@ -1061,7 +1092,9 @@ export class GitTransport {
1061
1092
  throw err;
1062
1093
  // 注入的 exec 实现可能直接抛错(默认实现只返回非零 code)——同样归一为带分类的传输层错误
1063
1094
  const detail = err instanceof Error ? err.message : String(err);
1064
- 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 });
1065
1098
  }
1066
1099
  finally {
1067
1100
  if (cleanup)
@@ -1092,7 +1125,7 @@ export class GitTransport {
1092
1125
  ? this.msg('sync.git.pushAuthFailed', { err: this.mask(result.stderr, token) })
1093
1126
  : args[0] === 'clone' && classified.kind === 'auth'
1094
1127
  ? this.msg('sync.git.cloneAuthFailed', { err: this.mask(result.stderr, token) })
1095
- : this.msg('sync.git.cmdFailed', { args: args.join(' '), code: String(result.code), 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) });
1096
1129
  // 归类同样不能交给原文:`cannot exec ...: No such file or directory` 里的 ENOENT 会被判成
1097
1130
  // notfound(「仓库不存在」),而真实原因是凭据通道不可用 → 钉成 auth(非瞬时、别重试)。
1098
1131
  throw new GitTransportError(message, credentialBlocked ? { kind: 'auth', retryable: false } : classified);
@@ -1140,7 +1173,8 @@ export class GitTransport {
1140
1173
  return u.port ? `${u.hostname}:${u.port}` : u.hostname;
1141
1174
  }
1142
1175
  catch {
1143
- 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 }));
1144
1178
  }
1145
1179
  }
1146
1180
  /** 读取一次 token(错误消息脱敏用);非 http(s) 场景返回空 */
@@ -1154,6 +1188,30 @@ export class GitTransport {
1154
1188
  return null;
1155
1189
  }
1156
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
+ }
1157
1215
  /** 错误/日志脱敏:token(原文与 URL 编码两种形态)与 repoUrl 一律替换 */
1158
1216
  mask(text, token) {
1159
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;
@@ -0,0 +1,38 @@
1
+ import { redact } from '../security/redaction.js';
2
+ /** 单侧预览文本上限(2 KiB **字符**预算):超出截断并追加省略号。 */
3
+ export const MERGE_PREVIEW_TEXT_LIMIT = 2048;
4
+ /** 严格 UTF-8 解码器:非法字节序列直接抛错(用于区分文本与二进制文件冲突)。 */
5
+ const STRICT_UTF8 = new TextDecoder('utf-8', { fatal: true });
6
+ /**
7
+ * 预览文本统一出口:先 redact(敏感值绝不回传浏览器),再截断到 2 KiB。
8
+ *
9
+ * 顺序恒为「先 redact 再截断」:反过来会把跨边界的敏感值切成半个形状,让脱敏匹配不到它
10
+ * (等于把秘密截一半发出去)。redact 之后的剩余文本已不含秘密形状,截断才安全。
11
+ */
12
+ export function finalizePreviewText(text) {
13
+ const masked = redact(text);
14
+ return masked.length > MERGE_PREVIEW_TEXT_LIMIT ? `${masked.slice(0, MERGE_PREVIEW_TEXT_LIMIT)}…` : masked;
15
+ }
16
+ /** 把任意冲突侧值转成**可读字符串**;二进制只回传形状与字节数,绝不回传原始值对象。 */
17
+ export function previewTextOf(value) {
18
+ if (value === undefined)
19
+ return '';
20
+ if (typeof value === 'string')
21
+ return finalizePreviewText(value);
22
+ if (value instanceof Uint8Array) {
23
+ try {
24
+ return finalizePreviewText(STRICT_UTF8.decode(value));
25
+ }
26
+ catch {
27
+ // 二进制内容解码只会得到乱码(同样误导用户)→ 只回传形状;JSON 是数据形态,不是文案
28
+ return JSON.stringify({ binary: true, bytes: value.length });
29
+ }
30
+ }
31
+ try {
32
+ return finalizePreviewText(JSON.stringify(value) ?? '');
33
+ }
34
+ catch {
35
+ return finalizePreviewText(String(value));
36
+ }
37
+ }
38
+ //# sourceMappingURL=merge-preview-text.js.map
@@ -7,6 +7,10 @@
7
7
  * `getResourceV4`、`oss/auth.go` 的 `getSubResource` / `getSignedStrV4`)**独立重写**一遍,
8
8
  * 只吃「收到的 HTTP 请求」(method / url / 头 / body),绝不复用客户端的签名中间量。
9
9
  *
10
+ * 也照真服务端实现**条件写能力**:PutObject 收到 If-Match / If-None-Match 一律拒(0017-00000245),
11
+ * 只接受 `x-oss-forbid-overwrite: true`(已存在 → 409 FileAlreadyExists)—— 这一层不照真服务端写,
12
+ * 「本地全绿、真机 400」的盲点就会回来(issue #109 第二层)。
13
+ *
10
14
  * 用法:`s3-transport.oss4-server.test.ts`(内存对象存储,逐请求验签)与
11
15
  * `scripts/oss-live-check.mjs`(真桶联调)。它证明的是「与本仓库对官方算法的独立复现一致」,
12
16
  * 不等于官方服务端盖章 —— 真桶连通性要靠带真实密钥跑一次脚本。
@@ -96,6 +100,10 @@ export function verifyOssV4(init, cfg) {
96
100
  }
97
101
  return { ok: true, reason: '', canonicalRequest, stringToSign, signature, objectKey, bucketLevel };
98
102
  }
103
+ /** 真 OSS 会拒绝的条件写头(PutObject 不支持;错误码 0017-00000245)。 */
104
+ const IF_CONDITIONAL_HEADERS = ['if-match', 'if-none-match'];
105
+ /** OSS 回显头名时用的原始大小写(真机报文里看到的是 `If-None-Match`)。 */
106
+ const IF_HEADER_ECHO = { 'if-match': 'If-Match', 'if-none-match': 'If-None-Match' };
99
107
  /**
100
108
  * 内存 OSS(验签通过才落盘/回读):返回可直接注入 S3Transport 的 `request`,
101
109
  * 以及验签成功/失败流水,供测试与联调脚本断言。
@@ -127,13 +135,20 @@ export function makeOssVerifyServer(cfg) {
127
135
  const h = lower(headers);
128
136
  const existing = objects.get(key);
129
137
  if (method === 'PUT') {
130
- const ifMatch = h['if-match'];
131
- const ifNoneMatch = h['if-none-match'];
132
- if (ifMatch !== undefined && existing !== undefined && ifMatch.replace(/"/g, '') !== existing.etag) {
133
- return respond(412, '<Error><Code>PreconditionFailed</Code></Error>');
138
+ // 真 OSS 的 PutObject **不支持 If-Match / If-None-Match**:收到就回
139
+ // 400 InvalidArgument「A header you provided implies functionality that is not implemented.」
140
+ // (错误码 0017-00000245,issue #109 第二层)。这里必须照真服务端拒掉 —— 之前这个验签器
141
+ // 自己实现了 if-none-match,等于用自家规则验自家人,于是「14 个请求零失败」漏掉了这一层。
142
+ const unsupported = IF_CONDITIONAL_HEADERS.find((n) => h[n] !== undefined);
143
+ if (unsupported !== undefined) {
144
+ return respond(400, '<Error><Code>InvalidArgument</Code><Message>A header you provided implies '
145
+ + 'functionality that is not implemented.</Message><Header>' + IF_HEADER_ECHO[unsupported]
146
+ + '</Header><EC>0017-00000245</EC></Error>');
134
147
  }
135
- if (ifNoneMatch === '*' && existing !== undefined) {
136
- return respond(412, '<Error><Code>PreconditionFailed</Code></Error>');
148
+ // OSS 唯一支持的「禁止覆盖」:对象已存在即 409 FileAlreadyExists。
149
+ if ((h['x-oss-forbid-overwrite'] ?? '').trim().toLowerCase() === 'true' && existing !== undefined) {
150
+ return respond(409, '<Error><Code>FileAlreadyExists</Code><Message>The object you specified already '
151
+ + 'exists and cannot be overwritten again.</Message></Error>');
137
152
  }
138
153
  const body = opts.body ?? '';
139
154
  const etag = sha256(body).slice(0, 32);
@@ -6,6 +6,15 @@ export declare const S3_DEFAULT_PREFIX = "dsh-config-manager";
6
6
  export declare const S3_INDEX_FILE = "index.json";
7
7
  export declare const S3_BLOBS_SEG = "blobs";
8
8
  export declare const S3_BLOBS_INDEX_FILE = "blobs-index.json";
9
+ /**
10
+ * 条件写能力(决定「防两台设备同时写」怎么落地):
11
+ * - `etag`:AWS 风格 If-Match / If-None-Match(s3 / minio / cos / kodo);
12
+ * - `forbid-overwrite`:阿里云 OSS —— PutObject **不支持 If-\***(真机会回 400
13
+ * InvalidArgument「A header you provided implies functionality that is not implemented.」,
14
+ * 错误码 0017-00000245;issue #109 第二层),只有 `x-oss-forbid-overwrite: true`
15
+ * 「对象已存在即拒」这一种禁止覆盖语义。
16
+ */
17
+ export type S3ConditionalWrite = 'etag' | 'forbid-overwrite';
9
18
  export interface S3ProviderVariant {
10
19
  id: S3CompatProvider;
11
20
  /** 默认签名方言(可被 \`dialectId\` 覆盖) */
@@ -18,6 +27,8 @@ export interface S3ProviderVariant {
18
27
  endpointTemplate?: string;
19
28
  /** 默认寻址风格:true = path-style(<endpoint>/<bucket>/<key>),false = virtual-host(<bucket>.<endpoint>/<key>) */
20
29
  defaultPathStyle: boolean;
30
+ /** 条件写能力(见 S3ConditionalWrite;与签名方言解耦,跟着服务商走而不是跟着 dialectId 走) */
31
+ conditionalWrite: S3ConditionalWrite;
21
32
  /**
22
33
  * 变体说明的**目录键**(自 t6 起字段是键而不是文案 —— 中文只存在于 `sync/s3/messages.ts` 的本地目录,
23
34
  * 经 `s3Msg` / `composeMsg(host, s3Msg)` 解析成当前语言;本字段本身不渲染)。
@@ -46,6 +57,8 @@ export interface S3Target {
46
57
  prefix: string;
47
58
  pathStyle: boolean;
48
59
  dialect: SigV4Dialect;
60
+ /** 条件写能力(来自变体表;dialectId 覆盖不影响它) */
61
+ conditionalWrite: S3ConditionalWrite;
49
62
  }
50
63
  export interface S3TargetInput {
51
64
  provider: S3CompatProvider;
@@ -31,25 +31,30 @@ export const S3_PROVIDER_VARIANTS = {
31
31
  s3: {
32
32
  id: 's3', dialectId: 'aws4', service: 's3', defaultRegion: 'us-east-1',
33
33
  endpointTemplate: 'https://s3.{region}.amazonaws.com', defaultPathStyle: false,
34
+ conditionalWrite: 'etag',
34
35
  note: 'sync.s3.providerNoteS3',
35
36
  },
36
37
  oss: {
37
38
  id: 'oss', dialectId: 'oss4', service: 'oss',
38
39
  endpointTemplate: 'https://oss-{region}.aliyuncs.com', defaultPathStyle: false,
40
+ conditionalWrite: 'forbid-overwrite',
39
41
  note: 'sync.s3.providerNoteOss',
40
42
  },
41
43
  cos: {
42
44
  id: 'cos', dialectId: 'aws4', service: 's3',
43
45
  endpointTemplate: 'https://cos.{region}.myqcloud.com', defaultPathStyle: false,
46
+ conditionalWrite: 'etag',
44
47
  note: 'sync.s3.providerNoteCos',
45
48
  },
46
49
  minio: {
47
50
  id: 'minio', dialectId: 'aws4', service: 's3', defaultRegion: 'us-east-1', defaultPathStyle: true,
51
+ conditionalWrite: 'etag',
48
52
  note: 'sync.s3.providerNoteMinio',
49
53
  },
50
54
  kodo: {
51
55
  id: 'kodo', dialectId: 'aws4', service: 's3',
52
56
  endpointTemplate: 'https://s3-{region}.qiniucs.com', defaultPathStyle: false,
57
+ conditionalWrite: 'etag',
53
58
  note: 'sync.s3.providerNoteKodo',
54
59
  },
55
60
  };
@@ -119,6 +124,7 @@ export function resolveS3Target(input) {
119
124
  prefix,
120
125
  pathStyle: input.pathStyle ?? variant.defaultPathStyle,
121
126
  dialect: sigV4Dialect(input.dialectId ?? variant.dialectId),
127
+ conditionalWrite: variant.conditionalWrite,
122
128
  },
123
129
  };
124
130
  }
@@ -1,4 +1,5 @@
1
1
  import type { MsgFunc } from '../../core/msg-types.ts';
2
+ import type { GcSkipCode } from '../gc-skip.ts';
2
3
  import { SyncTransportError } from '../transport.ts';
3
4
  import type { SyncProbeResult, SyncRetryOptions, SyncSnapshot, SyncSnapshotMeta, SyncTransport, SyncTransportErrorOptions } from '../transport.ts';
4
5
  import type { SigV4DialectId } from './sigv4.ts';
@@ -63,6 +64,10 @@ export declare class S3Transport implements SyncTransport {
63
64
  readonly type: string;
64
65
  private readonly target;
65
66
  private readonly o;
67
+ /** 最近一轮 blob GC 的放弃码(`null` = 跑完或未触发;SYN-04)。 */
68
+ private gcSkip;
69
+ /** 最近一轮 blob GC 是否因「无法证明引用集完整」而整体放弃(`null` = 正常跑完),供上层给用户提示。 */
70
+ get lastGcSkip(): GcSkipCode | null;
66
71
  constructor(options: S3TransportOptions);
67
72
  /** 解析后的目标(只读;端点/region/寻址风格/方言;**不含任何密钥**)。 */
68
73
  get resolvedTarget(): S3Target;
@@ -79,6 +84,25 @@ export declare class S3Transport implements SyncTransport {
79
84
  delete(id: string): Promise<void>;
80
85
  /** 条件写失败:远端索引在本次读取之后被别人改过 —— 中止写入让用户重跑(cloud-sync 借鉴项 ①)。 */
81
86
  private concurrentWrite;
87
+ /**
88
+ * OSS 方言的「ETag 条件写」替身(issue #109 第二层):PutObject 既无 If-Match 也无
89
+ * If-None-Match,`x-oss-forbid-overwrite` 只能表达「别覆盖已存在的对象」,表达不了
90
+ * 「远端必须还是我读到的那一版」。所以索引进已存在时改成**写前 HEAD 复核 ETag**:
91
+ * 变了 / 对象没了 → 按并发写中止(零写入)。
92
+ *
93
+ * **不是原子的**:复核与 PUT 之间仍有窗口(服务端不支持条件写就没有真正的解),
94
+ * 比无保护强、比 If-Match 弱 —— 如实登记在 docs/decisions/0003。
95
+ * 其它方言(etag)与「服务端不给 ETag」两种情况一律直接放行,不改既有行为。
96
+ */
97
+ private reassertIndexEtag;
98
+ /**
99
+ * 条件写失败分类(issue #109 第二层复核):`isConcurrentWrite` 只看「状态码像不像」,
100
+ * 这里再问报文一句确认「对象确实已存在」。OSS 的 **409 不止 FileAlreadyExists** ——
101
+ * FileImmutable(Bucket 数据处于保护状态,删改都会被拒)同为 409,一律按并发写报
102
+ * 「别的设备改过索引」就是假话。报文读不出时仍按并发写处理(宁可让用户重跑一次,
103
+ * 不吞掉真冲突)。412 是 If-Match 语义,恒为并发写。
104
+ */
105
+ private conditionalFailure;
82
106
  /**
83
107
  * 连通性探针(cloud-sync 借鉴项 ②):HEAD 桶证明端点/凭据/桶可达,再读一次索引回报快照数。
84
108
  * 重定向(301/307/308)时读 x-amz-bucket-region 直接把「region 该填什么」告诉用户 ——
@@ -90,7 +114,10 @@ export declare class S3Transport implements SyncTransport {
90
114
  private secretOnce;
91
115
  /** 发送一次已签名请求;网络错误/超时归一为带分类的通道错误 */
92
116
  private send;
117
+ /** 读错误响应体(未脱敏原文,截断到 ERR_BODY_MAX;读不出按空串) */
118
+ private errorBody;
93
119
  /** 构造 HTTP 非 2xx 失败消息:附上脱敏后的响应体片段(截断) */
120
+ private failMessage;
94
121
  private failText;
95
122
  /** 识别超时错误(AbortError / TimeoutError) */
96
123
  private isTimeout;
@@ -129,6 +156,8 @@ export declare class S3Transport implements SyncTransport {
129
156
  /** 下载后把引用形态还原成文件分区(缺 blob → 硬失败,绝不降级为空分区) */
130
157
  private rehydrate;
131
158
  /** blob 仓 GC:逐份读仍存在的快照收集引用,删除无人引用且超保护窗的 blob;
132
- * 读坏任一份快照 → 本轮直接放弃(宁可留垃圾,不可删在用的) */
159
+ * 读不坏任何一份快照 → 正常回收,否则本轮整体放弃(宁可留垃圾,不可删在用的)。
160
+ * SYN-04(P1):**404 也放弃本轮** —— 条目在但文件 404 = 拿不到内容 = 无法证明「没人引用」,
161
+ * 按残集回收会删掉仍在用的 blob(与 WebDAV 同型,口径一致)。 */
133
162
  private gcBlobStore;
134
163
  }