dsh-profile-config-sync 0.6.47 → 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.
@@ -0,0 +1,238 @@
1
+ // 「插件数据」/「额外路径」两组的判定规则 —— Host 面板与 Node 引擎共用同一份。
2
+ //
3
+ // 为什么要挪出来
4
+ // 这两组的规则(单文件上限 / 排除通配 / 跳过的目录 / 安全必需项)原先只写在 index.js 里,
5
+ // 于是 macOS / Linux 的引擎(runtime/sync-engine.mjs)压根不知道这些规则,也就没法抓这两组。
6
+ // 规则一旦两份实现,迟早走样(0.6.15 就出过一次:JS 侧漏了 browser-profiles,
7
+ // 面板把几千个文件的 mtime 算成「待推送」,而 capture 根本不会抓它们)。
8
+ // 所以规则只认这个文件,engine 与 index.js 都从这里 import。
9
+
10
+ import { closeSync, openSync, readdirSync as readdirSyncImpl, readFileSync, readSync, statSync } from 'node:fs'
11
+ import { join } from 'node:path'
12
+
13
+ export const EXTRA_CONFIG_NAME = 'config-sync-extra.json'
14
+ /** GitHub 单文件硬上限 100MB,超过必被拒收,所以配置里调多大都按这个封顶。 */
15
+ export const EXTRA_HARD_MAX_BYTES = 104857600
16
+ export const EXTRA_DEFAULT_SKIP_DIRS = [
17
+ 'profiles', 'skills', '.agent-presets', 'storages', 'sessions', 'attachments', 'logs', 'backups',
18
+ 'update-staging', 'electron', 'dsh-runtimes', 'dsh-market', '.dsh-plugin-market', 'dsh-session-manager',
19
+ 'browser-profiles', 'im', 'node_modules',
20
+ // 插件自己产出的暂存目录不能当成「插件数据」再传上去:
21
+ // profile-from-cloud / prompt-from-cloud 是跨平台移植时摊出来的对照件,
22
+ // local-plugins-restore 是解包出来的本地插件副本 —— 传上去既没用又会来回翻倍。
23
+ 'profile-from-cloud', 'prompt-from-cloud', 'local-plugins-restore',
24
+ ]
25
+ export const EXTRA_DEFAULT_EXCLUDE = [
26
+ '*.db', '*.db-*', '*.db3', '*.sqlite', '*.sqlite3', '*.sqlite-*', '*.db-shm', '*.db-wal',
27
+ '*.node', '*.exe', '*.dll', '*.asar', '*.pak', '*.bin', '*.iso', '*.img',
28
+ '*.zip', '*.7z', '*.rar', '*.tar', '*.gz', '*.tgz', '*.mp4', '*.mkv', '*.avi',
29
+ '*.log', '*.log.*', '*.tmp', '*.bak', '*.bak-*', '*.old', '*.orig', '*.swp',
30
+ '*.env', '.env*', 'config-sync-gh.json', 'config-sync-feedback-outbox.json', 'dsh-config-sync.json', 'dsh-ssh-master.key',
31
+ 'api-key', '*.pem', '*.key', '*.p12', '*.pfx', '*.crt',
32
+ '*cache*', '*token*', '*secret*', '*credential*', '*password*', '*vault*',
33
+ 'browser-profiles', 'User Data', 'Login Data', 'Cookies', 'Web Data', 'Local State',
34
+ 'node_modules', '.git', '.cache', '__pycache__', '.venv',
35
+ ]
36
+
37
+ /**
38
+ * 安全必需项:用户自己的 config-sync-extra.json 不允许把它们去掉。
39
+ * 与 runtime/dsh-sync-common.ps1 的 $SyncExtraMandatorySkipDirs / $SyncExtraMandatoryExcludes 同一份名单。
40
+ *
41
+ * 起因(实测):exclude / skipDirs 是「整份替换」语义,用户早先存下的旧快照会让新加的
42
+ * browser-profiles 规则整条失效 —— 那目录里有几千个文件、268MB,含密码库与登录态。
43
+ */
44
+ export const EXTRA_MANDATORY_SKIP_DIRS = ['browser-profiles']
45
+ export const EXTRA_MANDATORY_EXCLUDES = ['browser-profiles', 'User Data', 'Login Data', 'Cookies', 'Web Data', 'Local State']
46
+
47
+ export function extraConfigPath(dshHome) { return join(dshHome, EXTRA_CONFIG_NAME) }
48
+
49
+ export function wildcardToRegex(pat) {
50
+ const esc = String(pat).replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.')
51
+ return new RegExp(`^${esc}$`, 'i')
52
+ }
53
+
54
+ export function topUpExtraMandatory(cfg) {
55
+ if (!cfg || !cfg.pluginData) return { skipDirs: [], exclude: [] }
56
+ const addedSkip = EXTRA_MANDATORY_SKIP_DIRS.filter((x) => !(cfg.pluginData.skipDirs || []).includes(x))
57
+ const addedExcl = EXTRA_MANDATORY_EXCLUDES.filter((x) => !(cfg.pluginData.exclude || []).includes(x))
58
+ if (addedSkip.length) cfg.pluginData.skipDirs = [...(cfg.pluginData.skipDirs || []), ...addedSkip]
59
+ if (addedExcl.length) cfg.pluginData.exclude = [...(cfg.pluginData.exclude || []), ...addedExcl]
60
+ return { skipDirs: addedSkip, exclude: addedExcl }
61
+ }
62
+
63
+ /** 读规则文件;缺文件 / 坏 JSON 都退回默认(不让整页读不出来)。 */
64
+ export function readExtraConfig(dshHome) {
65
+ const cfg = {
66
+ version: 1,
67
+ pluginData: {
68
+ enabled: true,
69
+ maxFileBytes: EXTRA_HARD_MAX_BYTES,
70
+ exclude: [...EXTRA_DEFAULT_EXCLUDE],
71
+ skipDirs: [...EXTRA_DEFAULT_SKIP_DIRS],
72
+ },
73
+ extra: { enabled: true, paths: [] },
74
+ }
75
+ const p = extraConfigPath(dshHome)
76
+ let raw = ''
77
+ try { raw = readFileSync(p, 'utf8') } catch { return cfg }
78
+ try {
79
+ const j = JSON.parse(raw)
80
+ const pd = j && j.pluginData
81
+ if (pd) {
82
+ if (pd.enabled === false) cfg.pluginData.enabled = false
83
+ const n = Number(pd.maxFileBytes)
84
+ if (Number.isFinite(n) && n > 0) cfg.pluginData.maxFileBytes = Math.min(Math.floor(n), EXTRA_HARD_MAX_BYTES)
85
+ // 排除名单整份替换:用户在面板里删掉一条就真的不再排除
86
+ if (Array.isArray(pd.exclude)) cfg.pluginData.exclude = pd.exclude.filter((x) => typeof x === 'string' && x)
87
+ if (Array.isArray(pd.skipDirs)) cfg.pluginData.skipDirs = pd.skipDirs.filter((x) => typeof x === 'string' && x)
88
+ }
89
+ const ex = j && j.extra
90
+ if (ex) {
91
+ if (ex.enabled === false) cfg.extra.enabled = false
92
+ if (Array.isArray(ex.paths)) {
93
+ cfg.extra.paths = ex.paths
94
+ .filter((x) => x && typeof x.id === 'string' && typeof x.src === 'string' && x.id && x.src)
95
+ .map((x) => ({ id: x.id, src: x.src, label: typeof x.label === 'string' && x.label ? x.label : x.id }))
96
+ }
97
+ }
98
+ } catch { /* 坏了就按默认规则走 */ }
99
+ const added = topUpExtraMandatory(cfg)
100
+ if (added.skipDirs.length || added.exclude.length) {
101
+ cfg.pluginData.missingMandatory = { skipDirs: added.skipDirs, exclude: added.exclude }
102
+ }
103
+ return cfg
104
+ }
105
+
106
+ /** 返回跳过原因('' = 允许同步),与 runtime/dsh-sync-common.ps1 的 Test-SyncExtraSkip 判定一致。 */
107
+ export function extraSkipReason(relName, size, cfg) {
108
+ const max = Math.min(cfg.pluginData.maxFileBytes || EXTRA_HARD_MAX_BYTES, EXTRA_HARD_MAX_BYTES)
109
+ if (size > max) return 'too-big'
110
+ if (!relName) return ''
111
+ const parts = String(relName).split(/[\\/]+/).filter((x) => x)
112
+ const name = parts.length ? parts[parts.length - 1] : relName
113
+ for (const pat of cfg.pluginData.exclude || []) {
114
+ const re = wildcardToRegex(pat)
115
+ if (re.test(name)) return 'excluded'
116
+ for (const seg of parts) if (re.test(seg)) return 'excluded'
117
+ }
118
+ return ''
119
+ }
120
+
121
+ /**
122
+ * 插件数据槽:`<DshHome>` 的一级目录(跳过系统/已覆盖目录与隐藏目录)。
123
+ * 与 dsh-sync-common.ps1 的 Get-PluginDataSlots 同一份语义,只是不带统计(引擎不需要)。
124
+ */
125
+ /**
126
+ * 无论用户配置里怎么写都必须跳过的目录:这些是**插件自己的暂存产物**,
127
+ * 不是别人家的插件数据。传上去再拉下来只会来回翻倍,还会把移植对照件当配置铺回去。
128
+ * (老的 config-sync-extra.json 已经把旧默认名单抄进去了,topUp 不会补新项,所以这里硬拦。)
129
+ */
130
+ export const PLUGIN_DATA_HARD_SKIP = new Set([
131
+ 'profile-from-cloud', 'prompt-from-cloud', 'local-plugins-restore',
132
+ 'browser-profiles', 'user data', 'User Data',
133
+ ])
134
+
135
+ export function listPluginDataSlots(dshHome, cfg) {
136
+ const skip = new Set((cfg && cfg.pluginData && cfg.pluginData.skipDirs) || [])
137
+ let entries = []
138
+ try { entries = readdirSync2(dshHome) } catch { return [] }
139
+ const out = []
140
+ for (const e of entries) {
141
+ if (!e.isDirectory()) continue
142
+ if (skip.has(e.name)) continue
143
+ if (PLUGIN_DATA_HARD_SKIP.has(e.name)) continue
144
+ if (e.name.startsWith('.')) continue
145
+ out.push({ id: e.name, src: join(dshHome, e.name) })
146
+ }
147
+ return out
148
+ }
149
+
150
+ function readdirSync2(dir) { return readdirSyncImpl(dir, { withFileTypes: true }) }
151
+ /**
152
+ * 凭据 / 私有文件的判定 —— 与 PowerShell 的 Test-PrivateSecretFileName + Test-SyncExtraSecret 对齐。
153
+ *
154
+ * 两道门:
155
+ * 1) 名字(自家私有 json / .env / *.pem / *.key / *.p12 / *.pfx / SSH 私钥名);
156
+ * 2) 内容嗅探(GitHub 令牌前缀 + accessToken / apiKey / password 这类字段名)——
157
+ * 名字看不出来的才算「嗅探」,但漏了它就把登录态搬进仓库了。
158
+ *
159
+ * 读不出来的文件一律当凭据(旧实现「读不了就放行」,超长路径 / 独占 / 权限不足的文件会静默进仓库)。
160
+ */
161
+ export const PRIVATE_FILE_NAMES = [
162
+ 'config-sync-gh.json', 'config-sync-feedback-outbox.json', 'dsh-config-sync.json',
163
+ 'config-sync-state.json', 'config-sync-roots.json', 'config-sync-scope.json',
164
+ 'config-sync-delete-cloud.json', 'config-sync-extra.json', 'sync-notices.json',
165
+ '.credentials.yaml', '.env', 'dsh-ssh-master.key',
166
+ ]
167
+
168
+ const PRIVATE_NAME_PATTERNS = [/\.env\..*$/i, /\.pem$/i, /\.key$/i, /\.p12$/i, /\.pfx$/i, /^(id_(?:rsa|dsa|ecdsa|ed25519)(?:_sk)?|identity|.*\.ppk)$/i]
169
+
170
+ /** 内容里的凭据标记(小写匹配;GitHub 令牌按正则单独判) */
171
+ const SECRET_MARKERS = [
172
+ '"accesstoken"', '"refreshtoken"', '"idtoken"', '"apikey"', '"api_key"',
173
+ '"clientsecret"', '"privatekey"', '"password"', '"webdavpass"', '"updatetoken"',
174
+ 'authorization: bearer', 'github_token=', 'gh_token=',
175
+ ]
176
+
177
+ const GITHUB_TOKEN_RE = /gh[pousr]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,}/
178
+ const PEM_HEAD_RE = /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----|PuTTY-User-Key-File-[0-9]/
179
+
180
+ /**
181
+ * 源码类文件不做「字段名」扫描(那道门是给配置/数据文件用的)。
182
+ *
183
+ * 实测踩到的坑:本地源码插件这一组按目录打包时,插件自己的 `dsh-sync-common.ps1`
184
+ * (里面定义了一张名为 "$SyncExtraSecretMarkers" 的名单,字面量就含 "password" / "apikey")、
185
+ * `runtime/extra-rules.mjs`、`tools/selftest.mjs` 全被判成凭据文件跳过 —— 打出来的 zip 缺关键文件,
186
+ * 对方机器解出来是个装不上的插件。真实令牌(GitHub 前缀)和私钥头仍然一律拦,那道门不看扩展名。
187
+ */
188
+ const CODE_EXTS = new Set([
189
+ '.js', '.mjs', '.cjs', '.ts', '.tsx', '.jsx', '.vue', '.svelte', '.css', '.scss', '.less',
190
+ '.html', '.md', '.ps1', '.psm1', '.sh', '.bash', '.zsh', '.py', '.rb', '.go', '.rs', '.java',
191
+ '.c', '.h', '.cpp', '.bat', '.cmd', '.sql', '.proto',
192
+ ])
193
+
194
+ export function looksPrivateName(relOrPath) {
195
+ const leaf = String(relOrPath || '').split(/[\\/]/).pop() || ''
196
+ if (!leaf) return false
197
+ const lower = leaf.toLowerCase()
198
+ if (PRIVATE_FILE_NAMES.includes(lower)) return true
199
+ return PRIVATE_NAME_PATTERNS.some((re) => re.test(leaf))
200
+ }
201
+
202
+ /** 读一段样本:≤2 MB 整份,更大的取头尾各 512 KB(令牌常落在头部或日志尾部)。 */
203
+ function sampleBytes(full) {
204
+ const st = statSync(full)
205
+ const len = st.size
206
+ if (len <= 2100000) return readFileSync(full)
207
+ const chunk = 512 * 1024
208
+ const head = Buffer.alloc(Math.min(chunk, len))
209
+ const tail = Buffer.alloc(Math.min(chunk, len - Math.max(0, len - chunk)))
210
+ const fd = openSync(full, 'r')
211
+ try {
212
+ const headRead = readSync(fd, head, 0, head.length, 0)
213
+ readSync(fd, tail, 0, tail.length, Math.max(0, len - chunk))
214
+ return Buffer.concat([head.subarray(0, headRead), tail])
215
+ } finally { closeSync(fd) }
216
+ }
217
+
218
+ export function looksSecretFile(full, relOrPath) {
219
+ if (looksPrivateName(relOrPath || full)) return true
220
+ try {
221
+ const buf = sampleBytes(full)
222
+ // latin1(码位 = 字节):二进制里的 ASCII 令牌照样命中,也不会因非法 UTF-8 抛错
223
+ const raw = buf.toString('latin1')
224
+ // 显式豁免:文件里写了 dsh-sync-allow-secret 说明里面的令牌是**测试夹具**(本仓库的 selftest 就是),
225
+ // 由作者自己担这个责任;真实令牌不会自带这行。
226
+ if (/dsh-sync-allow-secret/i.test(raw)) return false
227
+ if (GITHUB_TOKEN_RE.test(raw)) return true
228
+ if (PEM_HEAD_RE.test(raw)) return true
229
+ const leaf = String(relOrPath || full).split(/[\\/]/).pop() || ''
230
+ const ext = leaf.includes('.') ? leaf.slice(leaf.lastIndexOf('.')).toLowerCase() : ''
231
+ if (CODE_EXTS.has(ext)) return false
232
+ const lower = raw.toLowerCase()
233
+ return SECRET_MARKERS.some((m) => lower.includes(m))
234
+ } catch {
235
+ // 读不了 = 判不了 → 宁可跳过(调用方会记进未同步清单)
236
+ return true
237
+ }
238
+ }
@@ -0,0 +1,279 @@
1
+ // 把插件新版本装进插件目录(macOS / Linux)—— install-plugin.ps1 的 Node 版。
2
+ //
3
+ // 为什么要有:Windows 版更新流程走 PowerShell 脚本(下载 → 校验 → 备份 → 覆盖),
4
+ // macOS / Linux 上没有 PowerShell,0.6.47 之前这边「检查到更新」之后两条路都断了:
5
+ // - 运行中安装 install-live 调的是 install-plugin.ps1(必然 ENOENT);
6
+ // - 退出后安装交给 post-exit.ps1(也不存在,见 post-exit.mjs)。
7
+ //
8
+ // 用法:
9
+ // node install-plugin.mjs -PluginDir <插件目录> [-Version 0.6.49] [-Sha256 <hex>] \
10
+ // [-Integrity <sri>] [-Sha1 <hex>] [-TgzUrls "url1|url2"] [-TgzFile <本地 tgz>] \
11
+ // -DshHome ~/.dsh [-LogFile <log>]
12
+ //
13
+ // 结果固定打一行 `RESULT:{json}`(ok / version / backup / log / error),与 PowerShell 版同形,
14
+ // 宿主(index.js runInstallPlugin 与 post-exit.mjs installUpdate)解析的就是这一行。
15
+ //
16
+ // 零第三方依赖:下载用全局 fetch,解包用 node:zlib 的 gunzip + 手写 ustar 解析
17
+ // (npm tarball 就是 gzip 的 tar,不需要 tar 命令,也不依赖系统装了 bsdtar)。
18
+
19
+ import { spawnSync } from 'node:child_process'
20
+ import {
21
+ copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync,
22
+ } from 'node:fs'
23
+ import { createHash } from 'node:crypto'
24
+ import { tmpdir } from 'node:os'
25
+ import { dirname, join, resolve, sep } from 'node:path'
26
+ import { fileURLToPath } from 'node:url'
27
+ import { gunzipSync } from 'node:zlib'
28
+
29
+ const SELF_DIR = dirname(fileURLToPath(import.meta.url))
30
+
31
+ /** `-Key value` / `-Key=value` 解析(与 sync-engine.mjs 同语义)。 */
32
+ function parseArgs(argv) {
33
+ const out = {}
34
+ for (let i = 0; i < argv.length; i++) {
35
+ const tok = String(argv[i])
36
+ if (!tok.startsWith('-')) continue
37
+ const clean = tok.replace(/^-+/, '')
38
+ const eq = clean.indexOf('=')
39
+ if (eq > 0) { out[clean.slice(0, eq)] = clean.slice(eq + 1); continue }
40
+ const next = argv[i + 1]
41
+ if (next !== undefined && !String(next).startsWith('-')) { out[clean] = String(next); i++ }
42
+ else out[clean] = true
43
+ }
44
+ return out
45
+ }
46
+
47
+ const a = parseArgs(process.argv.slice(2))
48
+ const pluginDir = resolve(String(a.PluginDir || a.pluginDir || ''))
49
+ const version = String(a.Version || a.version || '')
50
+ const sha256 = String(a.Sha256 || a.sha256 || '')
51
+ const integrity = String(a.Integrity || a.integrity || '')
52
+ const sha1 = String(a.Sha1 || a.sha1 || '')
53
+ const tgzFile = String(a.TgzFile || a.tgzFile || '')
54
+ const dshHome = resolve(String(a.DshHome || a.dshHome || join(process.env.HOME || '', '.dsh')))
55
+ const logFile = String(a.LogFile || a.logFile || '')
56
+ const urls = String(a.TgzUrls || a.tgzUrls || '').split('|').map((s) => s.trim()).filter(Boolean)
57
+
58
+ const stamp = new Date().toISOString().replace(/[-:]/g, '').replace(/\..+/, '').replace('T', '-')
59
+ const resolvedLog = logFile || join(dshHome, 'logs', `plugin-install-${stamp}.log`)
60
+
61
+ function log(text) {
62
+ const line = `[${new Date().toISOString().slice(11, 19)}] ${text}`
63
+ try { mkdirSync(dirname(resolvedLog), { recursive: true }); writeFileSync(resolvedLog, line + '\n', { flag: 'a' }) } catch { /* 日志写不进去不影响安装 */ }
64
+ try { process.stdout.write(line + '\n') } catch { /* 没有终端 */ }
65
+ }
66
+
67
+ function finish(ok, payload = {}) {
68
+ const obj = {
69
+ ok: Boolean(ok),
70
+ version: String(payload.version || version || ''),
71
+ backup: String(payload.backup || ''),
72
+ log: resolvedLog,
73
+ error: String(payload.error || ''),
74
+ }
75
+ process.stdout.write('RESULT:' + JSON.stringify(obj) + '\n')
76
+ process.exit(0)
77
+ }
78
+
79
+ /** 失败时把插件目录恢复成动手前的样子。 */
80
+ function restoreBackup(backup, target) {
81
+ if (!backup || !existsSync(backup)) return false
82
+ try {
83
+ for (const e of readdirSync(target, { withFileTypes: true })) {
84
+ rmSync(join(target, e.name), { recursive: true, force: true })
85
+ }
86
+ for (const e of readdirSync(backup, { withFileTypes: true })) {
87
+ copyTree(join(backup, e.name), join(target, e.name))
88
+ }
89
+ return true
90
+ } catch (e) {
91
+ log(`回滚失败:${(e && e.message) || e}`)
92
+ return false
93
+ }
94
+ }
95
+
96
+ function copyTree(from, to) {
97
+ const st = statSync(from)
98
+ if (st.isDirectory()) {
99
+ mkdirSync(to, { recursive: true })
100
+ for (const e of readdirSync(from, { withFileTypes: true })) copyTree(join(from, e.name), join(to, e.name))
101
+ return
102
+ }
103
+ mkdirSync(dirname(to), { recursive: true })
104
+ copyFileSync(from, to)
105
+ }
106
+
107
+ /** 下载到本地文件(带超时)。 */
108
+ async function download(url, dest) {
109
+ const ctrl = typeof AbortController === 'function' ? new AbortController() : null
110
+ const timer = ctrl ? setTimeout(() => { try { ctrl.abort() } catch { /* 忽略 */ } }, 180000) : null
111
+ try {
112
+ const res = await fetch(url, { signal: ctrl ? ctrl.signal : undefined, redirect: 'follow' })
113
+ if (!res.ok) throw new Error(`HTTP ${res.status}`)
114
+ const buf = Buffer.from(await res.arrayBuffer())
115
+ writeFileSync(dest, buf)
116
+ return buf.length
117
+ } finally { if (timer) clearTimeout(timer) }
118
+ }
119
+
120
+ /** SRI(sha512-base64)校验。 */
121
+ function checkIntegrity(buf, sri) {
122
+ const m = /^sha512-([A-Za-z0-9+/=]+)$/.exec(String(sri || '').trim())
123
+ if (!m) return false
124
+ const got = createHash('sha512').update(buf).digest('base64')
125
+ return got === m[1]
126
+ }
127
+
128
+ /**
129
+ * 解 npm tarball(gzip 的 ustar)到目标目录。
130
+ * 返回解出的文件数;遇到 GNU 长名('L')与 pax 头('x')都能处理。
131
+ */
132
+ function extractTarball(tgzPath, destDir) {
133
+ const raw = gunzipSync(readFileSync(tgzPath))
134
+ mkdirSync(destDir, { recursive: true })
135
+ let offset = 0
136
+ let longName = ''
137
+ let count = 0
138
+ const writeOne = (name, body) => {
139
+ // 剥掉 ./ 与 package/ 前缀,剩下的就是插件目录内容
140
+ const rel = name.replace(/^\.\//, '').replace(/^package\//, '')
141
+ // 安全边界:拒绝绝对路径与任何 .. 段,别让一个恶意包写到插件目录外面
142
+ if (!rel || rel.startsWith('/') || rel.split('/').includes('..')) return
143
+ // macOS 的 tar 会塞 AppleDouble 资源分叉(._xxx),解出来会在插件目录里留一堆垃圾文件
144
+ if (rel.split('/').some((seg) => seg.startsWith('._'))) return
145
+ const target = join(destDir, rel)
146
+ if (body === null) { mkdirSync(target, { recursive: true }); return }
147
+ mkdirSync(dirname(target), { recursive: true })
148
+ writeFileSync(target, body)
149
+ count++
150
+ }
151
+ while (offset + 512 <= raw.length) {
152
+ const header = raw.subarray(offset, offset + 512)
153
+ // 全零块 = 归档结束
154
+ if (header.every((b) => b === 0)) break
155
+ const readStr = (start, len) => header.subarray(start, start + len).toString('utf8').replace(/\0.*$/, '')
156
+ const nameRaw = readStr(0, 100)
157
+ const sizeRaw = readStr(124, 12).trim()
158
+ const size = sizeRaw ? parseInt(sizeRaw, 8) || 0 : 0
159
+ const type = String.fromCharCode(header[156] || 48)
160
+ const prefix = readStr(345, 155)
161
+ const dataStart = offset + 512
162
+ const dataEnd = dataStart + size
163
+ if (dataEnd > raw.length) break
164
+ const body = raw.subarray(dataStart, dataEnd)
165
+ if (type === 'L') {
166
+ // GNU 长文件名:内容就是真实路径(可能带结尾 NUL)
167
+ longName = body.toString('utf8').replace(/\0.*$/, '')
168
+ } else if (type === 'x' || type === 'g') {
169
+ // pax 扩展头:只关心 path=,其余忽略
170
+ const text = body.toString('utf8')
171
+ const m = /(\d+) path=([^\n]+)\n/.exec(text)
172
+ if (m) longName = m[2]
173
+ } else if (type === '0' || type === '\0' || type === '') {
174
+ writeOne(longName || (prefix ? prefix + '/' + nameRaw : nameRaw), body)
175
+ longName = ''
176
+ } else if (type === '5') {
177
+ writeOne(longName || (prefix ? prefix + '/' + nameRaw : nameRaw), null)
178
+ longName = ''
179
+ }
180
+ offset = dataEnd + Math.ceil(size / 512) * 512 - size
181
+ }
182
+ return count
183
+ }
184
+
185
+ async function main() {
186
+ if (!pluginDir) return finish(false, { error: '-PluginDir 必填(插件安装目录)' })
187
+ if (!existsSync(pluginDir)) return finish(false, { error: `插件目录不存在:${pluginDir}` })
188
+
189
+ const work = mkdtempSync(join(tmpdir(), 'dsh-plugin-install-'))
190
+ let backup = ''
191
+ try {
192
+ // 1) 拿到安装包
193
+ let tgz = ''
194
+ if (tgzFile && existsSync(tgzFile)) {
195
+ tgz = tgzFile
196
+ log(`使用已下载的安装包:${tgz}(${statSync(tgz).size} 字节)`)
197
+ } else {
198
+ if (!urls.length) return finish(false, { error: '没有可用的下载地址(-TgzUrls 为空且 -TgzFile 不存在)' })
199
+ const buf = Buffer.alloc(0)
200
+ let lastError = ''
201
+ for (const url of urls) {
202
+ const dest = join(work, 'package.tgz')
203
+ try {
204
+ log(`下载:${url}`)
205
+ await download(url, dest)
206
+ tgz = dest
207
+ break
208
+ } catch (e) {
209
+ lastError = `${url}:${(e && e.message) || e}`
210
+ log(` 失败:${lastError}`)
211
+ }
212
+ }
213
+ if (!tgz) return finish(false, { error: `下载失败(每个地址都试过了):${lastError}` })
214
+ void buf
215
+ }
216
+
217
+ // 2) 校验:sha256 / integrity / sha1 —— 与被校验物同源(npm registry 给的值)
218
+ const data = readFileSync(tgz)
219
+ const got256 = createHash('sha256').update(data).digest('hex')
220
+ const got1 = createHash('sha1').update(data).digest('hex')
221
+ if (sha256 && got256.toLowerCase() !== sha256.toLowerCase()) {
222
+ return finish(false, { error: `sha256 不匹配(期望 ${sha256},实际 ${got256})` })
223
+ }
224
+ if (sha1 && got1.toLowerCase() !== sha1.toLowerCase()) {
225
+ return finish(false, { error: `sha1 不匹配(期望 ${sha1},实际 ${got1})` })
226
+ }
227
+ if (integrity && !checkIntegrity(data, integrity)) {
228
+ return finish(false, { error: `integrity 不匹配(期望 ${integrity})` })
229
+ }
230
+ log(`校验通过:sha256=${got256.slice(0, 16)}…${sha1 ? ` sha1=${got1.slice(0, 12)}…` : ''}${integrity ? ' integrity=ok' : ''}`)
231
+
232
+ // 3) 解包到暂存目录,并核对包里的 version 与清单一致
233
+ const stage = join(work, 'stage')
234
+ const files = extractTarball(tgz, stage)
235
+ if (files === 0) return finish(false, { error: '安装包里没有解出任何文件' })
236
+ let pkg = null
237
+ try { pkg = JSON.parse(readFileSync(join(stage, 'package.json'), 'utf8')) } catch { pkg = null }
238
+ if (!pkg) return finish(false, { error: '安装包里没有 package.json(不是合法的 npm 包)' })
239
+ const gotVersion = String(pkg.version || '')
240
+ if (version && gotVersion !== version) {
241
+ return finish(false, { error: `包里的版本(${gotVersion})与清单(${version})不一致` })
242
+ }
243
+ log(`解包完成:${files} 个文件,版本 ${gotVersion}`)
244
+
245
+ // 4) 动手前整目录备份
246
+ const backupRoot = join(dshHome, 'backups')
247
+ mkdirSync(backupRoot, { recursive: true })
248
+ backup = join(backupRoot, `plugin-${gotVersion || 'unknown'}-${stamp}`)
249
+ mkdirSync(backup, { recursive: true })
250
+ for (const e of readdirSync(pluginDir, { withFileTypes: true })) {
251
+ copyTree(join(pluginDir, e.name), join(backup, e.name))
252
+ }
253
+ log(`已备份当前插件:${backup}`)
254
+
255
+ // 5) 覆盖(先清空再拷,避免旧版本残留文件混进新版本)
256
+ for (const e of readdirSync(pluginDir, { withFileTypes: true })) {
257
+ rmSync(join(pluginDir, e.name), { recursive: true, force: true })
258
+ }
259
+ for (const e of readdirSync(stage, { withFileTypes: true })) {
260
+ copyTree(join(stage, e.name), join(pluginDir, e.name))
261
+ }
262
+ log(`已覆盖插件目录:${pluginDir}`)
263
+ finish(true, { version: gotVersion, backup })
264
+ } catch (e) {
265
+ const message = String((e && e.stack) || e)
266
+ log(`安装失败:${message}`)
267
+ if (backup && restoreBackup(backup, pluginDir)) log('已把插件目录恢复成安装前的样子')
268
+ finish(false, { error: String((e && e.message) || e), backup })
269
+ } finally {
270
+ try { rmSync(work, { recursive: true, force: true }) } catch { /* 清不掉临时目录不算失败 */ }
271
+ }
272
+ }
273
+
274
+ // spawnSync 只为保持与 PowerShell 版一致的「子进程里跑」语义(宿主用 execFile 调它)。
275
+ void spawnSync
276
+ void SELF_DIR
277
+ void sep
278
+
279
+ main()