dsh-profile-config-sync 0.6.46 → 0.7.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.
package/index.js CHANGED
@@ -20,8 +20,15 @@ import { AsyncLocalStorage } from 'node:async_hooks'
20
20
  import { spawn } from 'node:child_process'
21
21
  import { createHash } from 'node:crypto'
22
22
  import { createRequire } from 'node:module'
23
+ import { gunzipSync } from 'node:zlib'
23
24
  import { closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, readSync, rmSync, statSync, unlinkSync, writeFileSync, chmodSync } from 'node:fs'
24
25
  import { writeFileAtomicSync } from './runtime/atomic-write.mjs'
26
+ import { SETTINGS_SOURCES, settingsSourcePath as settingsSourcePathOf, zeroVolatileFields } from './runtime/settings-sources.mjs'
27
+ import {
28
+ EXTRA_CONFIG_NAME, EXTRA_DEFAULT_EXCLUDE, EXTRA_DEFAULT_SKIP_DIRS, EXTRA_HARD_MAX_BYTES,
29
+ EXTRA_MANDATORY_EXCLUDES, EXTRA_MANDATORY_SKIP_DIRS, extraConfigPath, extraSkipReason,
30
+ readExtraConfig, topUpExtraMandatory, wildcardToRegex,
31
+ } from './runtime/extra-rules.mjs'
25
32
  import { homedir, hostname, tmpdir } from 'node:os'
26
33
  import { basename, dirname, isAbsolute, join, relative } from 'node:path'
27
34
  import { fileURLToPath } from 'node:url'
@@ -36,10 +43,12 @@ import { setWorkspaceStateLive, setSessionStateLive } from './runtime/tools/work
36
43
  // 0.4.0:跨端(Windows / macOS / Linux)。平台差异全部收敛在 runtime/platform.mjs,
37
44
  // 这里只消费它的结论 —— 业务代码里不允许再出现 process.platform 分支。
38
45
  import {
39
- IS_WIN, OS, appRootCandidates, appRootLayout, clientExecutable, clientProcessNames,
40
- findGit, findSsh, hostNodeExe,
46
+ IS_WIN, OS, appRootCandidates, appRootLayout, asarPath, clientExecutable,
47
+ clientProcessPattern, defaultRepoPath, findGit, findSsh, hostNodeExe,
41
48
  hostDshNodeModules as platformHostDshNodeModules,
42
- isAppRoot as pfIsAppRoot, isFile as pfIsFile, platformFamily, platformLabel,
49
+ isAppRoot as pfIsAppRoot, isFile as pfIsFile, normalizeAppRoot, platformFamily, platformLabel,
50
+ postExitScriptName, readAppVersion as platformReadAppVersion,
51
+ readElectronVersion as platformReadElectronVersion, repoPathProblem,
43
52
  normalizeSyncExtraPaths,
44
53
  } from './runtime/platform.mjs'
45
54
  // 0.4.0:客户端身份(仓库里 machines/<id>.json)—— 跨端不分叉仓库,只登记「谁推的」
@@ -48,7 +57,9 @@ import { listMachines } from './runtime/machines.mjs'
48
57
  import { checkContract, readContract } from './runtime/contract.mjs'
49
58
  // 0.4.0:WebDAV 通道(第二种同步方式,与 git 共用同一份仓库格式)
50
59
  import {
51
- downloadRepo, isSecureUrl, normalizeWebdav, testConnection, uploadRepo, webdavActive,
60
+ downloadRepo, isSecureUrl, normalizeWebdav, sanitizeUserAgent, testConnection, uploadRepo, webdavActive,
61
+ purgeForbiddenFromCloud,
62
+ purgeStaleLocksFromCloud,
52
63
  } from './runtime/webdav.mjs'
53
64
 
54
65
  const pluginRequire = createRequire(import.meta.url)
@@ -63,6 +74,8 @@ const ROUTE_CONFLICT = '/config-sync/conflict'
63
74
  // 0.3.30:跨机路径确认(每台机器把自己的根目录报给插件一次)与问题反馈(落仓库 feedback\ 再推 GitHub)
64
75
  const ROUTE_ROOTS = '/config-sync/roots'
65
76
  const ROUTE_FEEDBACK = '/config-sync/feedback'
77
+ /** 反馈请求体上限:4 个附件 × 20 MB 的 base64(约 27 MB/个)+ 余量。 */
78
+ const ROUTE_FEEDBACK_MAX_BODY = 160 * 1024 * 1024
66
79
  // 0.3.76:会话投影缓存守卫(GET 只读扫描 / POST scan|sweep|clear|busy)
67
80
  const ROUTE_CACHE_GUARD = '/config-sync/cache-guard'
68
81
  // 0.3.76:工作区显示状态(GET 读 / POST workspace 三态 | session 独立隐藏)
@@ -100,32 +113,54 @@ const PLUGIN_VERSION = (() => {
100
113
  return String(pkg.version || '')
101
114
  } catch { return '' }
102
115
  })()
103
- // version.json 放在公开插件仓库根:{ version, notes, releasedAt, tgz, sha256 }
104
- // 更新检查只读这一个文件,几百字节,不拉整包。公开仓库不需要令牌。
116
+ // ── 0.6.47 起:更新检查只查 npm,不看 GitHub ──
117
+ // 用户明确要求「插件更新只检查 npm 是否有更新,不检查 GitHub」。
105
118
  //
106
- // 为什么不止一个地址:raw.githubusercontent.com 在这类网络上时通时不通(本机实测一次 20 秒超时 code=000、
107
- // 另一次 538ms 正常),而宿主的 fetch 是 Node 内置实现、**不读系统代理**,超时一到就被 AbortController 掐断,
108
- // 面板上只剩一句 "This operation was aborted"。
119
+ // 版本判定:npm registry 的 dist-tags.latest。
120
+ // 下载地址与校验值:该版本的单版本文档里的 dist.tarball / dist.integrity / dist.shasum。
121
+ // 发布说明:npm tarball 里的 package/release-notes.json(已加进 package.json 的 files 字段)。
109
122
  //
110
- // 候选顺序:两个实时反代(gh-proxy / ghfast,实测 1 秒内拿到最新清单,且能把 tgz 一起拉下来)→ 直连 raw。
111
- // **不要**用 jsDelivr 兜清单:它对 `@main` 这类分支别名有明显缓存(实测发版后仍返回上一版清单,purge 接口也没
112
- // 立刻刷新),拿它当清单源会让"有新版本"晚几小时才出现,比读不到更误导人。
113
- // 用户自己在设置里填了清单地址时只用他那一个 —— 不掺镜像,免得"读到的其实不是他指定的源"。
114
- const UPDATE_REPO_OWNER = 'huanyu-a'
115
- const UPDATE_REPO_NAME = 'dsh-profile-config-sync'
116
- const RAW_MANIFEST_URL = `https://raw.githubusercontent.com/${UPDATE_REPO_OWNER}/${UPDATE_REPO_NAME}/main/version.json`
117
- const API_MANIFEST_URL = `https://api.github.com/repos/${UPDATE_REPO_OWNER}/${UPDATE_REPO_NAME}/contents/version.json?ref=main`
118
- const UPDATE_MANIFEST_MIRRORS = [
119
- `https://gh-proxy.com/${RAW_MANIFEST_URL}`,
120
- `https://ghfast.top/${RAW_MANIFEST_URL}`,
121
- API_MANIFEST_URL,
122
- RAW_MANIFEST_URL,
123
- ]
124
- const UPDATE_MANIFEST_URL = RAW_MANIFEST_URL
125
- // 30 秒:慢链路 10 秒根本不够(raw 通的时候也要几百毫秒到十几秒不等)
123
+ // 为什么这么换(不是"顺手改一下",是踩到过坑):
124
+ // GitHub release 资产与 npm tarball **不是同一个字节流** —— 实测 npm pack 产物与 registry 上的
125
+ // tarball 逐字节一致(sha256 相同),但与 pnpm pack 的资产不同,差在打包元数据。
126
+ // 于是旧实现「清单里记 pnpm 的 sha256、下载走 npm 兜底」在校验那一步必然失败,
127
+ // 那条「npm 兜底下载」的路一直有坑。改成单一 npm 源后,校验改用 registry 自己的
128
+ // dist.integrity / dist.shasum,权威值与被校验物同源,不会再出现这种错配。
129
+ //
130
+ // npm 作为唯一更新源(0.6.47 起)
131
+ const NPM_PACKAGE_NAME = 'dsh-profile-config-sync'
132
+ // registry / dist-tags / 版本文档的 URL 一律由 npmUrls(registry) 现算(见下方 effectiveNpmRegistry),
133
+ // 不在模块顶层写死 —— 否则夹具没法用本地服务器当 registry。
134
+
135
+ // 30 秒:慢链路 10 秒根本不够
126
136
  const UPDATE_FETCH_TIMEOUT = 30 * 1000
127
137
  const UPDATE_CHECK_TTL = 30 * 60 * 1000
128
138
  const GH_TOKEN_ENV_CANDIDATES = ['DSH_CONFIG_SYNC_GH_TOKEN', 'GITHUB_TOKEN', 'GH_TOKEN']
139
+ // 0.6.47:npm registry 可被设置或环境变量覆盖。
140
+ // 用途有两个:① 国内用户换 npmmirror 之类镜像(仍然只查 npm,只是换了个 registry);
141
+ // ② 审计夹具用本地 HTTP 服务器当 registry,不必真的连公网。
142
+ // 环境变量优先,便于夹具在进程启动前就定好;设置里改了下次检查生效。
143
+ const NPM_REGISTRY_ENV = 'DSH_CONFIG_SYNC_NPM_REGISTRY'
144
+ const DEFAULT_NPM_REGISTRY = 'https://registry.npmjs.org'
145
+
146
+ function effectiveNpmRegistry(settings = {}) {
147
+ const fromSettings = String((settings && settings.updateRegistry) || '').trim()
148
+ if (fromSettings) return fromSettings.replace(/\/+$/, '')
149
+ const fromEnv = String(process.env[NPM_REGISTRY_ENV] || '').trim()
150
+ if (fromEnv) return fromEnv.replace(/\/+$/, '')
151
+ return DEFAULT_NPM_REGISTRY
152
+ }
153
+
154
+ function npmUrls(registry) {
155
+ const base = String(registry || DEFAULT_NPM_REGISTRY).replace(/\/+$/, '')
156
+ return {
157
+ registry: base,
158
+ distTags: `${base}/${NPM_PACKAGE_NAME}/-/package/${NPM_PACKAGE_NAME}/dist-tags`,
159
+ versionDoc: (v) => `${base}/${NPM_PACKAGE_NAME}/${encodeURIComponent(v)}`,
160
+ latestDoc: `${base}/${NPM_PACKAGE_NAME}/latest`,
161
+ tarball: (v) => `${base}/${NPM_PACKAGE_NAME}/-/${NPM_PACKAGE_NAME}-${v}.tgz`,
162
+ }
163
+ }
129
164
 
130
165
  const winEnvCache = new Map()
131
166
  function clearWinEnvCache() { winEnvCache.clear() }
@@ -252,6 +287,12 @@ function resolveAppRoot(explicit) {
252
287
  for (const c of candidates) {
253
288
  if (pfIsAppRoot(c)) return c
254
289
  }
290
+ // 用户可能把 appRoot 填成 .app 内部路径(/Applications/X.app/Contents/Resources)。
291
+ // 第二轮把候选归一成「客户端根」再判一次,别让一个多余的后缀把整块功能锁死。
292
+ for (const c of candidates) {
293
+ const n = normalizeAppRoot(c)
294
+ if (n && n !== c && pfIsAppRoot(n)) return n
295
+ }
255
296
  // 一个都认不出就返回空,让上层明确报错;绝不把插件自己所在的那一级当成客户端根。
256
297
  return ''
257
298
  }
@@ -269,11 +310,14 @@ function readAppMeta(appRoot) {
269
310
  const res = layout.resources || join(appRoot, 'resources')
270
311
  const plain = readJson(join(res, 'app', 'package.json'))
271
312
  if (plain) return plain
272
- const asar = join(res, 'app.asar')
273
- // Electron 主进程把 asar 当目录挂载:直接按「目录 + 内部路径」读最省事(外面普通 node 读不到就是 null,不用管)。
313
+ // 打包版:优先交给平台层按 asar 头解析(macOS 的 asar 在 Contents/Resources 下,
314
+ // 路径由 asarPath 统一算,不再各处硬拼 <root>/resources)
315
+ const viaPlatform = platformReadAppVersion(appRoot)
316
+ if (viaPlatform) return { version: viaPlatform }
317
+ const asar = asarPath(appRoot)
274
318
  const viaMount = readJson(join(asar, 'dsh', 'package.json'))
275
319
  if (viaMount) return viaMount
276
- if (!pfIsFile(asar)) return null
320
+ if (!asar || !pfIsFile(asar)) return null
277
321
  try {
278
322
  const fd = openSync(asar, 'r')
279
323
  try {
@@ -341,6 +385,9 @@ function readSettings(dshHome) {
341
385
  webdavPass: typeof raw.webdavPass === 'string' ? raw.webdavPass : '',
342
386
  // WebDAV 上存放同步包的目录(相对根,默认 dsh-config-sync)
343
387
  webdavDir: typeof raw.webdavDir === 'string' ? raw.webdavDir : '',
388
+ // 0.6.48:自定义 User-Agent。部分第三方 WebDAV 按 UA 放行/拦截,默认 undici UA 会被拒。
389
+ // 留空 = 不发 User-Agent 头(与 0.6.47 之前的行为一致)。
390
+ webdavUserAgent: typeof raw.webdavUserAgent === 'string' ? raw.webdavUserAgent : '',
344
391
  }
345
392
  }
346
393
 
@@ -371,6 +418,7 @@ function writeSettings(dshHome, s) {
371
418
  webdavUser: s.webdavUser || '',
372
419
  webdavPass: s.webdavPass || '',
373
420
  webdavDir: s.webdavDir || '',
421
+ webdavUserAgent: s.webdavUserAgent || '',
374
422
  }
375
423
  const payload = JSON.stringify(merged, null, 2) + '\n'
376
424
  // 这份文件里有 WebDAV 密码与更新令牌:POSIX 上收紧到仅本人可读写(Windows 靠用户目录 ACL,0o600 是空操作)
@@ -475,7 +523,12 @@ function resolveRepo(explicit, dshHome) {
475
523
  }
476
524
 
477
525
  const home = homedir()
478
- for (const c of ['D:\\dsh-config', 'G:\\dsh-config', 'C:\\dsh-config', join(home, 'dsh-config')]) {
526
+ // 0.6.49:自动探测的候选随平台走 —— 原来前三个是 Windows 盘符(D:/G:/C:),
527
+ // macOS 上等于扫了三个永远不存在的位置;现在 Windows 保原样,POSIX 只探自己语义下的路径。
528
+ const guesses = IS_WIN
529
+ ? ['D:\\dsh-config', 'G:\\dsh-config', 'C:\\dsh-config', join(home, 'dsh-config')]
530
+ : [defaultRepoPath(), join(home, 'Documents', 'dsh-config'), join(home, 'dsh-config')]
531
+ for (const c of guesses) {
479
532
  if (isRepoDir(c)) {
480
533
  tried.push(`自动探测:${c}`)
481
534
  return { repo: c, source: 'auto' }
@@ -705,7 +758,8 @@ function readBundles(profileDir) {
705
758
  let asarNamesCache = new Map()
706
759
  function asarBundleNames(appRoot) {
707
760
  if (!appRoot) return null
708
- const asar = join(appRoot, 'resources', 'app.asar')
761
+ const asar = asarPath(appRoot)
762
+ if (!asar) return null
709
763
  if (asarNamesCache.has(asar)) return asarNamesCache.get(asar)
710
764
  let names = null
711
765
  try {
@@ -843,7 +897,9 @@ function inspectBackup(dshHome, rootOverride) {
843
897
  entryNames = list.slice(0, 6).map((e) => e.name)
844
898
  } catch { }
845
899
  }
846
- all.push({ name, dir, at: st.mtimeMs, files: null, bytes: null, hasProfile, plugins, bundles, kind, entries, entryNames })
900
+ // at 用整型毫秒:mtimeMs 是浮点,直接进 JSON 会变成 1795845400410.4312 这种小数,
901
+ // 面板与读结果文件的地方都得再处理一次
902
+ all.push({ name, dir, at: Math.round(st.mtimeMs), files: null, bytes: null, hasProfile, plugins, bundles, kind, entries, entryNames })
847
903
  } catch { }
848
904
  }
849
905
  all.sort((a, b) => b.at - a.at)
@@ -1084,7 +1140,9 @@ async function inspect(config) {
1084
1140
 
1085
1141
  const localApp = readAppMeta(appRoot)
1086
1142
  const localVersion = typeof localApp?.version === 'string' ? localApp.version : ''
1087
- const electronVersion = readText(join(appRoot, 'version')).trim()
1143
+ // 0.6.49:Electron 版本统一交给 platform.mjs(macOS 没有 <root>/version 文件,
1144
+ // 原来读出来永远是空串,面板那一格只剩 "app 0.2.2-rc.5 /")
1145
+ const electronVersion = platformReadElectronVersion(appRoot) || readText(join(appRoot, 'version')).trim()
1088
1146
  const contract = readJson(join(repo, 'profile', 'host-contract.json'))
1089
1147
  const contractVersion = typeof contract?.appVersion === 'string' ? contract.appVersion : ''
1090
1148
 
@@ -1258,10 +1316,15 @@ async function inspect(config) {
1258
1316
  advice.push(t('待推送扫描没跑完(文件太多或超时),这次的数字可能偏小:可再刷新一次', 'The pending scan did not finish (too many files or a timeout); the count may be low — refresh again.'))
1259
1317
  } else if (local && Array.isArray(local.engineGroups)) {
1260
1318
  // 非 Windows:这句话只覆盖引擎真会同步的四组,不能写成「仓库与本机一致」
1261
- advice.push(t(
1262
- `这台机器走跨平台引擎,只同步 ${local.engineGroups.join(' / ')},这几组与仓库一致(会话记录、插件数据、额外路径要 Windows 版才会同步)`,
1263
- `This machine uses the cross-platform engine, which syncs only ${local.engineGroups.join(' / ')}; those groups match the repo (conversations, plugin data and extra paths sync on Windows).`,
1264
- ))
1319
+ advice.push(local.engineAllGroups
1320
+ ? t(
1321
+ `这台机器走跨平台引擎,${local.engineGroups.length} 组内容(${local.engineGroups.join(' / ')})都与仓库一致`,
1322
+ `This machine uses the cross-platform engine; all ${local.engineGroups.length} groups (${local.engineGroups.join(' / ')}) match the repo.`,
1323
+ )
1324
+ : t(
1325
+ `这台机器走跨平台引擎,只同步 ${local.engineGroups.join(' / ')},这几组与仓库一致(其余组要 Windows 版才会同步)`,
1326
+ `This machine uses the cross-platform engine, which syncs only ${local.engineGroups.join(' / ')}; those groups match the repo (the rest sync on Windows).`,
1327
+ ))
1265
1328
  } else {
1266
1329
  advice.push(t('仓库与本机一致,没有待办', 'The repo matches this machine — nothing to do.'))
1267
1330
  }
@@ -1362,6 +1425,9 @@ async function inspect(config) {
1362
1425
  lastCheckError: autoState.lastCheckError,
1363
1426
  drift: autoState.drift,
1364
1427
  pending: autoState.pending,
1428
+ // 0.6.49:后台自动拉取(启动时那条,没有请求也没有面板)在 macOS 上不再弹原生框,
1429
+ // 而是把这个提示挂出来,由面板的「立即拉取」接手 —— 否则对话框被窗口挡住就等于永不发生。
1430
+ pullPrompt: autoState.pullPrompt || null,
1365
1431
  watcherStartedAt: autoState.watcherStartedAt,
1366
1432
  script: autoScript(dshHome, repo),
1367
1433
  // post-exit.ps1 上次执行的结果(成功/失败/是否回滚),客户端启动后据此弹 5 秒提示
@@ -1381,7 +1447,7 @@ async function inspect(config) {
1381
1447
  // 0.4.0:跨端信息。面板据此显示「本机平台 / 仓库契约来自哪个平台 / 已登记哪些机器」。
1382
1448
  // 这里刻意不显示本机绝对路径的明文(那是本机私有),只给平台族与版本。
1383
1449
  platform: (() => {
1384
- const contract = repo ? readContract(repo) : null
1450
+ const contract = repo ? readContract(repo, process.platform) : null
1385
1451
  const local = {
1386
1452
  os: OS,
1387
1453
  osLabel: platformLabel(),
@@ -1422,6 +1488,8 @@ async function inspect(config) {
1422
1488
  url: w.url,
1423
1489
  user: w.user,
1424
1490
  dir: w.dir,
1491
+ // 0.6.48:UA(留空 = 不发 User-Agent 头)
1492
+ userAgent: w.ua,
1425
1493
  secure: isSecureUrl(w.url),
1426
1494
  }
1427
1495
  })(),
@@ -1486,14 +1554,21 @@ function sendJson(res, code, body) {
1486
1554
  } catch { /* 客户端已断开就忽略 */ }
1487
1555
  }
1488
1556
 
1489
- function readBody(req) {
1557
+ function readBody(req, maxBytes = 64 * 1024) {
1490
1558
  return new Promise((resolve, reject) => {
1491
- let data = ''
1559
+ // 用数组收块、最后再 join:反馈路由的请求体上限放宽到 160 MB,
1560
+ // 逐块 `data += c` 会在这种体量下反复复制整条字符串(O(n²)),内存也翻倍。
1561
+ const chunks = []
1562
+ let total = 0
1492
1563
  req.on('data', (c) => {
1493
- data += c
1494
- if (data.length > 64 * 1024) { reject(new Error('body too large')); req.destroy() }
1564
+ const buf = Buffer.isBuffer(c) ? c : Buffer.from(c)
1565
+ total += buf.length
1566
+ // 0.6.48:上限可放宽(反馈带附件时 base64 会超 64 KB),默认值不变,
1567
+ // 其它路由的行为一个字节都不动。
1568
+ if (total > maxBytes) { reject(new Error('body too large')); req.destroy() }
1569
+ else chunks.push(buf)
1495
1570
  })
1496
- req.on('end', () => resolve(data))
1571
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
1497
1572
  req.on('error', reject)
1498
1573
  })
1499
1574
  }
@@ -1761,13 +1836,15 @@ function shHead(title) {
1761
1836
  * 进程守护:DSH 还在跑就拒绝执行。
1762
1837
  * 用 pgrep -f 匹配客户端可执行文件;找不到 pgrep 时跳过(不假装守护成功)。
1763
1838
  */
1764
- function shProcGuard() {
1765
- const names = clientProcessNames()
1766
- const pattern = names.map((n) => n.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|')
1839
+ function shProcGuard(appRoot) {
1840
+ // 0.6.49:用**客户端可执行文件路径**匹配,不用进程名。
1841
+ // 按名字匹配会命中我们自己的 Node 执行体(它的命令行里带着 ".../DeepSeek Harness.app/..."),
1842
+ // 于是一个已经退出的场景也会被判成「还在运行」,脚本永远拒绝执行。
1843
+ const pattern = clientProcessPattern(appRoot)
1767
1844
  return [
1768
1845
  '# 先确认 DSH 已退出:运行中 capture 会读到写了一半的 cordis.patch.yml',
1769
1846
  'if command -v pgrep >/dev/null 2>&1; then',
1770
- ` if pgrep -f "${pattern}" >/dev/null 2>&1; then`,
1847
+ ` if pgrep -f ${shQuote(pattern)} >/dev/null 2>&1; then`,
1771
1848
  ' echo "[X] DSH 还在运行,请先完全退出(窗口 + 托盘)再重试。"',
1772
1849
  ' exit 1',
1773
1850
  ' fi',
@@ -1820,6 +1897,29 @@ function buildSh(config, action, repo, appRoot, dshHome, state = {}) {
1820
1897
  const note = target === 'push'
1821
1898
  ? String(state.message || '').replace(/["\r\n]/g, ' ').trim().slice(0, 120)
1822
1899
  : ''
1900
+ // 提示与 .cmd 版同语义(面板拿 payload.warnings 提示「本机领先,别点错」)。
1901
+ // 0.6.49 之前 buildSh 直接不返回这两个字段,于是 macOS 面板上永远看不到这些提醒。
1902
+ const warnings = []
1903
+ if (target === 'pull') {
1904
+ const ahead = Number(state.ahead) || 0
1905
+ const dirty = Number(state.dirty) || 0
1906
+ if (ahead > 0) {
1907
+ warnings.push(t(
1908
+ `本机领先远端 ${ahead} 个提交(还没推送),拉取后这些改动在仓库里仍然缺失`,
1909
+ `This machine is ${ahead} commit(s) ahead (not pushed yet); after pulling, those changes are still missing from the repo.`,
1910
+ ))
1911
+ }
1912
+ if (dirty > 0) {
1913
+ warnings.push(t(
1914
+ `工作区有 ${dirty} 项未提交,拉取会用仓库版本覆盖对应的本机文件`,
1915
+ `${dirty} uncommitted change(s): pulling overwrites the matching local files with the repo version.`,
1916
+ ))
1917
+ }
1918
+ warnings.push(t(
1919
+ '拉取 = 拉远端 + apply 到本机:会用仓库里的版本覆盖本机配置',
1920
+ 'Pull = fetch the remote and apply it locally: the repo version overwrites the local config.',
1921
+ ))
1922
+ }
1823
1923
 
1824
1924
  const confirmBlock = target === 'pull'
1825
1925
  ? [
@@ -1835,60 +1935,137 @@ function buildSh(config, action, repo, appRoot, dshHome, state = {}) {
1835
1935
  ]
1836
1936
  : []
1837
1937
 
1838
- const invocation = isRestore
1839
- ? buildShRestoreInvocation({ engine, nodeExe, common, state })
1840
- : [
1938
+ // 还原:生成时就挑好快照并写进脚本(与 .cmd 版同语义)。
1939
+ // 0.6.49 之前 POSIX 的还原脚本只是裸调一次 restore —— 既不显示用的是哪份快照、
1940
+ // 也不先 dry-run、更没有确认(.cmd 版三样都有);响应里也没有 backup 字段,面板拿不到快照信息。
1941
+ let backupInfo = null
1942
+ const body = []
1943
+ if (isRestore) {
1944
+ const settings = readSettings(dshHome)
1945
+ const backup = inspectBackup(dshHome, backupRootOf(dshHome, settings))
1946
+ const picked = String(state.backupDir || '')
1947
+ const pickedSnap = picked ? (backup.snapshots || []).find((sn) => sn.dir === picked) : null
1948
+ const chosen = picked || backup.latest || ''
1949
+ const kind = String(state.snapshotKind || (pickedSnap ? pickedSnap.kind : '') || '')
1950
+ const restoreState = { ...state, backupDir: chosen, snapshotKind: kind }
1951
+ backupInfo = {
1952
+ dir: chosen, root: backup.root,
1953
+ at: pickedSnap ? pickedSnap.at : backup.latestAt,
1954
+ count: backup.count, files: pickedSnap ? pickedSnap.files : backup.latestFiles,
1955
+ }
1956
+ const drySupported = engineSupportsDryRun(engine)
1957
+ const dry = drySupported
1958
+ ? buildShRestoreInvocation({ engine, nodeExe, common, state: restoreState, extra: ['-DryRun'] })
1959
+ : []
1960
+ const real = buildShRestoreInvocation({ engine, nodeExe, common, state: restoreState })
1961
+ body.push(
1962
+ chosen
1963
+ ? `echo ${shQuote(`备份快照:${chosen}`)}`
1964
+ : `echo ${shQuote(`备份快照:${backup.root}(生成脚本时这里还没有快照)`)}`,
1965
+ chosen
1966
+ ? `echo ${shQuote(`快照时间:${new Date(backupInfo.at || Date.now()).toLocaleString('zh-CN', { hour12: false })} 备份根下共 ${backup.count} 份`
1967
+ // files 可能是 null(体积/文件数不递归统计,见 inspectBackup)——别把 null 印成「含 null 个文件」
1968
+ + (typeof backupInfo.files === 'number' && Number.isFinite(backupInfo.files)
1969
+ ? `,这份含 ${backupInfo.files} 个文件` : '(文件数未统计)'))}`
1970
+ : `echo ${shQuote('执行时由 sync-engine.mjs 自动取该目录下最新一份;若那时仍为空,会提示你先跑一次拉取。')}`,
1971
+ '',
1972
+ ...(drySupported
1973
+ ? [`echo ${shQuote('[第一步] 只看不动,先打印还原计划:')}`, ...dry]
1974
+ : [`echo ${shQuote('[!] 这个执行体还不认 -DryRun(仓库里那份偏旧):跳过计划预览;先推送一次即可刷新它。')}`]),
1975
+ 'echo',
1976
+ ...restoreConfirmBlock(),
1977
+ `echo ${shQuote('[第二步] 开始还原(会先把当前 profile 另存一份再覆盖):')}`,
1978
+ ...real,
1979
+ )
1980
+ } else {
1981
+ body.push(
1982
+ ...confirmBlock,
1841
1983
  `${shQuote(nodeExe)} ${shQuote(engine)} ${target} ${common.join(' ')}` +
1842
- (note ? ` -Message ${shQuote(note)}` : ''),
1843
- ]
1984
+ (note ? ` -Message ${shQuote(note)}` : ''),
1985
+ )
1986
+ }
1844
1987
 
1988
+ const headWhat = isRestore
1989
+ ? t('把本机 profile 退回到下面这个快照(先留底、再覆盖、再核对依赖)。',
1990
+ 'Roll the local profile back to the snapshot below (copy aside, restore, then verify dependencies).')
1991
+ : `会先确认 DSH 是否已退出,再执行「${label}」。`
1845
1992
  const text = [
1846
- ...shHead(`会先确认 DSH 是否已退出,再执行「${label}」。`),
1847
- ...shProcGuard(),
1993
+ ...shHead(headWhat),
1994
+ ...shProcGuard(appRoot),
1848
1995
  ...envLines,
1849
1996
  '',
1850
- ...confirmBlock,
1851
- ...invocation,
1997
+ ...body,
1852
1998
  '',
1853
- 'echo "执行结束。若为拉取,确认无误后启动 DSH。"',
1999
+ `echo ${shQuote(isRestore ? '执行结束。确认无误后再启动 DSH。' : '执行结束。若为拉取,确认无误后启动 DSH。')}`,
1854
2000
  ].join('\n')
1855
2001
 
1856
2002
  const fileName = isRestore
1857
- ? (state.snapshotName ? `同步-还原-${state.snapshotName}.sh` : '同步-还原.sh')
2003
+ ? (pickedName(state))
1858
2004
  : `同步-${target === 'push' ? '推送' : '拉取'}.sh`
1859
2005
  const path = join(repo, fileName)
1860
2006
  writeFileSync(path, text, 'utf8')
1861
2007
  try { chmodSync(path, 0o755) } catch { /* Windows 上没意义,忽略 */ }
1862
- return {
2008
+ const result = {
1863
2009
  action: isRestore ? 'restore' : target,
1864
2010
  label: isRestore ? t('还原(本机 → 快照)', 'Restore (machine → snapshot)') : label,
1865
2011
  path,
1866
- command: invocation.join(' '),
2012
+ command: body.filter((l) => /sync-engine\.mjs/.test(l)).pop() || '',
2013
+ warnings,
2014
+ message: note,
1867
2015
  platform: 'posix',
1868
2016
  }
2017
+ if (backupInfo) result.backup = backupInfo
2018
+ return result
2019
+ }
2020
+
2021
+ /** 还原脚本文件名:面板点某一行的还原时带快照名,多份脚本互不覆盖。 */
2022
+ function pickedName(state) {
2023
+ return state.snapshotName ? `同步-还原-${state.snapshotName}.sh` : '同步-还原.sh'
1869
2024
  }
1870
2025
 
1871
2026
  /** 还原脚本的命令拼装(POSIX)。 */
1872
- function buildShRestoreInvocation({ engine, nodeExe, common, state }) {
2027
+ function buildShRestoreInvocation({ engine, nodeExe, common, state, extra = [] }) {
1873
2028
  const args = [...common]
1874
2029
  if (state.backupDir) args.push(`-BackupDir ${shQuote(state.backupDir)}`)
1875
2030
  if (state.snapshotKind && state.snapshotKind !== 'profile') {
1876
2031
  args.push(`-SnapshotKind ${shQuote(state.snapshotKind)}`)
1877
2032
  }
2033
+ args.push(...extra)
1878
2034
  return [`${shQuote(nodeExe)} ${shQuote(engine)} restore ${args.join(' ')}`]
1879
2035
  }
1880
2036
 
2037
+ /** 还原的确认守卫(POSIX):--yes 免确认,否则读一行 y。 */
2038
+ function restoreConfirmBlock() {
2039
+ return [
2040
+ 'if [ "${1:-}" = "--yes" ]; then',
2041
+ ' :',
2042
+ 'else',
2043
+ ' printf "按上面的计划执行还原?(y/N) "',
2044
+ ' read -r GO',
2045
+ ' case "$GO" in y|Y) ;; *) echo "没有收到确认(y),已退出:本机什么都没改。"; exit 0 ;; esac',
2046
+ 'fi',
2047
+ '',
2048
+ ]
2049
+ }
2050
+
1881
2051
  /**
1882
2052
  * 挑执行引擎:优先仓库里的 sync-engine.mjs(随仓库更新),
1883
2053
  * 其次插件自带的 runtime\(新机器刚装、仓库还没拉下来时)。
1884
2054
  * 找不到返回空串,调用方据此明确报错,不生成一个必然失败的脚本。
1885
2055
  */
1886
2056
  function pickEngine(repo) {
1887
- const fromRepo = join(repo, 'sync-engine.mjs')
1888
- if (isFile(fromRepo)) return fromRepo
2057
+ // 0.6.49:插件自带的执行体优先。旧顺序是仓库优先(理由:随仓库更新),但实测代价太大 ——
2058
+ // 仓库里那份可能是老版本,它不认识新参数(-DryRun 被当成未知参数忽略,还原脚本的
2059
+ // 「第一步只看不动」直接变成真还原)。插件自带的永远是「正在跑的这份代码」,其余从属。
1889
2060
  const fromPlugin = join(pluginRoot(), 'runtime', 'sync-engine.mjs')
1890
2061
  if (isFile(fromPlugin)) return fromPlugin
1891
- return ''
2062
+ const fromRepo = join(repo, 'sync-engine.mjs')
2063
+ return isFile(fromRepo) ? fromRepo : ''
2064
+ }
2065
+
2066
+ /** 执行体是否认 -DryRun(老版本的仓库执行体不认,别让「计划」变成真跑)。 */
2067
+ function engineSupportsDryRun(engine) {
2068
+ try { return readFileSync(engine, 'utf8').includes('DryRun') } catch { return false }
1892
2069
  }
1893
2070
 
1894
2071
  /* ============================ 自动同步 / 自动推送 ============================
@@ -1925,10 +2102,20 @@ const autoState = {
1925
2102
  }
1926
2103
 
1927
2104
  function autoScript(dshHome, repo) {
1928
- const fromPlugin = join(pluginRoot(), 'runtime', 'post-exit.ps1')
2105
+ // 0.6.49:执行体随平台走 —— Windows 用 post-exit.ps1,macOS / Linux 用 post-exit.mjs。
2106
+ // 原来这里只找 .ps1,于是非 Windows 上 autoScript() 恒为空,spawnWatcher 直接返回
2107
+ // 「插件与仓库里都没有 post-exit.ps1,无法排队」—— 退出后推送/拉取/还原/更新整条链路都是死的。
2108
+ const name = postExitScriptName()
2109
+ const fromPlugin = join(pluginRoot(), 'runtime', name)
1929
2110
  if (isFile(fromPlugin)) return fromPlugin
1930
- const fromRepo = join(repo || '', 'post-exit.ps1')
1931
- return isFile(fromRepo) ? fromRepo : ''
2111
+ const fromRepo = join(repo || '', name)
2112
+ if (isFile(fromRepo)) return fromRepo
2113
+ // 兼容老仓库(里面只有 .ps1):Windows 上仍能退回它,POSIX 上不能(跑不起来)
2114
+ if (IS_WIN) {
2115
+ const legacy = join(repo || '', 'post-exit.ps1')
2116
+ if (isFile(legacy)) return legacy
2117
+ }
2118
+ return ''
1932
2119
  }
1933
2120
 
1934
2121
  /**
@@ -2009,6 +2196,10 @@ async function checkDrift(repo) {
2009
2196
 
2010
2197
  /** 系统确认框(立在 DSH 窗口前面,不开面板也看得见)。Yes → true。 */
2011
2198
  function askConfirm(title, text) {
2199
+ // 0.6.49:POSIX 上用 osascript 的 display dialog。原来只会 spawn powershell.exe,
2200
+ // macOS 上 'error' 事件直接 resolve(false) —— 自动拉取的确认框永远等于「用户点了取消」,
2201
+ // 更新(apply)流程也永远走不到安装那一步。
2202
+ if (!IS_WIN) return askConfirmPosix(title, text)
2012
2203
  return new Promise((resolve) => {
2013
2204
  // 参数走 spawn 的数组形式,不经过 shell 解析,所以文本里的引号/换行不会被二次解释。
2014
2205
  const safe = (s) => String(s).replace(/'/g, "''")
@@ -2029,6 +2220,35 @@ function askConfirm(title, text) {
2029
2220
  })
2030
2221
  }
2031
2222
 
2223
+ /**
2224
+ * POSIX 版确认框:AppleScript 的 display dialog。
2225
+ * 两个按钮「取消 / 继续」,默认「继续」;回车=继续,Esc/取消=取消。
2226
+ * 脚本从 stdin 读,免得把中文与引号拼进 -e 参数时被 shell/AppleScript 二次解释。
2227
+ */
2228
+ function askConfirmPosix(title, text) {
2229
+ return new Promise((resolve) => {
2230
+ if (!isFile('/usr/bin/osascript')) { resolve(false); return }
2231
+ // AppleScript 字符串就是 "...":用 JSON.stringify 得到同样语义的转义(\" \\ \n)
2232
+ const asStr = (s) => JSON.stringify(String(s == null ? '' : s))
2233
+ const script = [
2234
+ 'try',
2235
+ ` display dialog ${asStr(text)} with title ${asStr(title)} buttons {"取消", "继续"} default button "继续" with icon caution`,
2236
+ ' return "continue"',
2237
+ 'on error number -128',
2238
+ ' return "cancel"',
2239
+ 'end try',
2240
+ ].join('\n')
2241
+ let out = ''
2242
+ const child = spawn('/usr/bin/osascript', ['-'], { stdio: ['pipe', 'pipe', 'ignore'] })
2243
+ child.on('error', () => resolve(false))
2244
+ child.stdout.on('data', (c) => { out += c })
2245
+ child.on('close', () => resolve(/continue/.test(out)))
2246
+ try { child.stdin.end(script, 'utf8') } catch { resolve(false) }
2247
+ const timer = setTimeout(() => { try { child.kill() } catch { } resolve(false) }, 12 * 60 * 1000)
2248
+ try { timer.unref?.() } catch { }
2249
+ })
2250
+ }
2251
+
2032
2252
  /**
2033
2253
  * 找 powershell 的绝对路径。
2034
2254
  * 不能只写 'powershell.exe' 靠 PATH:Electron 主进程继承的 PATH 可能被裁剪(本机实测就是
@@ -2085,11 +2305,19 @@ function psWinArg(value) {
2085
2305
  */
2086
2306
  async function spawnWatcher({ mode, repo, appRoot, dshHome, restart, extraArgs = [], closeRequested = false }) {
2087
2307
  const script = autoScript(dshHome, repo)
2088
- if (!script) return { ok: false, error: t('插件与仓库里都没有 post-exit.ps1,无法排队', 'post-exit.ps1 is in neither the plugin nor the repo — cannot queue') }
2089
-
2308
+ if (!script) {
2309
+ return { ok: false, error: t(
2310
+ `插件与仓库里都没有 ${postExitScriptName()},无法排队`,
2311
+ `${postExitScriptName()} is in neither the plugin nor the repo — cannot queue`,
2312
+ ) }
2313
+ }
2090
2314
  // 同一时刻只允许一次同步。实测过的坑:启动首检排了 push、用户在确认框点确认又排了 pull,
2091
2315
  // 两个守护都在等同一个 pid —— DSH 一退出它们**同时开工**,一次推送一次拉取并行跑、各重启一次,
2092
2316
  // 配置可能互相覆盖。锁文件记 pid,进程还活着就拒掉后来者。
2317
+ //
2318
+ // 0.6.49:这段原来只在 Windows 分支里(在 spawnWatcher 后半段),POSIX 走新分支后
2319
+ // 锁就没人写了 —— 面板显示「排队中」而磁盘上没有痕迹,两个动作同时排队也没人挡。
2320
+ // 现在两个平台共用同一套判定,放在分支之前。
2093
2321
  const lockFile = join(dshHome, 'auto-sync.lock')
2094
2322
  try {
2095
2323
  if (isFile(lockFile)) {
@@ -2103,7 +2331,7 @@ async function spawnWatcher({ mode, repo, appRoot, dshHome, restart, extraArgs =
2103
2331
  // 同一种同步已经在等,直接复用,别再加一个并行的
2104
2332
  if (lockMode === mode) return { ok: true, pid: lockPid, reused: true }
2105
2333
  // 不同的同步正在等(例如首检排了推送、用户在确认框点了拉取):用户的手动动作优先,
2106
- // 干掉那个还没开工的等待进程,改排这一次。它此时只可能在等 DSH 退出,没有副作用。
2334
+ // 干掉那个还没开工的等待进程,改排这一次。
2107
2335
  try { process.kill(lockPid) } catch { }
2108
2336
  logLaunch(dshHome, `取消上一个等待中的 ${lockMode || '同步'}(pid ${lockPid}),改排 ${mode}`)
2109
2337
  }
@@ -2112,6 +2340,35 @@ async function spawnWatcher({ mode, repo, appRoot, dshHome, restart, extraArgs =
2112
2340
  }
2113
2341
  } catch { }
2114
2342
 
2343
+ // 0.6.49:POSIX 走 Node 执行体(post-exit.mjs)。它不是「等退出→换可见窗口」两段式,
2344
+ // 自己就盯着 pid,所以这里直接 detached 起它,不必先起一个短命 launcher。
2345
+ if (!IS_WIN) {
2346
+ const nodeExe = hostNodeExe(appRoot) || process.execPath
2347
+ const args = ['-Mode', mode, '-WatchPid', String(process.pid), '-DshHome', dshHome]
2348
+ if (closeRequested) args.push('-CloseWhenIdle')
2349
+ if (repo) args.push('-RepoRoot', repo)
2350
+ if (appRoot) args.push('-AppRoot', appRoot)
2351
+ if (restart) args.push('-Restart')
2352
+ if (Array.isArray(extraArgs) && extraArgs.length) args.push(...extraArgs)
2353
+ try {
2354
+ const child = spawn(nodeExe, [script, ...args], {
2355
+ detached: true, stdio: 'ignore', windowsHide: true,
2356
+ })
2357
+ child.unref()
2358
+ } catch (error) {
2359
+ const msg = String((error && error.message) || error)
2360
+ try { unlinkSync(lockFile) } catch { }
2361
+ logLaunch(dshHome, `启动失败 ${mode} exe=${nodeExe}:${msg}`)
2362
+ return { ok: false, error: t(`拉不起 Node 执行体(${nodeExe}):${msg}`, `Cannot launch the Node runner (${nodeExe}): ${msg}`) }
2363
+ }
2364
+ autoState.watcherStartedAt = Date.now()
2365
+ try {
2366
+ writeFileSync(lockFile, JSON.stringify({ pid: process.pid, mode, at: Date.now() }), 'utf8')
2367
+ } catch { }
2368
+ logLaunch(dshHome, `已启动 ${mode}(Node 执行体 ${postExitScriptName()},等 pid ${process.pid} 退出)`)
2369
+ return { ok: true, pid: process.pid, via: 'node' }
2370
+ }
2371
+
2115
2372
  const logsDir = join(dshHome, 'logs')
2116
2373
  try { if (!existsSync(logsDir)) mkdirSync(logsDir, { recursive: true }) } catch { }
2117
2374
  const pidFile = join(logsDir, `.watch-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.pid`)
@@ -2206,11 +2463,42 @@ function electronApp() {
2206
2463
  *
2207
2464
  * 现在优先 app.quit()(走 before-quit,配置照常落盘);拿不到 electron 才退回 taskkill。
2208
2465
  */
2209
- function closeDsh() {
2466
+ function closeDsh(appRoot = '') {
2467
+ const el = electronApp()
2468
+ const quitSoft = () => {
2469
+ // Electron 主进程形态下 app.quit 最温和(有 before-quit 落盘)
2470
+ if (el) { try { el.app.quit(); return true } catch { } }
2471
+ return false
2472
+ }
2473
+
2474
+ // 0.6.49:POSIX 上没有 taskkill(原来这里 join(C:\\Windows, System32, taskkill.exe),
2475
+ // 在 macOS 上 spawn 一个不存在的可执行文件,'error' 事件没人接 —— 关不掉客户端还会掉异常)。
2476
+ if (!IS_WIN) {
2477
+ if (quitSoft()) return true
2478
+ // 交给 AppleScript 走客户端的正常退出流程(等价于用户按 ⌘Q,配置照常落盘)
2479
+ try {
2480
+ spawn('/usr/bin/osascript', ['-e', 'tell application "DeepSeek Harness" to quit'],
2481
+ { stdio: 'ignore', detached: false })
2482
+ } catch { /* 没有 osascript 时退回下面的强杀 */ }
2483
+ // 6 秒后还在就按可执行文件整族结束(用户已经点过「立即同步」,明确授权关闭)
2484
+ const timer = setTimeout(() => {
2485
+ // 按可执行文件路径精确结束:按名字会把「等客户端退出的 post-exit.mjs」一起杀掉,
2486
+ // 于是用户点完「立即拉取」反而什么都没发生。
2487
+ try {
2488
+ spawn('/usr/bin/pkill', ['-f', clientProcessPattern(appRoot || resolveAppRoot(''))], { stdio: 'ignore' })
2489
+ } catch { }
2490
+ }, 6000)
2491
+ try { timer.unref?.() } catch { }
2492
+ return true
2493
+ }
2494
+
2210
2495
  const exe = join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'taskkill.exe')
2211
2496
  const imageName = 'DeepSeek Harness.exe'
2212
2497
  const run = (args) => {
2213
- try { spawn(isFile(exe) ? exe : 'taskkill', args, { stdio: 'ignore', windowsHide: true, detached: false }) } catch { }
2498
+ try {
2499
+ const child = spawn(isFile(exe) ? exe : 'taskkill', args, { stdio: 'ignore', windowsHide: true, detached: false })
2500
+ child.on?.('error', () => { })
2501
+ } catch { }
2214
2502
  }
2215
2503
 
2216
2504
  // 先走一次「礼貌关闭」(不带 /F 只对带窗口的进程有效,会让 Electron 走正常关闭流程)。
@@ -2221,9 +2509,7 @@ function closeDsh() {
2221
2509
  const timer = setTimeout(() => { run(['/IM', imageName, '/F']) }, 3500)
2222
2510
  try { timer.unref?.() } catch { }
2223
2511
 
2224
- // Electron 主进程形态下 app.quit 更温和(有 before-quit 落盘);拿到了就先用它
2225
- const el = electronApp()
2226
- if (el) { try { setTimeout(() => { try { el.app.quit() } catch { } }, 150) } catch { } }
2512
+ quitSoft()
2227
2513
  return true
2228
2514
  }
2229
2515
 
@@ -2611,6 +2897,7 @@ function localPending(dshHome, lastSyncAt, profileName, ctx = {}) {
2611
2897
  truncated: scanned >= 20000 || Date.now() >= deadline,
2612
2898
  // 非 Windows 时只统计引擎真会同步的四组,把这件事说出来(面板会显示,不让用户以为别的组也在同步)
2613
2899
  engineGroups: ENGINE_SYNCED_GROUPS ? [...ENGINE_SYNCED_GROUPS] : null,
2900
+ engineAllGroups: ENGINE_COVERS_ALL,
2614
2901
  }
2615
2902
  }
2616
2903
 
@@ -2679,7 +2966,28 @@ async function handleSettings(req, res, config) {
2679
2966
  let repoPath = before.repoPath
2680
2967
  if (has('repoPath')) {
2681
2968
  repoPath = String(body.repoPath || '').trim().replace(/[\\/]+$/, '')
2969
+ // POSIX 用户习惯写 ~/dsh-config:这里先展开再校验,否则会被「要绝对路径」挡回去,
2970
+ // 而用户会以为插件连自己家目录都不认。
2971
+ if (repoPath === '~' || repoPath.startsWith('~/')) repoPath = join(homedir(), repoPath.slice(1)).replace(/[\\/]+$/, '')
2682
2972
  if (!repoPath) throw new Error(t('仓库路径不能为空', 'Repo path cannot be empty'))
2973
+ // 0.6.49:先按平台校验写法。踩过的坑:macOS 上把 `D:\dsh-config` 当相对路径,
2974
+ // 后续 mkdirSync 会在当前工作目录里真的建出一个叫 `D:\dsh-config` 的目录(本仓库根就留了一个);
2975
+ // 反过来 Windows 也不该接受 /Users/x/dsh-config。被拒的路径整批报错,绝不静默存成别的意思。
2976
+ const problem = repoPathProblem(repoPath)
2977
+ if (!problem.ok) {
2978
+ throw new Error(t(
2979
+ problem.reason === 'windows-shape'
2980
+ ? `仓库路径要填本机(${platformLabel()})的绝对路径,不能是 Windows 盘符写法:${repoPath}`
2981
+ : (problem.reason === 'posix-absolute'
2982
+ ? `仓库路径要填绝对路径(以 / 开头,例如 ${defaultRepoPath()}):${repoPath}`
2983
+ : `仓库路径要填本机(${platformLabel()})的绝对路径(例如 ${defaultRepoPath()}):${repoPath}`),
2984
+ problem.reason === 'windows-shape'
2985
+ ? `Repo path must be an absolute ${platformLabel()} path, not a Windows drive path: ${repoPath}`
2986
+ : (problem.reason === 'posix-absolute'
2987
+ ? `Repo path must be absolute (starting with /, e.g. ${defaultRepoPath()}): ${repoPath}`
2988
+ : `Repo path must be an absolute ${platformLabel()} path (e.g. ${defaultRepoPath()}): ${repoPath}`),
2989
+ ))
2990
+ }
2683
2991
  // 新机器上这个目录常常还不存在、或者是个空目录(等着首次拉取去初始化):都允许存。
2684
2992
  // 只有「已经有别的东西、又明显不是 dsh-config 仓库」才拒,免得住错地方把人家目录写乱。
2685
2993
  // 判据统一交给 repoPhase,跟面板、体检那边保持同一套口径;带 .git\HEAD 的目录
@@ -2873,78 +3181,91 @@ function compareVersion(a, b) {
2873
3181
  }
2874
3182
 
2875
3183
  /**
2876
- * 0.3.89:npm registry 的 tarball 地址(双源)。npm 包与 GitHub release 的 tgz 是同一份
2877
- * 发布产物(实测 sha256 完全一致),GitHub release 不通时自动从 npm 取。两个源都列:
2878
- * npmmirror 国内快、但发版后有同步窗口期会短暂 404;官方 registry 更权威、不受镜像延迟影响。
2879
- * 清单里的权威 sha256 照常校验,换源不放宽校验。
3184
+ * 0.3.89 起是「npm 双源」;0.6.47 起 npm 成为**唯一**更新源。
3185
+ *
3186
+ * 旧注释说「npm 包与 GitHub release 的 tgz 是同一份发布产物(实测 sha256 完全一致)」——
3187
+ * 这句话是错的,实测:npm pack 产物与 registry 上的 tarball 逐字节一致(sha256 相同),
3188
+ * 但与 pnpm pack 的资产**不是同一份**(打包元数据不同,sha256 不同)。
3189
+ * 于是旧实现「清单记 pnpm 的 sha256、下载走 npm 兜底」在校验那一步必然失败。
3190
+ * 0.6.47 改成单一 npm 源后,校验值取 registry 自己的 dist.integrity / dist.shasum,
3191
+ * 权威值与被校验物同源,这个错配从根上没了。
2880
3192
  */
2881
- function npmTgzUrls(version) {
3193
+ function npmTgzUrls(version, registry = DEFAULT_NPM_REGISTRY) {
2882
3194
  const v = String(version || '').replace(/[^0-9A-Za-z.+\-]/g, '')
2883
3195
  if (!v) return []
2884
- const f = `dsh-profile-config-sync-${v}.tgz`
2885
- return [
2886
- `https://registry.npmmirror.com/dsh-profile-config-sync/-/${f}`,
2887
- `https://registry.npmjs.org/dsh-profile-config-sync/-/${f}`,
2888
- ]
3196
+ return [npmUrls(registry).tarball(v)]
2889
3197
  }
2890
- // 兼容旧调用:返回首选 npm 兜底地址
2891
- function npmTgzUrl(version) {
2892
- const list = npmTgzUrls(version)
3198
+ // 兼容旧调用:返回首选 npm 地址
3199
+ function npmTgzUrl(version, registry = DEFAULT_NPM_REGISTRY) {
3200
+ const list = npmTgzUrls(version, registry)
2893
3201
  return list.length ? list[0] : ''
2894
3202
  }
2895
3203
 
2896
3204
  /**
2897
- * 清单里 tgz 可以写相对路径(releases/xxx.tgz),也可以是绝对 GitHub release 地址。
2898
- * 下载地址按"读到清单的那个源"优先,其余镜像依次兜底;末尾追加 npm 镜像作为最终兜底
2899
- * —— GitHub release 整段不通时(国内常见),仍能走 npm 把包下下来。
3205
+ * 0.6.47:下载地址只认 npm 单版本文档里给的 dist.tarball。
3206
+ * 没有它才退回按版本号拼 registry 地址(正常不会走到)。
2900
3207
  */
2901
- function resolveTgzCandidates(manifest, manifestUrl = '') {
3208
+ function resolveTgzCandidates(manifest, registry = DEFAULT_NPM_REGISTRY) {
2902
3209
  const tgz = String((manifest && manifest.tgz) || '')
2903
- const npmList = npmTgzUrls(manifest && manifest.version)
2904
- const withNpm = (list) => {
2905
- const out = list.slice()
2906
- for (const u of npmList) if (u && !out.includes(u)) out.push(u)
2907
- return out
2908
- }
2909
- // 清单没给 tgz 时,也留 npm 这两条路(有版本就能拼出 tarball)
3210
+ const npmList = npmTgzUrls(manifest && manifest.version, registry)
2910
3211
  if (!tgz) return npmList.slice()
2911
- // 清单里写了绝对地址:先照它来,末尾追加 npm 双源兜底(0.3.89 起不再直接 return)
2912
- if (/^https?:\/\//i.test(tgz)) return withNpm([tgz])
3212
+ if (/^https?:\/\//i.test(tgz)) return [tgz]
3213
+ const base = String(registry || DEFAULT_NPM_REGISTRY).replace(/\/+$/, '')
2913
3214
  const rel = tgz.replace(/^\.?\//, '')
2914
- const bases = []
2915
- const actual = String(manifestUrl || '').replace(/[^/]*$/, '')
2916
- if (actual) bases.push(actual)
2917
- for (const cand of UPDATE_MANIFEST_MIRRORS) {
2918
- const base = cand.replace(/[^/]*$/, '')
2919
- if (base && !bases.includes(base)) bases.push(base)
2920
- }
2921
- return withNpm(bases.map((base) => base + rel))
3215
+ return [`${base}/${rel}`]
2922
3216
  }
2923
3217
 
2924
- /** version.json 里的 tgz 可以写相对路径(releases/xxx.tgz),拼在仓库 raw 根上。 */
2925
- function resolveTgzUrl(manifest, manifestUrl = UPDATE_MANIFEST_URL) {
2926
- const list = resolveTgzCandidates(manifest, manifestUrl)
3218
+ /** 下载地址:优先用 registry 给的绝对地址,没有才按版本号拼。 */
3219
+ function resolveTgzUrl(manifest, registry = DEFAULT_NPM_REGISTRY) {
3220
+ const list = resolveTgzCandidates(manifest, registry)
2927
3221
  if (list.length) return list[0]
2928
3222
  // 没给 tgz 时保留原来的兜底行为(返回空串,调用方自己报错)
2929
3223
  return ''
2930
3224
  }
2931
3225
 
2932
- async function fetchManifest(url, timeoutMs = UPDATE_FETCH_TIMEOUT, headers = {}) {
3226
+ /**
3227
+ * 0.6.47:读 npm 的 dist-tags(几十字节),拿到 latest 指向的版本号。
3228
+ * 用 /-/package/<name>/dist-tags 而不是完整 packument —— 后者含全部历史版本,
3229
+ * 面板每次打开都拉一遍纯属浪费。
3230
+ */
3231
+ async function fetchNpmLatestVersion(registry = DEFAULT_NPM_REGISTRY, timeoutMs = UPDATE_FETCH_TIMEOUT) {
2933
3232
  if (typeof fetch !== 'function') throw new Error(t('当前运行环境没有 fetch,无法检查更新', 'fetch is unavailable in this runtime — cannot check for updates'))
2934
3233
  const seconds = Math.round(timeoutMs / 1000)
2935
3234
  const ctrl = typeof AbortController === 'function' ? new AbortController() : null
2936
3235
  let timedOut = false
2937
3236
  const timer = ctrl ? setTimeout(() => { timedOut = true; try { ctrl.abort() } catch { } }, timeoutMs) : null
2938
3237
  try {
2939
- const res = await fetch(url, { cache: 'no-store', headers, signal: ctrl ? ctrl.signal : undefined })
2940
- if (!res.ok) {
2941
- throw new Error(`HTTP ${res.status}${(res.status === 401 || res.status === 403 || res.status === 404) ? t('(若为私有仓库,需配置只读令牌或环境变量)', ' (if private, configure a read-only token or env var)') : ''}`)
2942
- }
3238
+ const res = await fetch(npmUrls(registry).distTags, { cache: 'no-store', signal: ctrl ? ctrl.signal : undefined })
3239
+ if (!res.ok) throw new Error(`HTTP ${res.status}`)
2943
3240
  const json = await res.json()
2944
- if (!json || !json.version) throw new Error(t('version.json 里没有 version 字段', 'version.json has no "version" field'))
3241
+ const latest = json && json.latest
3242
+ if (!latest || typeof latest !== 'string') throw new Error(t('npm 的 dist-tags 里没有 latest', 'npm dist-tags has no "latest"'))
3243
+ return String(latest)
3244
+ } catch (error) {
3245
+ if (timedOut) throw new Error(t(`超时(${seconds} 秒内没有响应)`, `timed out (no response in ${seconds}s)`))
3246
+ throw error
3247
+ } finally {
3248
+ if (timer) clearTimeout(timer)
3249
+ }
3250
+ }
3251
+
3252
+ /**
3253
+ * 0.6.47:读 npm 上某个版本的文档(2~3 KB),取 dist.tarball / dist.integrity / dist.shasum。
3254
+ * 校验值一律取 registry 自己给的 —— 权威值与被校验物同源,不会出现「清单记 A 的哈希、下载 B 的包」。
3255
+ */
3256
+ async function fetchNpmVersionDoc(version, registry = DEFAULT_NPM_REGISTRY, timeoutMs = UPDATE_FETCH_TIMEOUT) {
3257
+ if (typeof fetch !== 'function') throw new Error(t('当前运行环境没有 fetch,无法检查更新', 'fetch is unavailable in this runtime — cannot check for updates'))
3258
+ const seconds = Math.round(timeoutMs / 1000)
3259
+ const ctrl = typeof AbortController === 'function' ? new AbortController() : null
3260
+ let timedOut = false
3261
+ const timer = ctrl ? setTimeout(() => { timedOut = true; try { ctrl.abort() } catch { } }, timeoutMs) : null
3262
+ try {
3263
+ const res = await fetch(npmUrls(registry).versionDoc(version), { cache: 'no-store', signal: ctrl ? ctrl.signal : undefined })
3264
+ if (!res.ok) throw new Error(`HTTP ${res.status}`)
3265
+ const json = await res.json()
3266
+ if (!json || !json.version) throw new Error(t('npm 上没有这个版本的文档', 'npm has no document for that version'))
2945
3267
  return json
2946
3268
  } catch (error) {
2947
- // abort 的原话是 "This operation was aborted",看不出是谁的问题,换成能看懂的话
2948
3269
  if (timedOut) throw new Error(t(`超时(${seconds} 秒内没有响应)`, `timed out (no response in ${seconds}s)`))
2949
3270
  throw error
2950
3271
  } finally {
@@ -2952,6 +3273,33 @@ async function fetchManifest(url, timeoutMs = UPDATE_FETCH_TIMEOUT, headers = {}
2952
3273
  }
2953
3274
  }
2954
3275
 
3276
+ /**
3277
+ * 0.6.47:从 npm tarball 里取包内的 release-notes.json(发布说明)。
3278
+ * npm tarball 是 gzip 的 tar,只解到内存 —— 只取 release-notes.json 一个文件,
3279
+ * tar 里条目按顺序出现,release-notes.json 通常排在 package.json 之后。
3280
+ */
3281
+ function extractReleaseNotesFromTarball(buf) {
3282
+ try {
3283
+ const tar = gunzipSync(buf)
3284
+ // tar 头 512 字节一块;文件名在 0..100,size 在 124..156(八进制字符串)
3285
+ for (let off = 0; off + 512 <= tar.length; off += 512) {
3286
+ const nameRaw = tar.slice(off, off + 100)
3287
+ const zero = nameRaw.indexOf(0)
3288
+ const name = zero >= 0 ? nameRaw.slice(0, zero).toString('utf8') : nameRaw.toString('utf8')
3289
+ if (!name) continue
3290
+ const sizeRaw = tar.slice(off + 124, off + 156).toString('ascii').replace(/\0.*$/, '').trim()
3291
+ const size = parseInt(sizeRaw, 8) || 0
3292
+ const body = off + 512
3293
+ const base = name.replace(/^\.\//, '')
3294
+ if (base === 'package/release-notes.json' || base === 'release-notes.json') {
3295
+ if (size > 0 && body + size <= tar.length) return JSON.parse(tar.slice(body, body + size).toString('utf8'))
3296
+ }
3297
+ off += Math.ceil(size / 512) * 512
3298
+ }
3299
+ } catch { /* 解不出来就当没有说明文字 */ }
3300
+ return null
3301
+ }
3302
+
2955
3303
  /** 仅向直连官方域传令牌(绝不把令牌发给第三方反代 gh-proxy / ghfast)。 */
2956
3304
  function authHeadersForUrl(url, token) {
2957
3305
  try {
@@ -2994,39 +3342,13 @@ async function resolveUpdateToken(settings, customUrl = '') {
2994
3342
  }
2995
3343
 
2996
3344
  /**
2997
- * 读清单:自定义地址只用它自己;没配则按候选源依次试,第一个成功的就用。
2998
- * 有令牌时把 GitHub API 放在最前面(私有库第三方反代必 404、直连 raw 常超时,API 几百毫秒直达)。
2999
- * 全失败时把每个源各自的失败原因汇总抛出 —— 面板上一眼能看出是超时、HTTP 状态还是解析失败。
3345
+ * 0.6.47:旧的「清单」读取路径整体退休。
3346
+ *
3347
+ * 原来是「读 GitHub 仓库根的 version.json」(raw / API / gh-proxy / ghfast 依次试),
3348
+ * 现在更新检查只查 npm,GitHub 不再参与 —— fetchManifestAuto / fetchManifest 连同
3349
+ * UPDATE_MANIFEST_MIRRORS 一起删掉,避免留下「看起来还在用」的分支。
3350
+ * 保留 withAccessToken / authHeadersForUrl:下载环节还可能碰到 Gitee 私有库与 GitHub 资产的旧配置。
3000
3351
  */
3001
- async function fetchManifestAuto(targetUrl, token = '', timeoutMs = UPDATE_FETCH_TIMEOUT) {
3002
- const custom = String(targetUrl || '').trim()
3003
- const candidates = custom
3004
- ? [custom]
3005
- : (token
3006
- ? [API_MANIFEST_URL, ...UPDATE_MANIFEST_MIRRORS.filter((u) => u !== API_MANIFEST_URL)]
3007
- : UPDATE_MANIFEST_MIRRORS.slice())
3008
- const tried = []
3009
- for (const cand of candidates) {
3010
- try {
3011
- const headers = authHeadersForUrl(cand, token)
3012
- // 有令牌且走直连 GitHub 域时改用 Authorization Header,绝不把令牌拼进第三方反代 URL
3013
- const reqUrl = Object.keys(headers).length ? cand : withAccessToken(cand, token)
3014
- const manifest = await fetchManifest(reqUrl, timeoutMs, headers)
3015
- tried.push({ url: cand, ok: true })
3016
- return { manifest, url: cand, tried }
3017
- } catch (error) {
3018
- const msg = String((error && error.message) || error)
3019
- let host = cand
3020
- try { host = new URL(cand).host } catch { }
3021
- tried.push({ url: cand, host, ok: false, error: msg })
3022
- if (custom) break
3023
- }
3024
- }
3025
- const detail = tried.map((x) => `${x.host || x.url}:${x.ok ? 'ok' : x.error}`).join(';')
3026
- const error = new Error(t(`所有更新源都读不到(${detail})`, `No update source could be reached (${detail})`))
3027
- error.sources = tried
3028
- throw error
3029
- }
3030
3352
 
3031
3353
  /**
3032
3354
  * 私有仓库的 raw 链接匿名读会 403,必须换成 Gitee API 的 raw 端点再带 access_token。
@@ -3049,17 +3371,18 @@ function withAccessToken(url, token) {
3049
3371
  return target + sep + 'access_token=' + encodeURIComponent(token)
3050
3372
  }
3051
3373
 
3052
- async function checkUpdate({ force = false, url = '', token = '' } = {}) {
3053
- const custom = String(url || '').trim()
3374
+ async function checkUpdate({ force = false, registry = '', settings = {} } = {}) {
3375
+ const reg = String(registry || effectiveNpmRegistry(settings))
3054
3376
  const now = Date.now()
3055
- if (!force && updateState.requestUrl === custom && updateState.token === token && updateState.checkedAt && now - updateState.checkedAt < UPDATE_CHECK_TTL && (updateState.manifest || updateState.error)) {
3377
+ if (!force && updateState.requestUrl === reg && updateState.checkedAt && now - updateState.checkedAt < UPDATE_CHECK_TTL && (updateState.manifest || updateState.error)) {
3056
3378
  return updateState
3057
3379
  }
3058
3380
  updateState.checking = true
3059
- updateState.requestUrl = custom
3060
- updateState.token = token
3381
+ updateState.requestUrl = reg
3382
+ updateState.token = ''
3061
3383
  try {
3062
- const got = await fetchManifestAuto(custom, token)
3384
+ // 0.6.47:只查 npm。GitHub release 不再参与更新检查。
3385
+ const got = await fetchNpmLatest(reg)
3063
3386
  updateState.manifest = got.manifest
3064
3387
  updateState.url = got.url
3065
3388
  updateState.sources = got.tried
@@ -3075,25 +3398,153 @@ async function checkUpdate({ force = false, url = '', token = '' } = {}) {
3075
3398
  return updateState
3076
3399
  }
3077
3400
 
3401
+ /**
3402
+ * 0.6.47:更新检查的唯一实现 —— 读 npm。
3403
+ *
3404
+ * 流程:
3405
+ * 1) dist-tags 拿 latest 的版本号(几十字节);
3406
+ * 2) 该版本的单版本文档拿 dist.tarball / dist.integrity / dist.shasum(2~3 KB);
3407
+ * 3) 发布说明从 npm tarball 里的 package/release-notes.json 读(不解包到磁盘,只在内存里解 gzip+tar)。
3408
+ *
3409
+ * 为什么第 3 步要下整包:npm 的单版本文档里没有发布说明(那是 GitHub release 的内容,
3410
+ * 而用户明确要求更新检查不查 GitHub)。tarball 400 多 KB,只在有新版本时才读一次。
3411
+ */
3412
+ async function fetchNpmLatest(registry = DEFAULT_NPM_REGISTRY) {
3413
+ const u = npmUrls(registry)
3414
+ const tried = []
3415
+ const record = (url, ok, error) => {
3416
+ let host = url
3417
+ try { host = new URL(url).host } catch { }
3418
+ tried.push({ url, host, ok, ...(error ? { error } : {}) })
3419
+ }
3420
+ let latestVersion = ''
3421
+ try {
3422
+ latestVersion = await fetchNpmLatestVersion(registry)
3423
+ record(u.distTags, true)
3424
+ } catch (error) {
3425
+ record(u.distTags, false, String((error && error.message) || error))
3426
+ const detail = tried.map((x) => `${x.host}:${x.error}`).join(';')
3427
+ const err = new Error(t(`读不到 npm 的版本信息(${detail})`, `Cannot read the version list from npm (${detail})`))
3428
+ err.sources = tried
3429
+ throw err
3430
+ }
3431
+ if (compareVersion(latestVersion, PLUGIN_VERSION) <= 0) {
3432
+ // 本机已经是 npm 上的最新版:不必再拉版本文档,省一次请求。
3433
+ // 但下载地址要能给出来 —— 面板会显示它,也便于手工核对。
3434
+ return {
3435
+ manifest: {
3436
+ version: latestVersion, notes: '', notesEn: '', releasedAt: '',
3437
+ tgz: u.tarball(latestVersion), sha256: '', integrity: '', sha1: '', source: 'npm',
3438
+ },
3439
+ url: u.distTags,
3440
+ tried,
3441
+ }
3442
+ }
3443
+ let doc = null
3444
+ try {
3445
+ doc = await fetchNpmVersionDoc(latestVersion, registry)
3446
+ record(u.versionDoc(latestVersion), true)
3447
+ } catch (error) {
3448
+ record(u.versionDoc(latestVersion), false, String((error && error.message) || error))
3449
+ const detail = tried.map((x) => `${x.host}:${x.error}`).join(';')
3450
+ const err = new Error(t(`读不到 npm 上 ${latestVersion} 的包信息(${detail})`, `Cannot read the package info for ${latestVersion} from npm (${detail})`))
3451
+ err.sources = tried
3452
+ throw err
3453
+ }
3454
+ const dist = (doc && doc.dist) || {}
3455
+ const tarball = String(dist.tarball || '')
3456
+ const manifest = {
3457
+ version: String(doc.version || latestVersion),
3458
+ notes: '',
3459
+ notesEn: '',
3460
+ releasedAt: '',
3461
+ tgz: tarball,
3462
+ // npm 给的权威校验值:integrity 是 sha512(SRI),shasum 是 sha1。
3463
+ // 两者都取,下载时优先用 integrity(更强),退回 shasum。
3464
+ integrity: String(dist.integrity || ''),
3465
+ sha1: String(dist.shasum || ''),
3466
+ sha256: '',
3467
+ source: 'npm',
3468
+ }
3469
+ // 发布说明:下 tarball 从里面取 release-notes.json。
3470
+ // 缓存按「版本+integrity」记:同一次会话里反复点「检查更新」不该反复下 400KB。
3471
+ if (tarball) {
3472
+ const cacheKey = `${manifest.version}|${manifest.integrity}`
3473
+ const cached = notesCache.get(cacheKey)
3474
+ if (cached) {
3475
+ manifest.notes = cached.notes
3476
+ manifest.notesEn = cached.notesEn
3477
+ manifest.releasedAt = cached.releasedAt
3478
+ manifest.pkgSha256 = cached.pkgSha256
3479
+ } else {
3480
+ try {
3481
+ const buf = await fetchTarballBuffer(tarball)
3482
+ const inner = extractReleaseNotesFromTarball(buf)
3483
+ if (inner && typeof inner === 'object') {
3484
+ manifest.notes = String(inner.notes || '')
3485
+ manifest.notesEn = String(inner.notesEn || '')
3486
+ manifest.releasedAt = String(inner.releasedAt || '')
3487
+ // 包内 version.json 的 sha256 是打包时那份 tgz 的哈希,和 npm tarball 不是同一份,
3488
+ // 所以**不用**它做校验(校验用 registry 的 integrity/shasum)。
3489
+ manifest.pkgSha256 = String(inner.sha256 || '')
3490
+ }
3491
+ notesCache.set(cacheKey, {
3492
+ notes: manifest.notes, notesEn: manifest.notesEn,
3493
+ releasedAt: manifest.releasedAt, pkgSha256: manifest.pkgSha256,
3494
+ })
3495
+ } catch (error) {
3496
+ record(tarball, false, String((error && error.message) || error))
3497
+ // 取不到说明文字不算失败:版本号与下载地址已经拿到了
3498
+ }
3499
+ }
3500
+ }
3501
+ return { manifest, url: u.versionDoc(manifest.version), tried }
3502
+ }
3503
+
3504
+ /** 下载 npm tarball 到内存(只用于取包内 release-notes.json)。 */
3505
+ async function fetchTarballBuffer(url, timeoutMs = 120 * 1000) {
3506
+ if (typeof fetch !== 'function') throw new Error(t('当前运行环境没有 fetch', 'fetch is unavailable in this runtime'))
3507
+ const ctrl = typeof AbortController === 'function' ? new AbortController() : null
3508
+ const timer = ctrl ? setTimeout(() => { try { ctrl.abort() } catch { } }, timeoutMs) : null
3509
+ try {
3510
+ const res = await fetch(url, { cache: 'no-store', signal: ctrl ? ctrl.signal : undefined })
3511
+ if (!res.ok) throw new Error(`HTTP ${res.status}`)
3512
+ const buf = Buffer.from(await res.arrayBuffer())
3513
+ if (!buf.length) throw new Error(t('下载到的包是空的', 'the downloaded package is empty'))
3514
+ return buf
3515
+ } finally {
3516
+ if (timer) clearTimeout(timer)
3517
+ }
3518
+ }
3519
+
3520
+ // 发布说明缓存:key = 版本|integrity。同一次会话里反复点「检查更新」不该反复下 400KB 的包。
3521
+ const notesCache = new Map()
3522
+
3078
3523
  function updatePayload(state, settings = {}, resolvedToken = null) {
3079
3524
  const remote = state.manifest
3080
- const custom = String(settings.updateManifestUrl || '')
3081
- const resolvedUpd = resolvedToken || resolveTokenSpec(settings.updateToken, custom ? [] : GH_TOKEN_ENV_CANDIDATES)
3082
3525
  const installed = state.liveInstall || null
3526
+ const reg = effectiveNpmRegistry(settings)
3527
+ const u = npmUrls(reg)
3083
3528
  // 装好了但进程还在跑旧代码 = 需要重启;重启后 PLUGIN_VERSION 追上来,这条自然消失
3084
3529
  const restartRequired = Boolean(installed && compareVersion(installed.version, PLUGIN_VERSION) > 0)
3085
3530
  return {
3086
3531
  ok: !state.error,
3087
3532
  local: { version: PLUGIN_VERSION || t('未知', 'unknown'), dir: PLUGIN_DIR },
3088
- // 更新相关的配置集中在这里(清单地址、令牌是否已存),别散到「云端仓库」卡里
3533
+ // 更新相关的配置集中在这里。0.6.47 起更新源固定是 npm:
3534
+ // 清单地址/令牌这两项对 npm 都不再适用(npm 公开包不需要令牌,也没有可换的清单地址)。
3535
+ // registry 可被设置或环境变量覆盖(换镜像 / 夹具用本地服务器),但仍然是「只查 npm」。
3089
3536
  config: {
3090
- manifestUrl: custom || UPDATE_MANIFEST_MIRRORS[0],
3091
- manifestUrlIsDefault: !custom,
3092
- manifestSources: custom ? [] : UPDATE_MANIFEST_MIRRORS.slice(),
3093
- tokenSet: Boolean(resolvedUpd.token),
3094
- tokenSaved: Boolean(settings.updateToken && !parseEnvTokenRef(settings.updateToken)),
3095
- tokenSource: resolvedUpd.source,
3096
- tokenEnv: resolvedUpd.envName,
3537
+ source: 'npm',
3538
+ packageName: NPM_PACKAGE_NAME,
3539
+ registry: reg,
3540
+ registryIsDefault: reg === DEFAULT_NPM_REGISTRY,
3541
+ manifestUrl: u.distTags,
3542
+ manifestUrlIsDefault: true,
3543
+ manifestSources: [u.distTags],
3544
+ tokenSet: false,
3545
+ tokenSaved: false,
3546
+ tokenSource: resolvedToken && resolvedToken.source ? resolvedToken.source : '',
3547
+ tokenEnv: resolvedToken && resolvedToken.envName ? resolvedToken.envName : '',
3097
3548
  },
3098
3549
  remote: remote ? {
3099
3550
  version: String(remote.version || ''),
@@ -3101,11 +3552,14 @@ function updatePayload(state, settings = {}, resolvedToken = null) {
3101
3552
  // 清单里的说明是中英两份(notes / notesEn),由客户端按自己的语言挑
3102
3553
  notesEn: String(remote.notesEn || ''),
3103
3554
  releasedAt: String(remote.releasedAt || ''),
3104
- tgz: resolveTgzUrl(remote, state.url),
3105
- // 0.3.89:GitHub release 不通时的 npm 兜底下载地址(双源,面板显示首选),面板上单独显示一行
3106
- npmTgz: npmTgzUrl(remote.version),
3107
- npmTgzUrls: npmTgzUrls(remote.version),
3555
+ tgz: resolveTgzUrl(remote, reg),
3556
+ // npm 下载地址(单一来源,与被校验物同源)
3557
+ npmTgz: String(remote.tgz || ''),
3558
+ npmTgzUrls: remote.tgz ? [String(remote.tgz)] : [],
3108
3559
  sha256: String(remote.sha256 || ''),
3560
+ // registry 给的权威校验值
3561
+ integrity: String(remote.integrity || ''),
3562
+ sha1: String(remote.sha1 || ''),
3109
3563
  } : null,
3110
3564
  hasUpdate: remote ? compareVersion(remote.version, PLUGIN_VERSION) > 0 : false,
3111
3565
  checking: state.checking,
@@ -3122,6 +3576,11 @@ function updatePayload(state, settings = {}, resolvedToken = null) {
3122
3576
  file: String(state.prepared.file || ''),
3123
3577
  size: Number(state.prepared.size) || 0,
3124
3578
  sha256: String(state.prepared.sha256 || ''),
3579
+ // 0.6.47:记下这次是按哪个校验值过的 —— 面板/日志能看出「校验到底做了没有」
3580
+ integrity: String(state.prepared.integrity || ''),
3581
+ sha1: String(state.prepared.sha1 || ''),
3582
+ verifiedBy: String(state.prepared.verifiedBy || ''),
3583
+ verifiedAlgo: String(state.prepared.verifiedAlgo || ''),
3125
3584
  at: Number(state.prepared.at) || 0,
3126
3585
  ready: compareVersion(state.prepared.version, PLUGIN_VERSION) > 0,
3127
3586
  }
@@ -3170,12 +3629,53 @@ async function fetchGithubReleaseAsset(url, token, timeoutMs = 120 * 1000) {
3170
3629
  return Buffer.from(await assetRes.arrayBuffer())
3171
3630
  }
3172
3631
 
3173
- async function downloadPackage({ urls, sha256, version, dshHome, token = '' }) {
3632
+ /**
3633
+ * 0.6.47:校验下载到的包。
3634
+ *
3635
+ * 权威校验值取自 npm registry 自己的 dist.integrity(SRI,通常 sha512)/ dist.shasum(sha1),
3636
+ * 与被校验物同源。旧实现用 version.json 里的 sha256 —— 那是**打包时那份 tgz**的哈希,
3637
+ * 而 npm 上的 tarball 与它不是同一份字节流(npm pack 与 registry 上的 tarball 逐字节一致,
3638
+ * 但与 pnpm pack 的资产不同),所以旧校验对 npm 下载必然失败。
3639
+ *
3640
+ * 三种校验值都收:integrity 优先,其次 shasum(sha1),最后才是 sha256(兼容旧路径)。
3641
+ * 一个都没有时**不校验**(放行)—— 但要如实记下来,不能假装校验过。
3642
+ */
3643
+ function verifyDownloadedPackage(buf, { integrity = '', sha1 = '', sha256 = '' } = {}) {
3644
+ const sri = String(integrity || '').trim()
3645
+ if (sri) {
3646
+ // SRI 形如 "sha512-<base64>",可能有多条(空格分隔),任一条对上即可
3647
+ const parts = sri.split(/\s+/).filter(Boolean)
3648
+ for (const part of parts) {
3649
+ const dash = part.indexOf('-')
3650
+ if (dash <= 0) continue
3651
+ const algo = part.slice(0, dash).toLowerCase()
3652
+ const b64 = part.slice(dash + 1)
3653
+ if (!/^sha(?:256|384|512)$/.test(algo)) continue
3654
+ const digest = createHash(algo).update(buf).digest('base64')
3655
+ if (digest === b64) return { ok: true, algo, verified: 'integrity' }
3656
+ }
3657
+ return { ok: false, error: t('包的 integrity 校验不通过', 'integrity verification failed') }
3658
+ }
3659
+ const want1 = String(sha1 || '').trim().toLowerCase()
3660
+ if (want1) {
3661
+ const got = createHash('sha1').update(buf).digest('hex')
3662
+ if (got !== want1) return { ok: false, error: t(`sha1 不一致(拿到 ${got})`, `sha1 mismatch (got ${got})`) }
3663
+ return { ok: true, algo: 'sha1', verified: 'shasum' }
3664
+ }
3665
+ const want256 = String(sha256 || '').trim().toLowerCase()
3666
+ if (want256) {
3667
+ const got = createHash('sha256').update(buf).digest('hex')
3668
+ if (got !== want256) return { ok: false, error: t(`sha256 不一致(拿到 ${got})`, `sha256 mismatch (got ${got})`) }
3669
+ return { ok: true, algo: 'sha256', verified: 'sha256' }
3670
+ }
3671
+ return { ok: true, algo: '', verified: 'none' }
3672
+ }
3673
+
3674
+ async function downloadPackage({ urls, sha256, integrity = '', sha1 = '', version, dshHome, token = '' }) {
3174
3675
  if (typeof fetch !== 'function') return { ok: false, error: t('当前运行环境没有 fetch,无法下载更新包', 'fetch is unavailable in this runtime — cannot download the update package') }
3175
3676
  const dir = join(dshHome, 'update-staging')
3176
3677
  try { mkdirSync(dir, { recursive: true }) } catch { }
3177
3678
  const file = join(dir, `dsh-profile-config-sync-${version}.tgz`)
3178
- const want = String(sha256 || '').toLowerCase()
3179
3679
  const errors = []
3180
3680
  for (const rawUrl of urls) {
3181
3681
  const url = String(rawUrl || '').trim()
@@ -3200,10 +3700,11 @@ async function downloadPackage({ urls, sha256, version, dshHome, token = '' }) {
3200
3700
  buf = Buffer.from(await res.arrayBuffer())
3201
3701
  }
3202
3702
  if (!buf.length) throw new Error(t('下载到的文件是空的', 'the downloaded file is empty'))
3703
+ const verdict = verifyDownloadedPackage(buf, { integrity, sha1, sha256 })
3704
+ if (!verdict.ok) throw new Error(String(verdict.error))
3203
3705
  const hash = createHash('sha256').update(buf).digest('hex')
3204
- if (want && hash !== want) throw new Error(t(`sha256 不一致(拿到 ${hash})`, `sha256 mismatch (got ${hash})`))
3205
3706
  writeFileSync(file, buf)
3206
- return { ok: true, file, size: buf.length, sha256: hash, url }
3707
+ return { ok: true, file, size: buf.length, sha256: hash, url, verifiedBy: verdict.verified, verifiedAlgo: verdict.algo }
3207
3708
  } catch (error) {
3208
3709
  let host = url
3209
3710
  try { host = new URL(url).host } catch { }
@@ -3226,9 +3727,42 @@ async function downloadPackage({ urls, sha256, version, dshHome, token = '' }) {
3226
3727
  * 备份旧目录(<DshHome>\backups\plugin-<旧版本>-<时间戳>)、覆盖,失败就把备份拷回去。
3227
3728
  * 返回 { ok, version, backup, log, error }
3228
3729
  */
3229
- function runInstallPlugin({ version, sha256, urls, dshHome }) {
3230
- const script = join(PLUGIN_DIR, 'runtime', 'install-plugin.ps1')
3231
- if (!isFile(script)) return Promise.resolve({ ok: false, error: t('插件目录里没有 runtime\\install-plugin.ps1', 'runtime\\install-plugin.ps1 is missing from the plugin directory') })
3730
+ function runInstallPlugin({ version, sha256, integrity = '', sha1 = '', urls, dshHome }) {
3731
+ // 0.6.49:执行体随平台走。非 Windows 用 install-plugin.mjs(原来只找 .ps1,
3732
+ // 于是 macOS 上 install-live 永远返回「插件目录里没有 runtime\install-plugin.ps1」)。
3733
+ const script = IS_WIN
3734
+ ? join(PLUGIN_DIR, 'runtime', 'install-plugin.ps1')
3735
+ : join(PLUGIN_DIR, 'runtime', 'install-plugin.mjs')
3736
+ if (!isFile(script)) {
3737
+ const name = IS_WIN ? 'install-plugin.ps1' : 'install-plugin.mjs'
3738
+ return Promise.resolve({ ok: false, error: t(`插件目录里没有 runtime\\${name}`, `runtime/${name} is missing from the plugin directory`) })
3739
+ }
3740
+ const parse = (err, stdout, stderr) => {
3741
+ const text = String(stdout || '') + String(stderr || '')
3742
+ // 执行体最后一行固定是 RESULT:{json};前面是给人看的进度
3743
+ const line = text.split(/\r?\n/).filter((l) => l.startsWith('RESULT:')).pop()
3744
+ if (!line) {
3745
+ return { ok: false, error: t('安装脚本没有返回结果:', 'The installer returned no result: ') + (text.trim().slice(-400) || String((err && err.message) || '无输出')) }
3746
+ }
3747
+ try { return JSON.parse(line.slice('RESULT:'.length)) } catch { return { ok: false, error: t('安装脚本返回的结果不是合法 JSON', 'The installer result is not valid JSON') } }
3748
+ }
3749
+ if (!IS_WIN) {
3750
+ const nodeExe = hostNodeExe(resolveAppRoot('')) || process.execPath
3751
+ const args = [script,
3752
+ '-PluginDir', PLUGIN_DIR,
3753
+ '-Version', String(version || ''),
3754
+ '-Sha256', String(sha256 || ''),
3755
+ ...(integrity ? ['-Integrity', String(integrity)] : []),
3756
+ ...(sha1 ? ['-Sha1', String(sha1)] : []),
3757
+ '-TgzUrls', urls.join('|'),
3758
+ '-DshHome', dshHome,
3759
+ ]
3760
+ return new Promise((resolve) => {
3761
+ execFile(nodeExe, args, { timeout: 6 * 60 * 1000, maxBuffer: 8 * 1024 * 1024 }, (err, stdout, stderr) => {
3762
+ resolve(parse(err, stdout, stderr))
3763
+ })
3764
+ })
3765
+ }
3232
3766
  const sysRoot = process.env.SystemRoot || 'C:\\Windows'
3233
3767
  const ps = join(sysRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe')
3234
3768
  const args = [
@@ -3236,19 +3770,14 @@ function runInstallPlugin({ version, sha256, urls, dshHome }) {
3236
3770
  '-PluginDir', PLUGIN_DIR,
3237
3771
  '-Version', String(version || ''),
3238
3772
  '-Sha256', String(sha256 || ''),
3773
+ ...(integrity ? ['-Integrity', String(integrity)] : []),
3774
+ ...(sha1 ? ['-Sha1', String(sha1)] : []),
3239
3775
  '-TgzUrls', urls.join('|'),
3240
3776
  '-DshHome', dshHome,
3241
3777
  ]
3242
3778
  return new Promise((resolve) => {
3243
3779
  execFile(ps, args, { windowsHide: true, timeout: 6 * 60 * 1000, maxBuffer: 8 * 1024 * 1024 }, (err, stdout, stderr) => {
3244
- const text = String(stdout || '') + String(stderr || '')
3245
- // 脚本最后一行固定是 RESULT:{json};前面是给人看的进度
3246
- const line = text.split(/\r?\n/).filter((l) => l.startsWith('RESULT:')).pop()
3247
- if (!line) {
3248
- resolve({ ok: false, error: t('安装脚本没有返回结果:', 'The installer returned no result: ') + (text.trim().slice(-400) || String((err && err.message) || '无输出')) })
3249
- return
3250
- }
3251
- try { resolve(JSON.parse(line.slice('RESULT:'.length))) } catch { resolve({ ok: false, error: t('安装脚本返回的结果不是合法 JSON', 'The installer result is not valid JSON') }) }
3780
+ resolve(parse(err, stdout, stderr))
3252
3781
  })
3253
3782
  })
3254
3783
  }
@@ -3264,37 +3793,33 @@ function runInstallPlugin({ version, sha256, urls, dshHome }) {
3264
3793
  async function handleUpdate(req, res, config) {
3265
3794
  const dshHome = config?.dshHome || process.env.DSH_HOME || join(homedir(), '.dsh')
3266
3795
  const settings = readSettings(dshHome)
3267
- // 清单地址允许被设置覆盖:换镜像/自建仓库、或本地搭测试服务时不改动插件源码。
3268
- // 留空 = 用内置候选列表(GitHub API / gh-proxy / ghfast / raw)
3269
- const manifestUrl = String(settings.updateManifestUrl || '')
3796
+ // 0.6.47:更新源固定是 npm,没有可配置的清单地址,也不需要令牌。
3797
+ // 旧设置里的 updateManifestUrl / updateToken 保留在配置文件里不删(用户自己填的东西不该被悄悄抹掉),
3798
+ // 但更新检查不再读它们 —— 面板上那两栏也一并撤掉。
3270
3799
  try {
3271
3800
  if (req.method === 'GET') {
3272
- const resolvedUpd = await resolveUpdateToken(settings, manifestUrl)
3273
- sendJson(res, 200, updatePayload(await checkUpdate({ url: manifestUrl, token: resolvedUpd.token }), settings, resolvedUpd))
3801
+ sendJson(res, 200, updatePayload(await checkUpdate({ settings }), settings, null))
3274
3802
  return
3275
3803
  }
3276
3804
  if (req.method !== 'POST') { sendJson(res, 405, { ok: false, error: 'GET or POST only' }); return }
3277
3805
  if (!originAllowed(req)) { sendJson(res, 403, { ok: false, error: 'cross-origin request rejected' }); return }
3278
- // 先读 body 再解析令牌:读 body 之前不能有 await,否则请求流可能已经被读空/结束,
3806
+ // 先读 body 再解析:读 body 之前不能有 await,否则请求流可能已经被读空/结束,
3279
3807
  // 事件监听挂晚了就永远等不到 'end'(实测:把令牌解析提到前面会让所有 POST 一直挂住)。
3280
3808
  const raw = await readBody(req)
3281
3809
  const body = raw.trim() ? JSON.parse(raw) : {}
3282
3810
  const action = String(body.action || 'check')
3283
- const resolvedUpd = await resolveUpdateToken(settings, manifestUrl)
3284
- const updateToken = resolvedUpd.token
3285
3811
 
3286
3812
  if (action === 'check') {
3287
3813
  clearWinEnvCache()
3288
- const refreshedUpd = await resolveUpdateToken(settings, manifestUrl)
3289
- const state = await checkUpdate({ force: true, url: manifestUrl, token: refreshedUpd.token })
3290
- sendJson(res, 200, { ok: !state.error, action, ...updatePayload(state, settings, refreshedUpd) })
3814
+ const state = await checkUpdate({ force: true, settings })
3815
+ sendJson(res, 200, { ok: !state.error, action, ...updatePayload(state, settings, null) })
3291
3816
  return
3292
3817
  }
3293
3818
 
3294
3819
  // 只下载:把包落到 <DshHome>\update-staging\,校验 sha256,**不动插件目录**。
3295
3820
  // 面板点「下载更新」走这条 —— 页面不会因为插件被改写而重置。
3296
3821
  if (action === 'prepare') {
3297
- const state = await checkUpdate({ force: true, url: manifestUrl, token: updateToken })
3822
+ const state = await checkUpdate({ force: true, settings })
3298
3823
  const remote = state.manifest
3299
3824
  if (!remote) throw new Error(t(`读不到更新清单:${state.error || '未知原因'}`, `Cannot read the update manifest: ${state.error || 'unknown reason'}`))
3300
3825
  if (compareVersion(remote.version, PLUGIN_VERSION) <= 0) {
@@ -3303,12 +3828,19 @@ async function handleUpdate(req, res, config) {
3303
3828
  // 同一个版本已经下好就不重复下(DSH 一直开着时用户可能点第二次)
3304
3829
  const prev = updateState.prepared
3305
3830
  if (prev && prev.version === String(remote.version) && isFile(prev.file)) {
3306
- sendJson(res, 200, { ok: true, action, prepared: prev, ...updatePayload(state, settings, resolvedUpd) })
3831
+ sendJson(res, 200, { ok: true, action, prepared: prev, ...updatePayload(state, settings, null) })
3307
3832
  return
3308
3833
  }
3309
- const urls = resolveTgzCandidates(remote, state.url)
3310
- if (!urls.length) throw new Error(t('version.json 里没有给 tgz 下载地址', 'version.json gives no tgz download URL'))
3311
- const got = await downloadPackage({ urls, sha256: String(remote.sha256 || ''), version: String(remote.version), dshHome, token: updateToken })
3834
+ const urls = resolveTgzCandidates(remote, effectiveNpmRegistry(settings))
3835
+ if (!urls.length) throw new Error(t('npm 上没有给下载地址', 'npm gave no download URL'))
3836
+ const got = await downloadPackage({
3837
+ urls,
3838
+ integrity: String(remote.integrity || ''),
3839
+ sha1: String(remote.sha1 || ''),
3840
+ sha256: String(remote.sha256 || ''),
3841
+ version: String(remote.version),
3842
+ dshHome,
3843
+ })
3312
3844
  if (!got.ok) throw new Error(String(got.error || t('下载失败', 'download failed')))
3313
3845
  updateState.prepared = {
3314
3846
  version: String(remote.version),
@@ -3317,8 +3849,12 @@ async function handleUpdate(req, res, config) {
3317
3849
  size: got.size,
3318
3850
  at: Date.now(),
3319
3851
  url: got.url,
3852
+ verifiedBy: got.verifiedBy || '',
3853
+ verifiedAlgo: got.verifiedAlgo || '',
3854
+ integrity: String(remote.integrity || ''),
3855
+ sha1: String(remote.sha1 || ''),
3320
3856
  }
3321
- sendJson(res, 200, { ok: true, action, prepared: updateState.prepared, ...updatePayload(state, settings, resolvedUpd) })
3857
+ sendJson(res, 200, { ok: true, action, prepared: updateState.prepared, ...updatePayload(state, settings, null) })
3322
3858
  return
3323
3859
  }
3324
3860
 
@@ -3347,28 +3883,36 @@ async function handleUpdate(req, res, config) {
3347
3883
  '-UpdateTgz', prepared.file,
3348
3884
  '-UpdateVersion', String(prepared.version),
3349
3885
  '-UpdateSha256', String(prepared.sha256 || ''),
3886
+ ...(prepared.integrity ? ['-UpdateIntegrity', String(prepared.integrity)] : []),
3350
3887
  ],
3351
3888
  })
3352
3889
  if (!started.ok) throw new Error(started.error)
3353
3890
  autoState.pending = { mode: 'update', at: Date.now(), version: String(prepared.version), restart: true, watcherPid: started.pid, installFrom: prepared.file }
3354
3891
  const closed = closeDsh()
3355
3892
  autoState.pending.closeRequested = closed
3356
- sendJson(res, 200, { ok: true, action, started: true, pending: autoState.pending, closeRequested: closed, ...updatePayload(await checkUpdate({ force: false, url: manifestUrl, token: updateToken }), settings, resolvedUpd) })
3893
+ sendJson(res, 200, { ok: true, action, started: true, pending: autoState.pending, closeRequested: closed, ...updatePayload(await checkUpdate({ force: false, settings }), settings, null) })
3357
3894
  return
3358
3895
  }
3359
3896
 
3360
3897
  // 运行中直接装(不退出 DSH,**界面已不再使用**,留给 CLI/兼容):下载 → 校验 sha256 → 备份旧版 → 覆盖插件目录
3361
3898
  if (action === 'install-live') {
3362
- const state = await checkUpdate({ force: true, url: manifestUrl, token: updateToken })
3899
+ const state = await checkUpdate({ force: true, settings })
3363
3900
  const remote = state.manifest
3364
3901
  if (!remote) throw new Error(t(`读不到更新清单:${state.error || '未知原因'}`, `Cannot read the update manifest: ${state.error || 'unknown reason'}`))
3365
3902
  if (compareVersion(remote.version, PLUGIN_VERSION) <= 0) {
3366
3903
  throw new Error(t(`已经是最新版本(${PLUGIN_VERSION}),无需更新`, `Already on the latest version (${PLUGIN_VERSION}) — no update needed`))
3367
3904
  }
3368
- const urls = resolveTgzCandidates(remote, state.url)
3369
- if (!urls.length) throw new Error(t('version.json 里没有给 tgz 下载地址', 'version.json gives no tgz download URL'))
3905
+ const urls = resolveTgzCandidates(remote, effectiveNpmRegistry(settings))
3906
+ if (!urls.length) throw new Error(t('npm 上没有给下载地址', 'npm gave no download URL'))
3370
3907
  // 包只有一百多 KB,同步做完再回包:前端把按钮置灰等这一下就够了
3371
- const report = await runInstallPlugin({ version: String(remote.version), sha256: String(remote.sha256 || ''), urls, dshHome })
3908
+ const report = await runInstallPlugin({
3909
+ version: String(remote.version),
3910
+ sha256: String(remote.sha256 || ''),
3911
+ integrity: String(remote.integrity || ''),
3912
+ sha1: String(remote.sha1 || ''),
3913
+ urls,
3914
+ dshHome,
3915
+ })
3372
3916
  if (!report.ok) throw new Error(String(report.error || t('安装失败', 'install failed')))
3373
3917
  updateState.liveInstall = {
3374
3918
  version: String(remote.version),
@@ -3378,7 +3922,7 @@ async function handleUpdate(req, res, config) {
3378
3922
  }
3379
3923
  // 注意 hasUpdate 仍是 true:进程里跑的还是旧代码,重启后 PLUGIN_VERSION 才追上来。
3380
3924
  // 面板靠 restartRequired 换成「已装好,重启生效」
3381
- sendJson(res, 200, { ok: true, action, installed: updateState.liveInstall, ...updatePayload(state, settings, resolvedUpd) })
3925
+ sendJson(res, 200, { ok: true, action, installed: updateState.liveInstall, ...updatePayload(state, settings, null) })
3382
3926
  return
3383
3927
  }
3384
3928
 
@@ -3396,14 +3940,14 @@ async function handleUpdate(req, res, config) {
3396
3940
  }
3397
3941
 
3398
3942
  if (action === 'apply') {
3399
- const state = await checkUpdate({ force: true, url: manifestUrl, token: updateToken })
3943
+ const state = await checkUpdate({ force: true, settings })
3400
3944
  const remote = state.manifest
3401
3945
  if (!remote) throw new Error(t(`读不到更新清单:${state.error || '未知原因'}`, `Cannot read the update manifest: ${state.error || 'unknown reason'}`))
3402
3946
  if (compareVersion(remote.version, PLUGIN_VERSION) <= 0) {
3403
3947
  throw new Error(t(`已经是最新版本(${PLUGIN_VERSION}),无需更新`, `Already on the latest version (${PLUGIN_VERSION}) — no update needed`))
3404
3948
  }
3405
- const tgz = resolveTgzUrl(remote, state.url)
3406
- if (!tgz) throw new Error(t('version.json 里没有给 tgz 下载地址', 'version.json gives no tgz download URL'))
3949
+ const tgz = resolveTgzUrl(remote, effectiveNpmRegistry(settings))
3950
+ if (!tgz) throw new Error(t('npm 上没有给下载地址', 'npm gave no download URL'))
3407
3951
  const notes = String((langStore.getStore() === 'en' ? (remote.notesEn || remote.notes) : remote.notes) || '').trim()
3408
3952
  const yes = await askConfirm(
3409
3953
  t('更新「配置备份与同步」插件', 'Update the Config Backup & Sync plugin'),
@@ -3416,7 +3960,7 @@ async function handleUpdate(req, res, config) {
3416
3960
  + '\n\nSteps: exit DSH → download and verify the package → back up the old version → install over it → relaunch automatically.',
3417
3961
  ),
3418
3962
  )
3419
- if (!yes) { sendJson(res, 200, { ok: true, action, cancelled: true, ...updatePayload(state, settings, resolvedUpd) }); return }
3963
+ if (!yes) { sendJson(res, 200, { ok: true, action, cancelled: true, ...updatePayload(state, settings, null) }); return }
3420
3964
 
3421
3965
  const repo = resolveRepo(config?.repoPath, dshHome).repo || ''
3422
3966
  const appRoot = resolveAppRoot(config?.appRoot) || ''
@@ -3432,7 +3976,8 @@ async function handleUpdate(req, res, config) {
3432
3976
  '-UpdateVersion', String(remote.version),
3433
3977
  '-UpdateTgz', tgz,
3434
3978
  '-UpdateSha256', String(remote.sha256 || ''),
3435
- ...(updateToken ? ['-UpdateToken', updateToken] : []),
3979
+ ...(remote.integrity ? ['-UpdateIntegrity', String(remote.integrity)] : []),
3980
+ ...(remote.sha1 ? ['-UpdateSha1', String(remote.sha1)] : []),
3436
3981
  ],
3437
3982
  })
3438
3983
  if (!started.ok) throw new Error(started.error)
@@ -3539,7 +4084,9 @@ function countEntries(dir) {
3539
4084
  * profile(4 个文件)/ prompt / skills / presets —— 别的组在那台机器上根本不会被同步。
3540
4085
  * null 表示「全部组」,非 Windows 时是白名单。
3541
4086
  */
3542
- const ENGINE_SYNCED_GROUPS = IS_WIN ? null : new Set(['profile', 'prompt', 'skills', 'presets'])
4087
+ const ENGINE_SYNCED_GROUPS = IS_WIN ? null : new Set(['profile', 'prompt', 'skills', 'presets', 'storages-record', 'settings', 'mnemon', 'local-plugins', 'plugin-data', 'extra', 'workspace', 'conversations'])
4088
+ /** 引擎是否已覆盖全部内容分组('other' 是兜底桶,不算)。0.6.49 起非 Windows 是全 12 组。 */
4089
+ const ENGINE_COVERS_ALL = !ENGINE_SYNCED_GROUPS || Object.keys(PENDING_GROUP_LABEL).filter((id) => id !== 'other').every((id) => ENGINE_SYNCED_GROUPS.has(id))
3543
4090
 
3544
4091
  /** profile 目录:优先 desktop,其次 profiles 下唯一的那一个 */
3545
4092
  function resolveProfileDir(dshHome) {
@@ -3593,25 +4140,6 @@ function listLocalPlugins(dshHome) {
3593
4140
  * 与 runtime\dsh-sync-common.ps1 的默认值必须一致,否则面板说"会同步"、capture 却跳过。
3594
4141
  */
3595
4142
  const ROUTE_EXTRA_CONFIG = '/config-sync/extra-config'
3596
- const EXTRA_CONFIG_NAME = 'config-sync-extra.json'
3597
- /** GitHub 单文件硬上限 100MB,超过必被拒收,所以配置里调多大都按这个封顶。 */
3598
- const EXTRA_HARD_MAX_BYTES = 104857600
3599
- const EXTRA_DEFAULT_SKIP_DIRS = [
3600
- 'profiles', 'skills', '.agent-presets', 'storages', 'sessions', 'attachments', 'logs', 'backups',
3601
- 'update-staging', 'electron', 'dsh-runtimes', 'dsh-market', '.dsh-plugin-market', 'dsh-session-manager',
3602
- 'browser-profiles', 'im', 'node_modules',
3603
- ]
3604
- const EXTRA_DEFAULT_EXCLUDE = [
3605
- '*.db', '*.db-*', '*.db3', '*.sqlite', '*.sqlite3', '*.sqlite-*', '*.db-shm', '*.db-wal',
3606
- '*.node', '*.exe', '*.dll', '*.asar', '*.pak', '*.bin', '*.iso', '*.img',
3607
- '*.zip', '*.7z', '*.rar', '*.tar', '*.gz', '*.tgz', '*.mp4', '*.mkv', '*.avi',
3608
- '*.log', '*.log.*', '*.tmp', '*.bak', '*.bak-*', '*.old', '*.orig', '*.swp',
3609
- '*.env', '.env*', 'config-sync-gh.json', 'config-sync-feedback-outbox.json', 'dsh-config-sync.json', 'dsh-ssh-master.key',
3610
- 'api-key', '*.pem', '*.key', '*.p12', '*.pfx', '*.crt',
3611
- '*cache*', '*token*', '*secret*', '*credential*', '*password*', '*vault*',
3612
- 'browser-profiles', 'User Data', 'Login Data', 'Cookies', 'Web Data', 'Local State',
3613
- 'node_modules', '.git', '.cache', '__pycache__', '.venv',
3614
- ]
3615
4143
 
3616
4144
  /**
3617
4145
  * 安全必需项:用户自己的 config-sync-extra.json 不允许把它们去掉。
@@ -3623,8 +4151,6 @@ const EXTRA_DEFAULT_EXCLUDE = [
3623
4151
  * 于是待推送会把 browser-profiles 里几千个文件的 mtime 变动算成「待推送」,而 capture 根本不会抓它们
3624
4152
  * —— 面板永远消不掉,退出自动推送也每次白跑。
3625
4153
  */
3626
- const EXTRA_MANDATORY_SKIP_DIRS = ['browser-profiles']
3627
- const EXTRA_MANDATORY_EXCLUDES = ['browser-profiles', 'User Data', 'Login Data', 'Cookies', 'Web Data', 'Local State']
3628
4154
 
3629
4155
  /**
3630
4156
  * 浏览器剖面 / 凭据库的路径段黑名单:与 PS 的 $SyncBlockedProfileSegments、webdav.mjs 的
@@ -3641,14 +4167,6 @@ const BLOCKED_PROFILE_SEGMENTS = new Set([
3641
4167
  * 读配置要用、保存前也要用:POST 拿用户提交的名单覆盖掉之后,
3642
4168
  * 如果只在读的时候补,用户一保存就又把它删掉了(实测就是这样丢的)。
3643
4169
  */
3644
- function topUpExtraMandatory(cfg) {
3645
- if (!cfg || !cfg.pluginData) return { skipDirs: [], exclude: [] }
3646
- const addedSkip = EXTRA_MANDATORY_SKIP_DIRS.filter((x) => !(cfg.pluginData.skipDirs || []).includes(x))
3647
- const addedExcl = EXTRA_MANDATORY_EXCLUDES.filter((x) => !(cfg.pluginData.exclude || []).includes(x))
3648
- if (addedSkip.length) cfg.pluginData.skipDirs = [...(cfg.pluginData.skipDirs || []), ...addedSkip]
3649
- if (addedExcl.length) cfg.pluginData.exclude = [...(cfg.pluginData.exclude || []), ...addedExcl]
3650
- return { skipDirs: addedSkip, exclude: addedExcl }
3651
- }
3652
4170
 
3653
4171
  function isBlockedProfilePath(rel) {
3654
4172
  const s = String(rel || '')
@@ -3664,71 +4182,10 @@ function isBlockedProfilePath(rel) {
3664
4182
  * 以前 JS 只写了 4 条,capture 却抓 14 条:面板少列了 10 个文件,用户既看不到也勾不掉它们。
3665
4183
  * 每条 { id, rel }:rel 是相对 <DshHome> 的路径;profileRel 表示相对 profile 目录。
3666
4184
  */
3667
- const SYNC_SETTINGS_SOURCES = [
3668
- { id: 'our-free-model.json', rel: ['our-free-model', 'settings.json'] },
3669
- { id: 'comfyui-workflows.json', rel: ['data', 'dsh-comfyui', 'workflows.json'] },
3670
- { id: 'dsh-pet-main-config.jsonc', rel: ['dsh-pet', 'main-config.jsonc'] },
3671
- { id: 'dsh-market-state.json', profileRel: ['.dsh-market', 'state.json'] },
3672
- { id: 'dsh-pet-memory.json', rel: ['dsh-pet', 'memory.json'] },
3673
- { id: 'our-free-model-picks.json', rel: ['our-free-model', 'picks.json'] },
3674
- { id: 'dsh-im-interface-language.json', rel: ['integrations', 'dsh-im', 'interface-language.json'] },
3675
- { id: 'dsh-qq-config.json', rel: ['integrations', 'dsh-qq', 'config.json'] },
3676
- { id: 'dsh-qq-workspaces.json', rel: ['integrations', 'dsh-qq', 'workspaces.json'] },
3677
- { id: 'redteam-preset-declare.json', rel: ['redteam', 'preset-declare.json'] },
3678
- { id: 'task-board-ledger.json', rel: ['task-board', 'ledger-v2.json'] },
3679
- { id: 'task-board-scheduler.json', rel: ['task-board', 'scheduler-v2.json'] },
3680
- { id: 'dsh-workspaces.json', rel: ['storages', 'workspace.json'] },
3681
- { id: 'workspace-archives.json', rel: ['dsh-session-manager', 'workspace-archives.v1.json'] },
3682
- ]
4185
+ const SYNC_SETTINGS_SOURCES = SETTINGS_SOURCES
3683
4186
 
3684
- function settingsSourcePath(dshHome, profileDir, entry) {
3685
- return entry.profileRel ? join(profileDir, ...entry.profileRel) : join(dshHome, ...entry.rel)
3686
- }
4187
+ const settingsSourcePath = settingsSourcePathOf
3687
4188
 
3688
- function extraConfigPath(dshHome) { return join(dshHome, EXTRA_CONFIG_NAME) }
3689
-
3690
- function readExtraConfig(dshHome) {
3691
- const cfg = {
3692
- version: 1,
3693
- pluginData: {
3694
- enabled: true,
3695
- maxFileBytes: EXTRA_HARD_MAX_BYTES,
3696
- exclude: [...EXTRA_DEFAULT_EXCLUDE],
3697
- skipDirs: [...EXTRA_DEFAULT_SKIP_DIRS],
3698
- },
3699
- extra: { enabled: true, paths: [] },
3700
- }
3701
- const p = extraConfigPath(dshHome)
3702
- if (!isFile(p)) return cfg
3703
- try {
3704
- const j = JSON.parse(readFileSync(p, 'utf8'))
3705
- const pd = j?.pluginData
3706
- if (pd) {
3707
- if (pd.enabled === false) cfg.pluginData.enabled = false
3708
- const n = Number(pd.maxFileBytes)
3709
- if (Number.isFinite(n) && n > 0) cfg.pluginData.maxFileBytes = Math.min(Math.floor(n), EXTRA_HARD_MAX_BYTES)
3710
- // 排除名单整份替换:用户在面板里删掉一条就真的不再排除
3711
- if (Array.isArray(pd.exclude)) cfg.pluginData.exclude = pd.exclude.filter((x) => typeof x === 'string' && x)
3712
- if (Array.isArray(pd.skipDirs)) cfg.pluginData.skipDirs = pd.skipDirs.filter((x) => typeof x === 'string' && x)
3713
- }
3714
- const ex = j?.extra
3715
- if (ex) {
3716
- if (ex.enabled === false) cfg.extra.enabled = false
3717
- if (Array.isArray(ex.paths)) {
3718
- cfg.extra.paths = ex.paths
3719
- .filter((x) => x && typeof x.id === 'string' && typeof x.src === 'string' && x.id && x.src)
3720
- .map((x) => ({ id: x.id, src: x.src, label: typeof x.label === 'string' && x.label ? x.label : x.id }))
3721
- }
3722
- }
3723
- } catch { /* 坏了就按默认规则走,不让面板整页读不出来 */ }
3724
- // 安全必需项补齐(与 PowerShell 的 Get-SyncExtraConfig 同一步):用户文件可以改别的,
3725
- // 但这些名字必须留着。补齐了要能让面板说出来(missingMandatory),不静默改用户的口径。
3726
- const added = topUpExtraMandatory(cfg)
3727
- if (added.skipDirs.length || added.exclude.length) {
3728
- cfg.pluginData.missingMandatory = { skipDirs: added.skipDirs, exclude: added.exclude }
3729
- }
3730
- return cfg
3731
- }
3732
4189
 
3733
4190
  function saveExtraConfig(dshHome, cfg) {
3734
4191
  const p = extraConfigPath(dshHome)
@@ -3749,25 +4206,6 @@ function saveExtraConfig(dshHome, cfg) {
3749
4206
  return p
3750
4207
  }
3751
4208
 
3752
- function wildcardToRegex(pat) {
3753
- const esc = String(pat).replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.')
3754
- return new RegExp(`^${esc}$`, 'i')
3755
- }
3756
-
3757
- /** 返回跳过原因('' = 允许同步),与 runtime 的 Test-SyncExtraSkip 判定一致。 */
3758
- function extraSkipReason(relName, size, cfg) {
3759
- const max = Math.min(cfg.pluginData.maxFileBytes || EXTRA_HARD_MAX_BYTES, EXTRA_HARD_MAX_BYTES)
3760
- if (size > max) return 'too-big'
3761
- if (!relName) return ''
3762
- const parts = String(relName).split(/[\\/]+/).filter((x) => x)
3763
- const name = parts.length ? parts[parts.length - 1] : relName
3764
- for (const pat of cfg.pluginData.exclude || []) {
3765
- const re = wildcardToRegex(pat)
3766
- if (re.test(name)) return 'excluded'
3767
- for (const seg of parts) if (re.test(seg)) return 'excluded'
3768
- }
3769
- return ''
3770
- }
3771
4209
 
3772
4210
  function dirHasRules(cfg) { return (cfg.pluginData.exclude || []).map(wildcardToRegex) }
3773
4211
 
@@ -3928,8 +4366,12 @@ async function handleScope(req, res, config) {
3928
4366
  desc: t(g.descZh, g.descEn),
3929
4367
  enabled: g.enabled,
3930
4368
  required: g.required === true,
4369
+ // 0.6.49:这台机器上的引擎会不会真的同步这一组。非 Windows 只有四组(ENGINE_SYNCED_GROUPS),
4370
+ // 面板据此把其余组标成「此平台暂不支持」并禁用勾选 —— 让人勾上却永远不生效,比不给勾更糟。
4371
+ supported: ENGINE_SYNCED_GROUPS ? ENGINE_SYNCED_GROUPS.has(g.id) : true,
3931
4372
  items: g.items.map((it) => ({ id: it.id, label: it.label, enabled: it.enabled, excludable: it.excludable !== false })),
3932
4373
  })),
4374
+ engineGroups: ENGINE_SYNCED_GROUPS ? [...ENGINE_SYNCED_GROUPS] : null,
3933
4375
  })
3934
4376
  return
3935
4377
  }
@@ -4530,6 +4972,7 @@ async function handleAuto(req, res, config) {
4530
4972
  autoState.checking = false
4531
4973
  autoState.lastCheckAt = Date.now()
4532
4974
  autoState.drift = drift
4975
+ if (!drift || !(drift.behind > 0)) autoState.pullPrompt = null
4533
4976
  sendJson(res, 200, { ok: true, action, drift, error: autoState.lastCheckError || null })
4534
4977
  return
4535
4978
  }
@@ -4590,6 +5033,7 @@ async function handleAuto(req, res, config) {
4590
5033
  const started = await spawnWatcher({ mode, repo, appRoot, dshHome, restart, closeRequested: closeNow })
4591
5034
  if (!started.ok) throw new Error(started.error)
4592
5035
  autoState.pending = { mode, at: Date.now(), restart, watcherPid: started.pid, closeRequested: false }
5036
+ autoState.pullPrompt = null
4593
5037
  // 用户明确要求"现在就同步":排队后请求客户端退出(不带 /F,走正常关闭,配置能存下来)
4594
5038
  let closed = false
4595
5039
  if (body.closeNow !== false) {
@@ -4647,20 +5091,35 @@ function scheduleAutoStart(config) {
4647
5091
  }
4648
5092
  }
4649
5093
  autoState.drift = drift
5094
+ if (!drift || !(drift.behind > 0)) autoState.pullPrompt = null
4650
5095
  const appRoot = resolveAppRoot(config?.appRoot) || ''
4651
5096
 
4652
5097
  if (settings.autoPull && drift.behind > 0) {
4653
- const yes = await askConfirm(
4654
- t('云端有更新,要同步到本机吗?', 'The cloud has new commits — sync them to this machine?'),
4655
- t(
4656
- `云端比本机多 ${drift.behind} 个提交。\n`
4657
- + '同步需要先完全退出 DSH:确认后客户端会自动关闭,拉取完成后按设置自动重新打开。\n'
4658
- + `(本机领先 ${drift.ahead} 个提交,拉取不会动它们)`,
4659
- `The cloud is ${drift.behind} commit(s) ahead of this machine.\n`
4660
- + 'Syncing requires DSH to fully exit first: after you confirm, the client closes itself and reopens according to your settings once the pull finishes.\n'
4661
- + `(This machine is ${drift.ahead} commit(s) ahead — pulling leaves those alone.)`,
4662
- ),
5098
+ const title = t('云端有更新,要同步到本机吗?', 'The cloud has new commits — sync them to this machine?')
5099
+ const text = t(
5100
+ `云端比本机多 ${drift.behind} 个提交。\n`
5101
+ + '同步需要先完全退出 DSH:确认后客户端会自动关闭,拉取完成后按设置自动重新打开。\n'
5102
+ + `(本机领先 ${drift.ahead} 个提交,拉取不会动它们)`,
5103
+ `The cloud is ${drift.behind} commit(s) ahead of this machine.\n`
5104
+ + 'Syncing requires DSH to fully exit first: after you confirm, the client closes itself and reopens according to your settings once the pull finishes.\n'
5105
+ + `(This machine is ${drift.ahead} commit(s) ahead — pulling leaves those alone.)`,
4663
5106
  )
5107
+ // 0.6.49:启动时的自动拉取不再在 macOS 上弹原生框。这条路径是**没有请求、没有面板**的
5108
+ // 后台流程,osascript 的 display dialog 往往落在应用窗口后面甚至不出现在前台 —— 用户看
5109
+ // 不见就等于「自动拉取从来不会发生」,而 DSH 还以为在等确认(12 分钟超时)。
5110
+ // 现在改成把提示挂进状态,面板的「不一致 · 立即拉取」一键接手;Windows 保持原样。
5111
+ let yes = false
5112
+ if (IS_WIN) {
5113
+ yes = await askConfirm(title, text)
5114
+ } else {
5115
+ autoState.pullPrompt = { behind: drift.behind, ahead: drift.ahead, at: Date.now(), title, message: text }
5116
+ try {
5117
+ const logDir = join(dshHome, 'logs')
5118
+ mkdirSync(logDir, { recursive: true })
5119
+ writeFileSync(join(logDir, 'auto-sync-pull-prompt.log'),
5120
+ `[${new Date().toISOString()}] 云端领先 ${drift.behind} 个提交:等用户在面板里点「立即拉取」\n`, { flag: 'a' })
5121
+ } catch { }
5122
+ }
4664
5123
  if (yes) {
4665
5124
  // 用户点了确认,插件随后自己关客户端 → 允许守护进程在窗口消失后清残留
4666
5125
  const started = await spawnWatcher({ mode: 'pull', repo, appRoot, dshHome, restart: settings.autoRestart, closeRequested: true })
@@ -5106,6 +5565,9 @@ async function handleWebdav(req, res, config) {
5106
5565
  user: w.user,
5107
5566
  dir: w.dir,
5108
5567
  mode: w.mode,
5568
+ // 0.6.48:UA 回显(面板要能确认「发出去的到底是什么」),留空表示不发 User-Agent
5569
+ userAgent: w.ua,
5570
+ userAgentSanitized: Boolean(String(settings.webdavUserAgent || '').trim()) && !w.ua,
5109
5571
  secure: isSecureUrl(w.url),
5110
5572
  probe,
5111
5573
  platform: OS,
@@ -5122,13 +5584,26 @@ async function handleWebdav(req, res, config) {
5122
5584
 
5123
5585
  // save:只更新给出的字段;密码留空表示「不改」(避免面板回显后把密码清空)
5124
5586
  if (action === 'save') {
5125
- const next = { ...settings }
5126
- if (typeof body.url === 'string') next.webdavUrl = body.url.trim()
5127
- if (typeof body.user === 'string') next.webdavUser = body.user.trim()
5128
- if (typeof body.dir === 'string') next.webdavDir = body.dir.trim()
5129
- if (typeof body.mode === 'string' && ['git', 'webdav', 'auto'].includes(body.mode)) next.syncMode = body.mode
5130
- if (typeof body.pass === 'string' && body.pass.length > 0) next.webdavPass = body.pass
5131
5587
  try {
5588
+ const next = { ...settings }
5589
+ if (typeof body.url === 'string') next.webdavUrl = body.url.trim()
5590
+ if (typeof body.user === 'string') next.webdavUser = body.user.trim()
5591
+ if (typeof body.dir === 'string') next.webdavDir = body.dir.trim()
5592
+ if (typeof body.mode === 'string' && ['git', 'webdav', 'auto'].includes(body.mode)) next.syncMode = body.mode
5593
+ if (typeof body.pass === 'string' && body.pass.length > 0) next.webdavPass = body.pass
5594
+ // 0.6.48:UA。非法值(含 CRLF / 非 ASCII / 超长)不静默存:明确报错,
5595
+ // 否则用户以为填上了,实际发出去的还是默认 UA,症状又变成「连不上」。
5596
+ if (typeof body.userAgent === 'string') {
5597
+ const raw = body.userAgent.trim()
5598
+ const safe = sanitizeUserAgent(raw)
5599
+ if (raw && !safe) {
5600
+ throw new Error(t(
5601
+ 'User-Agent 只能是一行可见 ASCII(不含换行、中文、制表符),且不超过 200 字符',
5602
+ 'User-Agent must be a single line of visible ASCII (no newlines, CJK or tabs), at most 200 characters',
5603
+ ))
5604
+ }
5605
+ next.webdavUserAgent = safe
5606
+ }
5132
5607
  writeSettings(dshHome, next)
5133
5608
  clearWebdavProbeCache()
5134
5609
  const w = normalizeWebdav(next)
@@ -5184,7 +5659,17 @@ async function handleWebdav(req, res, config) {
5184
5659
 
5185
5660
  if (action === 'upload') {
5186
5661
  const r = await uploadRepo(w, repo)
5187
- sendJson(res, 200, { ok: r.ok, uploaded: r.uploaded.length, skipped: r.skipped.length, errors: r.errors.slice(0, 20) })
5662
+ // 顺手清掉老版本推上去的浏览器剖面(Login Data / Cookies 不该待在云端)
5663
+ const purge = await purgeForbiddenFromCloud(w)
5664
+ const lockPurge = await purgeStaleLocksFromCloud(w)
5665
+ sendJson(res, 200, {
5666
+ ok: r.ok,
5667
+ uploaded: r.uploaded.length,
5668
+ skipped: r.skipped.length,
5669
+ purged: purge.deleted.length,
5670
+ purgedLocks: lockPurge.deleted.length,
5671
+ errors: r.errors.slice(0, 20),
5672
+ })
5188
5673
  return
5189
5674
  }
5190
5675
  if (action === 'download') {
@@ -5658,11 +6143,174 @@ function issueBodyOf(text, config) {
5658
6143
  return `${String(text || '').trim()}\n\n---\n### 环境 / Environment\n${env}\n`
5659
6144
  }
5660
6145
 
5661
- async function createIssue(repo, token, title, text, config) {
6146
+ /* ---------- 0.6.48:反馈附件(图片 / 视频) ----------
6147
+ * 起因(issue #9):面板只能打字,截图与录屏没法带上来 —— 而这两样恰恰是
6148
+ * 「界面显示不对」「同步报错」类反馈里最关键的证据。
6149
+ *
6150
+ * 做法:走 GitHub 自己的 release asset 上传接口,不借道第三方图床。
6151
+ * 1) 找一个用来挂附件的 release(见 feedbackAssetRelease):没有就建一个
6152
+ * 名为 `feedback-assets` 的草稿 release(draft,标签页看不见,只有
6153
+ * 知道链接的人才打得到 —— 反馈附件本来就不该公开发布);
6154
+ * 2) POST 到该 release 的 `upload_url`(形如
6155
+ * https://uploads.github.com/repos/<o>/<r>/releases/<id>/assets{?name,label}),
6156
+ * body 是原始字节,Content-Type 是真实类型,`?name=` 给出文件名;
6157
+ * 3) 把返回的 `browser_download_url` 按 Markdown 图片 / 普通链接插进正文。
6158
+ *
6159
+ * 为什么要自己找 release:Issue 本身没有附件接口,只有 release 才有。
6160
+ * 而附件存成 release asset 的好处是:链接永久有效、换机器与别人看都能打开,
6161
+ * 且不依赖你本机的文件还在不在。
6162
+ *
6163
+ * 边界:
6164
+ * - 单文件 20 MB、最多 4 个(GitHub 单 asset 上限 2 GB,这里收紧是为了面板不卡);
6165
+ * - 白名单类型:PNG / JPEG / GIF / WebP / MP4 / MOV / WebM / 文本日志;
6166
+ * 其它一律拒(可执行文件、压缩包不进资产);
6167
+ * - 没有令牌时退回「浏览器预填页面」,并明确告知附件没上传,
6168
+ * 提示用户手动拖进网页 —— 不静默丢弃。
6169
+ */
6170
+ const FEEDBACK_MAX_ATTACH_BYTES = 20 * 1024 * 1024
6171
+ const FEEDBACK_MAX_ATTACH_COUNT = 4
6172
+ const FEEDBACK_ATTACH_MIME = {
6173
+ png: 'image/png',
6174
+ jpg: 'image/jpeg',
6175
+ jpeg: 'image/jpeg',
6176
+ gif: 'image/gif',
6177
+ webp: 'image/webp',
6178
+ bmp: 'image/bmp',
6179
+ svg: 'image/svg+xml',
6180
+ mp4: 'video/mp4',
6181
+ mov: 'video/quicktime',
6182
+ webm: 'video/webm',
6183
+ log: 'text/plain; charset=utf-8',
6184
+ txt: 'text/plain; charset=utf-8',
6185
+ md: 'text/plain; charset=utf-8',
6186
+ json: 'text/plain; charset=utf-8',
6187
+ }
6188
+
6189
+ /** 附件的扩展名 → MIME。不在白名单里返回 ''(调用方据此拒收)。 */
6190
+ function feedbackAttachMime(name) {
6191
+ const leaf = String(name || '').split(/[\\/]/).pop() || ''
6192
+ const dot = leaf.lastIndexOf('.')
6193
+ if (dot <= 0) return ''
6194
+ return FEEDBACK_ATTACH_MIME[leaf.slice(dot + 1).toLowerCase()] || ''
6195
+ }
6196
+
6197
+ /** Markdown 引用:图片用 ![](),其它(视频/日志)用普通链接,点开是下载/播放。 */
6198
+ function feedbackAttachMarkdown(item) {
6199
+ const url = String((item && item.url) || '')
6200
+ const name = String((item && item.name) || 'attachment').replace(/([\[\]])/g, '\\$1')
6201
+ if (!url) return ''
6202
+ return /^image\//.test(String((item && item.type) || '')) ? `![${name}](${url})` : `- [${name}](${url})`
6203
+ }
6204
+
6205
+ /**
6206
+ * 上传一个附件到 GitHub(两步:拿上传地址 → PUT 字节)。
6207
+ * 成功返回 { ok: true, name, url, type },失败返回 { ok: false, name, error } —— 不抛,
6208
+ * 因为「有一个附件传不上去」不该让整条反馈都发不出去。
6209
+ */
6210
+ /**
6211
+ * 找(或建)一个用来挂反馈附件的 release。
6212
+ *
6213
+ * GitHub 只有 release 有 asset 接口,Issue 没有。先按 tag `feedback-assets` 找;
6214
+ * 找不到就建一个**草稿** release(draft=true):它不会出现在 Releases 页面、
6215
+ * 不会被搜索引擎收录,但知道链接的人打得开 —— 反馈附件本来就不该公开发布。
6216
+ *
6217
+ * 缓存到进程内存里:一次反馈最多 4 个附件,不该为每个文件都去查一遍。
6218
+ */
6219
+ const feedbackReleaseCache = new Map()
6220
+
6221
+ async function feedbackAssetRelease(repo, token) {
6222
+ const cached = feedbackReleaseCache.get(repo)
6223
+ if (cached) return cached
6224
+ const tag = 'feedback-assets'
6225
+ const found = await ghApi(`/repos/${repo}/releases/tags/${encodeURIComponent(tag)}`, { token })
6226
+ if (found.ok && found.json && found.json.id) {
6227
+ const r = { id: found.json.id, uploadUrl: String(found.json.upload_url || '') }
6228
+ feedbackReleaseCache.set(repo, r)
6229
+ return r
6230
+ }
6231
+ // 没有就建:草稿 release,tag 固定,名字写明用途
6232
+ const created = await ghApi(`/repos/${repo}/releases`, {
6233
+ method: 'POST',
6234
+ token,
6235
+ body: {
6236
+ tag_name: tag,
6237
+ name: 'feedback-assets',
6238
+ body: 'Draft release holding the attachments of GitHub Issues in this repository. Created automatically by dsh-profile-config-sync; not published on purpose.',
6239
+ draft: true,
6240
+ prerelease: false,
6241
+ },
6242
+ timeoutMs: 20000,
6243
+ })
6244
+ if (!created.ok || !created.json || !created.json.id) {
6245
+ return { error: `${created.status} ${String((created.json && created.json.message) || '').slice(0, 160) || '建不了存放附件的 release'}` }
6246
+ }
6247
+ const r = { id: created.json.id, uploadUrl: String(created.json.upload_url || '') }
6248
+ feedbackReleaseCache.set(repo, r)
6249
+ return r
6250
+ }
6251
+
6252
+ /**
6253
+ * 上传一个附件到 GitHub 的 release assets。
6254
+ * 成功返回 { ok: true, name, url, type },失败返回 { ok: false, name, error } —— 不抛,
6255
+ * 因为「有一个附件传不上去」不该让整条反馈都发不出去。
6256
+ */
6257
+ async function uploadFeedbackAsset(repo, token, name, buf, mime) {
6258
+ const safe = String(name || 'attachment').split(/[\\/]/).pop().slice(0, 120) || 'attachment'
6259
+ const rel = await feedbackAssetRelease(repo, token)
6260
+ if (!rel || !rel.id) {
6261
+ return { ok: false, name: safe, error: String((rel && rel.error) || '拿不到存放附件的 release') }
6262
+ }
6263
+ if (!rel.uploadUrl) {
6264
+ return { ok: false, name: safe, error: 'release 没有 upload_url' }
6265
+ }
6266
+ // upload_url 形如 https://uploads.github.com/repos/<o>/<r>/releases/<id>/assets{?name,label}
6267
+ // —— 官方格式是「{?name,label}」这一整段,不能只把 {name} 当占位符替换。
6268
+ // 去掉那段之后地址末尾没有查询串,所以要用「?」而不是「&」。
6269
+ const base = rel.uploadUrl.replace(/\{\?[^}]*\}/g, '')
6270
+ const target = base + (base.includes('?') ? '&' : '?') + 'name=' + encodeURIComponent(safe)
6271
+ const headers = {
6272
+ Accept: 'application/vnd.github+json',
6273
+ 'X-GitHub-Api-Version': '2022-11-28',
6274
+ 'User-Agent': PACKAGE_ID,
6275
+ Authorization: `Bearer ${token}`,
6276
+ 'Content-Type': mime || 'application/octet-stream',
6277
+ 'Content-Length': String(buf.length),
6278
+ }
6279
+ let res
6280
+ try {
6281
+ const ctrl = typeof AbortController === 'function' ? new AbortController() : null
6282
+ const timer = ctrl ? setTimeout(() => { try { ctrl.abort() } catch { } }, 120000) : null
6283
+ try {
6284
+ res = await fetch(target, { method: 'POST', headers, body: buf, signal: ctrl ? ctrl.signal : undefined })
6285
+ } finally { if (timer) clearTimeout(timer) }
6286
+ } catch (e) {
6287
+ return { ok: false, name: safe, error: String((e && e.message) || e) }
6288
+ }
6289
+ const raw = await res.text().catch(() => '')
6290
+ let json = null
6291
+ try { json = raw ? JSON.parse(raw) : null } catch { json = null }
6292
+ if (!res.ok || !json || !json.browser_download_url) {
6293
+ return { ok: false, name: safe, error: `${res.status} ${String((json && json.message) || raw).slice(0, 160) || '上传失败'}` }
6294
+ }
6295
+ return { ok: true, name: safe, url: String(json.browser_download_url), type: mime || '' }
6296
+ }
6297
+
6298
+ /**
6299
+ * 正文 = 用户写的 + 附件引用 + 环境块(环境块永远在最后一段)。
6300
+ * 有附件时附件在前、环境块在后;没附件时就是原来的形状,老行为一个字节都不变。
6301
+ */
6302
+ function issueBodyWithAttachments(text, config, attachments) {
6303
+ const base = String(text || '').trim()
6304
+ const refs = (attachments || []).map(feedbackAttachMarkdown).filter(Boolean)
6305
+ const withRefs = refs.length ? `${base}${base ? '\n\n' : ''}### 附件 / Attachments\n${refs.join('\n')}\n` : base
6306
+ return issueBodyOf(withRefs, config)
6307
+ }
6308
+
6309
+ async function createIssue(repo, token, title, text, config, attachments = []) {
5662
6310
  return ghApi(`/repos/${repo}/issues`, {
5663
6311
  method: 'POST',
5664
6312
  token,
5665
- body: { title, body: issueBodyOf(text, config), labels: [GH_FEEDBACK_LABEL] },
6313
+ body: { title, body: issueBodyWithAttachments(text, config, attachments), labels: [GH_FEEDBACK_LABEL] },
5666
6314
  })
5667
6315
  }
5668
6316
 
@@ -6021,7 +6669,9 @@ async function handleFeedback(req, res, config) {
6021
6669
  if (!originAllowed(req)) { sendJson(res, 403, { ok: false, error: 'cross-origin request rejected' }); return }
6022
6670
 
6023
6671
  try {
6024
- const raw = await readBody(req)
6672
+ // 0.6.48:反馈可能带最多 4 个附件的 base64(每个 20 MB 上限,但 base64 后按 32 MB 算)。
6673
+ // 这里给 160 MB 的上限:够 4×20 MB 的极端情况,又不至于让一个请求把内存吃穿。
6674
+ const raw = await readBody(req, ROUTE_FEEDBACK_MAX_BODY)
6025
6675
  const payload = raw.trim() ? JSON.parse(raw) : {}
6026
6676
  const g = await ghToken(config, dshHome)
6027
6677
 
@@ -6110,7 +6760,9 @@ async function handleFeedback(req, res, config) {
6110
6760
  const sent = []
6111
6761
  const failed = []
6112
6762
  for (const item of pending) {
6113
- const r = await createIssue(g.repo, g.token, String(item.title || ''), String(item.body || ''), config)
6763
+ // 0.6.48:队列里可能带着已经上传好的附件 URL(建 issue 那步失败时留下的),
6764
+ // 补发直接引用,不再重传 —— 附件已经在仓库资产里,重传只会留下垃圾。
6765
+ const r = await createIssue(g.repo, g.token, String(item.title || ''), String(item.body || ''), config, Array.isArray(item.attachments) ? item.attachments : [])
6114
6766
  if (r.ok && r.json) sent.push({ number: r.json.number, url: r.json.html_url })
6115
6767
  else failed.push(item)
6116
6768
  }
@@ -6144,31 +6796,108 @@ async function handleFeedback(req, res, config) {
6144
6796
  const text = String(payload.body || payload.detail || '').trim().slice(0, 6000)
6145
6797
  if (!title) throw new Error(t('先写个标题,方便以后对上号', 'Give it a title so it can be found later'))
6146
6798
 
6147
- // 没令牌:不硬失败,给一条浏览器预填链接(浏览器登录了 GitHub 就能点提交)
6799
+ // 4a) 附件(issue #9:图片 / 视频)。面板把文件读成 base64 放进 payload.attachments:
6800
+ // [{ name, type, data }]。这里先校验再上传 —— 上传是不可撤销的(资产留在仓库里),
6801
+ // 所以宁可在本地就拒掉不合规的,也不要传上去再删。
6802
+ const attachments = []
6803
+ const attachErrors = []
6804
+ const rawAttachments = Array.isArray(payload.attachments) ? payload.attachments : []
6805
+ if (rawAttachments.length > FEEDBACK_MAX_ATTACH_COUNT) {
6806
+ throw new Error(t(
6807
+ `附件最多 ${FEEDBACK_MAX_ATTACH_COUNT} 个(收到 ${rawAttachments.length} 个)`,
6808
+ `At most ${FEEDBACK_MAX_ATTACH_COUNT} attachments (got ${rawAttachments.length})`,
6809
+ ))
6810
+ }
6811
+ for (const item of rawAttachments) {
6812
+ const name = String((item && item.name) || '')
6813
+ const mime = feedbackAttachMime(name)
6814
+ if (!mime) {
6815
+ attachErrors.push(`${name || '?'}: ${t('不支持的文件类型(只收图片 / 视频 / 日志)', 'unsupported type (images, videos and logs only)')}`)
6816
+ continue
6817
+ }
6818
+ let buf = null
6819
+ try {
6820
+ const b64 = String((item && item.data) || '')
6821
+ // 先按 base64 长度粗筛:base64 约为原字节的 4/3,
6822
+ // 超上限十几倍的数据根本不该解码(否则先占一份内存再丢掉)。
6823
+ if (b64 && b64.length <= Math.ceil(FEEDBACK_MAX_ATTACH_BYTES * 4 / 3) + 8) buf = Buffer.from(b64, 'base64')
6824
+ } catch { buf = null }
6825
+ if (!buf || buf.length === 0) {
6826
+ attachErrors.push(`${name || '?'}: ${t('读不到文件内容', 'cannot read the file content')}`)
6827
+ continue
6828
+ }
6829
+ if (buf.length > FEEDBACK_MAX_ATTACH_BYTES) {
6830
+ attachErrors.push(`${name}: ${t(`超过 ${Math.round(FEEDBACK_MAX_ATTACH_BYTES / 1048576)} MB`, `larger than ${Math.round(FEEDBACK_MAX_ATTACH_BYTES / 1048576)} MB`)}`)
6831
+ continue
6832
+ }
6833
+ attachments.push({ name, type: mime, buf })
6834
+ }
6835
+
6836
+ // 没令牌:不硬失败,给一条浏览器预填链接(浏览器登录了 GitHub 就能点提交)。
6837
+ // 有附件时必须在消息里说清楚「附件没带上,要手动拖进网页」—— 静默丢弃是这类功能最常见的坑。
6148
6838
  if (!g.token) {
6839
+ const localNames = attachments.map((a) => a.name)
6840
+ const notes = []
6841
+ if (localNames.length) {
6842
+ notes.push(t(
6843
+ `没有令牌:附件(${localNames.join('、')})没能上传,请在打开的页面里手动把它们拖进正文;标题和正文都已填好。`,
6844
+ `No token: attachments (${localNames.join(', ')}) were not uploaded — drag them into the body on the opened page; title and body are prefilled.`,
6845
+ ))
6846
+ }
6847
+ // 被拒的附件也要说:悄悄丢掉一个 .exe,用户会以为「它上去了」
6848
+ if (attachErrors.length) {
6849
+ notes.push(t(`有附件没带上:${attachErrors.join('、')}`, `Some attachments were left out: ${attachErrors.join(', ')}`))
6850
+ }
6149
6851
  sendJson(res, 200, {
6150
6852
  ok: true,
6151
6853
  needToken: true,
6152
6854
  submitted: false,
6153
6855
  fallbackUrl: newIssueUrl(g.repo, title, text, config),
6154
- error: t('没有令牌:可以打开预填好的新建 issue 页面,在浏览器里点一下提交', 'No token: open the prefilled new-issue page and press submit in the browser'),
6856
+ pendingAttachments: localNames,
6857
+ attachmentErrors: attachErrors,
6858
+ error: notes.join(' ') || t('没有令牌:可以打开预填好的新建 issue 页面,在浏览器里点一下提交', 'No token: open the prefilled new-issue page and press submit in the browser'),
6155
6859
  })
6156
6860
  return
6157
6861
  }
6158
6862
 
6159
- const r = await createIssue(g.repo, g.token, title, text, config)
6863
+ // 先传附件:资产一旦上传就留在仓库里,所以放在建 issue 之前——
6864
+ // 建 issue 失败时至少能把这些 URL 存进待发队列,补发时不用再传一遍。
6865
+ const uploaded = []
6866
+ for (const a of attachments) {
6867
+ const r = await uploadFeedbackAsset(g.repo, g.token, a.name, a.buf, a.type)
6868
+ if (r.ok) uploaded.push({ name: r.name, url: r.url, type: r.type })
6869
+ else attachErrors.push(`${a.name}: ${r.error}`)
6870
+ }
6871
+
6872
+ const r = await createIssue(g.repo, g.token, title, text, config, uploaded)
6160
6873
  if (r.ok && r.json) {
6161
- sendJson(res, 200, { ok: true, number: r.json.number, url: r.json.html_url, item: issueToItem(r.json) })
6874
+ sendJson(res, 200, {
6875
+ ok: true,
6876
+ number: r.json.number,
6877
+ url: r.json.html_url,
6878
+ item: issueToItem(r.json),
6879
+ attachments: uploaded.map((u) => ({ name: u.name, url: u.url })),
6880
+ attachmentErrors: attachErrors,
6881
+ })
6162
6882
  return
6163
6883
  }
6164
6884
  // 建 issue 失败:进本机队列,网络好了点「补发」
6165
6885
  const items = readOutbox(dshHome)
6166
- items.push({ title, body: text, createdAt: new Date().toISOString(), error: `${r.status} ${String((r.json && r.json.message) || '').slice(0, 160)}` })
6886
+ items.push({
6887
+ title,
6888
+ body: text,
6889
+ createdAt: new Date().toISOString(),
6890
+ error: `${r.status} ${String((r.json && r.json.message) || '').slice(0, 160)}`,
6891
+ // 附件 URL 一起入队:补发时直接引用,不重复上传
6892
+ attachments: uploaded.map((u) => ({ name: u.name, url: u.url, type: u.type })),
6893
+ })
6167
6894
  writeOutbox(dshHome, items)
6168
6895
  sendJson(res, 200, {
6169
6896
  ok: true,
6170
6897
  queued: true,
6171
6898
  remaining: items.length,
6899
+ attachments: uploaded.map((u) => ({ name: u.name, url: u.url })),
6900
+ attachmentErrors: attachErrors,
6172
6901
  error: `${r.status} ${String((r.json && r.json.message) || '').slice(0, 160)}`,
6173
6902
  })
6174
6903
  } catch (error) {