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/README.en.md +51 -7
- package/README.md +66 -17
- package/client.js +258 -155
- package/docs/CHANGELOG.md +6 -4
- package/docs/REFERENCE.md +39 -3
- package/index.js +1080 -351
- package/package.json +6 -4
- package/release-notes.json +7 -0
- package/runtime/contract.mjs +10 -3
- package/runtime/conversations.mjs +433 -0
- package/runtime/extra-rules.mjs +238 -0
- package/runtime/install-plugin.mjs +279 -0
- package/runtime/install-plugin.ps1 +60 -1
- package/runtime/platform.mjs +198 -5
- package/runtime/porting.mjs +319 -0
- package/runtime/post-exit.mjs +347 -0
- package/runtime/post-exit.ps1 +80 -1
- package/runtime/settings-sources.mjs +46 -0
- package/runtime/sync-engine.mjs +1190 -52
- package/runtime/webdav.mjs +247 -24
- package/runtime/zip.mjs +156 -0
package/runtime/webdav.mjs
CHANGED
|
@@ -23,6 +23,8 @@
|
|
|
23
23
|
|
|
24
24
|
import { createHash } from 'node:crypto'
|
|
25
25
|
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
|
|
26
|
+
import { request as httpRequest } from 'node:http'
|
|
27
|
+
import { request as httpsRequest } from 'node:https'
|
|
26
28
|
import { homedir } from 'node:os'
|
|
27
29
|
import { dirname, join, resolve, sep as SEP } from 'node:path'
|
|
28
30
|
import { fileURLToPath } from 'node:url'
|
|
@@ -40,15 +42,41 @@ export const DEFAULT_WEBDAV_DIR = 'dsh-config-sync'
|
|
|
40
42
|
export function normalizeWebdav(settings) {
|
|
41
43
|
const s = settings || {}
|
|
42
44
|
const rawUrl = String(s.webdavUrl || '').trim()
|
|
43
|
-
|
|
45
|
+
const w = {
|
|
44
46
|
enabled: Boolean(rawUrl),
|
|
45
47
|
url: rawUrl.replace(/\/+$/, ''),
|
|
46
48
|
user: String(s.webdavUser || '').trim(),
|
|
47
49
|
pass: String(s.webdavPass || ''),
|
|
48
50
|
dir: String(s.webdavDir || '').trim().replace(/^\/+|\/+$/g, '') || DEFAULT_WEBDAV_DIR,
|
|
51
|
+
// 0.6.48:自定义 User-Agent。部分第三方 WebDAV(群晖 / 坚果云 / 自建 DAV)会按 UA
|
|
52
|
+
// 放行或拦截客户端,默认 UA 会被当成未知客户端拒掉。留空 = 不发 User-Agent 头。
|
|
53
|
+
ua: sanitizeUserAgent(s.webdavUserAgent),
|
|
49
54
|
// auto:配了 WebDAV 就用它;否则走 git
|
|
50
55
|
mode: s.syncMode === 'webdav' || s.syncMode === 'auto' ? s.syncMode : 'git',
|
|
51
56
|
}
|
|
57
|
+
// 0.6.48:诊断字段(面板回显实际发出去的 UA / 失败状态码)。用不可枚举属性,
|
|
58
|
+
// 免得调用方 JSON.stringify(w) 或打日志时多出三个噪音字段。
|
|
59
|
+
Object.defineProperties(w, {
|
|
60
|
+
lastError: { value: '', writable: true, enumerable: false, configurable: true },
|
|
61
|
+
lastStatus: { value: 0, writable: true, enumerable: false, configurable: true },
|
|
62
|
+
})
|
|
63
|
+
return w
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* User-Agent 只允许单行可见 ASCII,且不能出现 CRLF。
|
|
68
|
+
*
|
|
69
|
+
* 这个值会进 HTTP 头:`\r\n` 能凭空造出一条头(响应拆分 / 绕过服务端 ACL),
|
|
70
|
+
* 非 ASCII 会让 undici 直接抛 TypeError(症状是「连不上」而不是「UA 非法」)。
|
|
71
|
+
* 不合法就退回「不发 UA」,绝不让一个填错的输入把整条同步打断。
|
|
72
|
+
*/
|
|
73
|
+
export function sanitizeUserAgent(raw) {
|
|
74
|
+
const s = String(raw == null ? '' : raw).trim()
|
|
75
|
+
if (!s) return ''
|
|
76
|
+
if (s.length > 200) return ''
|
|
77
|
+
// 可见 ASCII(0x20–0x7E)之外一律拒:tab 也不放行,头值里不需要它
|
|
78
|
+
if (!/^[\x20-\x7E]+$/.test(s)) return ''
|
|
79
|
+
return s
|
|
52
80
|
}
|
|
53
81
|
|
|
54
82
|
/** 当前是否应该走 WebDAV(auto 模式下看有没有配地址)。 */
|
|
@@ -99,28 +127,152 @@ function authHeader(w) {
|
|
|
99
127
|
return { authorization: `Basic ${token}` }
|
|
100
128
|
}
|
|
101
129
|
|
|
102
|
-
/**
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
130
|
+
/**
|
|
131
|
+
* 一个够用的 Response 替身。
|
|
132
|
+
*
|
|
133
|
+
* 为什么不直接用 fetch:undici 的 fetch **总会**带一个 User-Agent 头(默认 `node`),
|
|
134
|
+
* 且没有「不带 UA」的表达方式 —— 而「留空就不发 User-Agent」正是本插件对用户的承诺
|
|
135
|
+
* (有些服务看到陌生 UA 就拦)。node:http 则完全由我们决定发哪个头:没设就是没有。
|
|
136
|
+
* 这里只实现用到的那几个成员(ok / status / text / arrayBuffer)。
|
|
137
|
+
*/
|
|
138
|
+
class DavResponse {
|
|
139
|
+
constructor(status, headers, body) {
|
|
140
|
+
this.status = status
|
|
141
|
+
this.headers = headers || {}
|
|
142
|
+
this._body = body || Buffer.alloc(0)
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
get ok() { return this.status >= 200 && this.status < 300 }
|
|
146
|
+
|
|
147
|
+
async text() { return this._body.toString('utf8') }
|
|
148
|
+
|
|
149
|
+
async arrayBuffer() {
|
|
150
|
+
return this._body.buffer.slice(this._body.byteOffset, this._body.byteOffset + this._body.byteLength)
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** 真正发一次请求(不跟重定向)。 */
|
|
155
|
+
function rawRequestOnce(urlStr, { method, headers, body }, timeoutMs) {
|
|
156
|
+
return new Promise((resolve, reject) => {
|
|
157
|
+
let u
|
|
158
|
+
try { u = new URL(urlStr) } catch (e) { reject(new Error(`地址不合法:${urlStr}`)); return }
|
|
159
|
+
if (u.protocol !== 'http:' && u.protocol !== 'https:') {
|
|
160
|
+
reject(new Error(`只支持 http / https 地址:${urlStr}`))
|
|
161
|
+
return
|
|
162
|
+
}
|
|
163
|
+
const mod = u.protocol === 'https:' ? httpsRequest : httpRequest
|
|
164
|
+
let settled = false
|
|
165
|
+
const req = mod(u, { method: method || 'GET', headers: headers || {} }, (res) => {
|
|
166
|
+
const chunks = []
|
|
167
|
+
res.on('data', (c) => chunks.push(Buffer.isBuffer(c) ? c : Buffer.from(c)))
|
|
168
|
+
res.on('end', () => {
|
|
169
|
+
if (settled) return
|
|
170
|
+
settled = true
|
|
171
|
+
resolve(new DavResponse(res.statusCode || 0, res.headers, Buffer.concat(chunks)))
|
|
172
|
+
})
|
|
173
|
+
res.on('error', (e) => { if (!settled) { settled = true; reject(e) } })
|
|
111
174
|
})
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
175
|
+
req.on('error', (e) => { if (!settled) { settled = true; reject(e) } })
|
|
176
|
+
if (timeoutMs > 0) {
|
|
177
|
+
// 覆盖「响应头到手后 body 卡住」:node 的 socket 空闲计时同样管得到 body
|
|
178
|
+
req.setTimeout(timeoutMs, () => {
|
|
179
|
+
const err = new Error(`请求超时(${Math.round(timeoutMs / 1000)}s 内没有响应)`)
|
|
180
|
+
try { req.destroy(err) } catch { }
|
|
181
|
+
})
|
|
182
|
+
}
|
|
183
|
+
if (body !== undefined && body !== null) req.end(body)
|
|
184
|
+
else req.end()
|
|
185
|
+
})
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** 发请求,跟随重定向(最多 5 跳)。WebDAV 常见的 301/302 就是干这个的。 */
|
|
189
|
+
async function rawRequest(urlStr, init, timeoutMs, redirects = 0) {
|
|
190
|
+
const res = await rawRequestOnce(urlStr, init, timeoutMs)
|
|
191
|
+
const status = res.status
|
|
192
|
+
const isRedirect = status === 301 || status === 302 || status === 303 || status === 307 || status === 308
|
|
193
|
+
const location = res.headers && res.headers.location
|
|
194
|
+
if (isRedirect && location && redirects < 5) {
|
|
195
|
+
let next = ''
|
|
196
|
+
try { next = new URL(String(location), urlStr).toString() } catch { next = '' }
|
|
197
|
+
if (next) {
|
|
198
|
+
// 与浏览器一致:303 一律改成 GET;301/302 只在原方法是 POST 时改成 GET。
|
|
199
|
+
// PROPFIND / PUT 这类方法必须原样保留 —— 改成 GET 就把「列目录 / 传文件」变成取网页了。
|
|
200
|
+
const m = String(init.method || 'GET').toUpperCase()
|
|
201
|
+
const toGet = status === 303 || ((status === 301 || status === 302) && m === 'POST')
|
|
202
|
+
const init2 = toGet ? { ...init, method: 'GET', body: undefined } : init
|
|
203
|
+
return rawRequest(next, init2, timeoutMs, redirects + 1)
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
return res
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* 一次请求,带超时与统一错误。
|
|
211
|
+
*
|
|
212
|
+
* 0.6.48:User-Agent 可配置(留空则**不发**这个头)。
|
|
213
|
+
* 第三方 DAV 常按 UA 放行,默认的 undici UA 会被当成未知客户端直接 401/403 ——
|
|
214
|
+
* 用户看到的就是「连不上」。这里改用 node:http,因为只有它能做到「没设就是没有」。
|
|
215
|
+
*/
|
|
216
|
+
async function request(url, w, init = {}, timeoutMs = 30000) {
|
|
217
|
+
const headers = { ...(authHeader(w) || {}), ...((init && init.headers) || {}) }
|
|
218
|
+
const ua = sanitizeUserAgent(w && w.ua)
|
|
219
|
+
if (ua) headers['user-agent'] = ua
|
|
220
|
+
else delete headers['user-agent']
|
|
221
|
+
// 显式给 Content-Length:部分服务端不接受 chunked 的 PROPFIND
|
|
222
|
+
let body = init && init.body
|
|
223
|
+
if (body !== undefined && body !== null) {
|
|
224
|
+
const buf = Buffer.isBuffer(body) ? body : Buffer.from(String(body), 'utf8')
|
|
225
|
+
headers['content-length'] = String(buf.length)
|
|
226
|
+
body = buf
|
|
227
|
+
}
|
|
228
|
+
return rawRequest(url, { method: (init && init.method) || 'GET', headers, body }, timeoutMs)
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* 把「连不上 / 认证失败」拆成能照着修的具体原因。
|
|
233
|
+
*
|
|
234
|
+
* 以前无论 401、403、404、405 还是证书错误,面板都只显示
|
|
235
|
+
* 「连不上或认证失败(PROPFIND 无响应)」—— 用户既不知道是密码错、
|
|
236
|
+
* 还是这个服务压根不支持 PROPFIND,也不知道该去改哪一项。这里按状态码给话。
|
|
237
|
+
*
|
|
238
|
+
* 文案同时给中英文(面板与 CLI 都可能显示它,CLI 没有 accept-language)。
|
|
239
|
+
*/
|
|
240
|
+
function explainStatus(status, w) {
|
|
241
|
+
const url = String((w && w.url) || '')
|
|
242
|
+
if (status === 401) {
|
|
243
|
+
return '认证失败(401):用户名或密码不对,或这个服务要求别的认证方式(应用专用密码 / Token)'
|
|
244
|
+
+ ' / Auth failed (401): wrong username or password, or this service requires an app password / token'
|
|
115
245
|
}
|
|
246
|
+
if (status === 403) {
|
|
247
|
+
return '被拒绝(403):账号没有这个目录的权限;部分服务还会按 User-Agent 拦截,可在「User-Agent」里填它要求的客户端名'
|
|
248
|
+
+ ' / Forbidden (403): the account lacks access to this folder; some services also filter by User-Agent — set the client name they expect in "User-Agent"'
|
|
249
|
+
}
|
|
250
|
+
if (status === 404) {
|
|
251
|
+
return `地址下没有这个目录(404):${url} —— WebDAV 地址填到根(如 https://dav.example.com/dav),目录名单独填在「远端目录」`
|
|
252
|
+
+ ` / Not found (404): ${url} — put the server root in "WebDAV URL" (e.g. https://dav.example.com/dav) and the folder in "Remote dir"`
|
|
253
|
+
}
|
|
254
|
+
if (status === 405 || status === 501) {
|
|
255
|
+
return `这个服务不支持 PROPFIND(${status}):它可能不是标准 WebDAV 入口,或需要带路径前缀`
|
|
256
|
+
+ ` / PROPFIND not allowed (${status}): this may not be a standard WebDAV endpoint, or it needs a path prefix`
|
|
257
|
+
}
|
|
258
|
+
if (status === 301 || status === 302 || status === 307 || status === 308) {
|
|
259
|
+
return `地址被重定向(${status}):请直接填重定向后的最终地址`
|
|
260
|
+
+ ` / Redirected (${status}): use the final URL instead`
|
|
261
|
+
}
|
|
262
|
+
if (status === 0) {
|
|
263
|
+
return '连不上服务器:检查地址、网络与证书(自签名证书需加入系统信任库)'
|
|
264
|
+
+ ' / Cannot reach the server: check the URL, network and certificate (self-signed certs must be trusted by the system)'
|
|
265
|
+
}
|
|
266
|
+
return `PROPFIND 失败(HTTP ${status}) / PROPFIND failed (HTTP ${status})`
|
|
116
267
|
}
|
|
117
268
|
|
|
118
269
|
/**
|
|
119
270
|
* 读完响应体,带**独立**超时。
|
|
120
271
|
*
|
|
121
|
-
*
|
|
122
|
-
*
|
|
123
|
-
*
|
|
272
|
+
* 为什么还要单独计时:0.6.48 起传输层用 `node:http`,它的 `req.setTimeout` 是**空闲**计时
|
|
273
|
+
* (socket 上多久没数据),服务端若持续慢速吐 body 就永远不触发;而面板必须有一个
|
|
274
|
+
* 硬上限,否则整条同步流水线会永久挂着(进程不退、面板一直转)。
|
|
275
|
+
* 这个计时是「从发起到读完一共多久」,与服务端怎么吐数据无关。
|
|
124
276
|
*/
|
|
125
277
|
function withBodyTimeout(promise, timeoutMs = 30000, label = '读取响应体') {
|
|
126
278
|
let timer = null
|
|
@@ -177,7 +329,8 @@ export async function ensureRemoteDir(w, relDir = '') {
|
|
|
177
329
|
|
|
178
330
|
/**
|
|
179
331
|
* 列远端目录(PROPFIND Depth:1),返回相对路径 → { size, etag, mtime }。
|
|
180
|
-
* 失败返回 null
|
|
332
|
+
* 失败返回 null,并把 `lastError` 写在 w 上(调用方据此报「读不到云端」而不是「云端是空的」,
|
|
333
|
+
* 且能说出到底是 401、404 还是服务不支持 PROPFIND —— 0.6.48 起)。
|
|
181
334
|
*/
|
|
182
335
|
export async function listRemote(w, relDir = '') {
|
|
183
336
|
const url = remoteUrlFor(w, relDir)
|
|
@@ -193,7 +346,13 @@ export async function listRemote(w, relDir = '') {
|
|
|
193
346
|
}, 45000)
|
|
194
347
|
if (!res.ok && res.status !== 207) {
|
|
195
348
|
// 404 = 目录还不存在,这是正常的「首次同步」,返回空表
|
|
196
|
-
if (res.status === 404)
|
|
349
|
+
if (res.status === 404) {
|
|
350
|
+
w.lastError = ''
|
|
351
|
+
w.lastStatus = 404
|
|
352
|
+
return { entries: new Map(), exists: false }
|
|
353
|
+
}
|
|
354
|
+
w.lastError = explainStatus(res.status, w)
|
|
355
|
+
w.lastStatus = res.status
|
|
197
356
|
return null
|
|
198
357
|
}
|
|
199
358
|
const xml = await withBodyTimeout(res.text(), 60000, `PROPFIND 响应`)
|
|
@@ -202,8 +361,16 @@ export async function listRemote(w, relDir = '') {
|
|
|
202
361
|
// 服务端回的 href 里带着那段前缀,只拿 dir 去比 parent 永远对不上 → 列目录恒为空,
|
|
203
362
|
// 后果是 pull 报「云端还是空的」、push 每轮全量重传。
|
|
204
363
|
const base = requestPathBase(url, w, relDir)
|
|
364
|
+
w.lastError = ''
|
|
365
|
+
w.lastStatus = res.status
|
|
205
366
|
return { entries: parsePropfind(xml, w, base), exists: true }
|
|
206
|
-
} catch {
|
|
367
|
+
} catch (e) {
|
|
368
|
+
// 超时 / 连接被拒 / 证书不受信:原因各不一样,别一律说成「认证失败」
|
|
369
|
+
const msg = String((e && e.message) || e || '')
|
|
370
|
+
w.lastStatus = 0
|
|
371
|
+
w.lastError = /abort|timeout|超时/i.test(msg)
|
|
372
|
+
? `PROPFIND 超时(45s 内没有响应):${url} / PROPFIND timed out (no response in 45s)`
|
|
373
|
+
: `连不上服务器:${msg || url} / Cannot reach the server`
|
|
207
374
|
return null
|
|
208
375
|
}
|
|
209
376
|
}
|
|
@@ -383,6 +550,12 @@ const SELF_RUNTIME_FILES = new Set([
|
|
|
383
550
|
'restore.ps1', 'sync.ps1', 'webdav.mjs', 'sync-engine.mjs',
|
|
384
551
|
])
|
|
385
552
|
const GH_TOKEN_RE = /gh[pousr]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,}/
|
|
553
|
+
// 0.6.49:SSH / 其它私钥。原来只拦 `dsh-ssh-master.key` 这种自家文件名,
|
|
554
|
+
// `ssh-keygen` 的默认产物(id_ed25519 / id_rsa …)是裸名,既没有 .key 后缀也不在名单里,
|
|
555
|
+
// 一旦用户把 ~/.ssh 加进「额外路径」,私钥会被原样传上云端(自检实测抓到的)。
|
|
556
|
+
export const SSH_KEY_NAME_RE = /^(id_(?:rsa|dsa|ecdsa|ed25519)(?:_sk)?|identity|.*\.ppk)$/i
|
|
557
|
+
// 内容判据兜底:改名/塞进别处的私钥也认得出(PEM 与 PuTTY 两种头)
|
|
558
|
+
export const PRIVATE_KEY_BODY_RE = /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----|PuTTY-User-Key-File-[0-9]/
|
|
386
559
|
|
|
387
560
|
/**
|
|
388
561
|
* 上传前的拦截判定,**带原因**。
|
|
@@ -397,6 +570,7 @@ const GH_TOKEN_RE = /gh[pousr]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,}/
|
|
|
397
570
|
export function secretSkipReason(rel, buf) {
|
|
398
571
|
const leaf = String(rel || '').split('/').pop().toLowerCase()
|
|
399
572
|
if (PRIVATE_SECRET_FILES.has(leaf) || leaf.startsWith('.env.') || /\.(pem|key|p12|pfx)$/.test(leaf)) return 'secret'
|
|
573
|
+
if (SSH_KEY_NAME_RE.test(leaf)) return 'secret'
|
|
400
574
|
// 浏览器剖面 / 凭据库:无论它是怎么进到仓库里的(老版本抓的、手动拷的),都不上传
|
|
401
575
|
if (blockedProfilePath(rel)) return 'profile'
|
|
402
576
|
// 超大文件不上传:NAS 扛不住,且这类体积基本是缓存/数据库(不是安全问题,别冤枉用户的令牌)
|
|
@@ -408,6 +582,7 @@ export function secretSkipReason(rel, buf) {
|
|
|
408
582
|
if (slice.includes(0)) return ''
|
|
409
583
|
const text = slice.toString('utf8')
|
|
410
584
|
if (GH_TOKEN_RE.test(text)) return 'secret'
|
|
585
|
+
if (PRIVATE_KEY_BODY_RE.test(text)) return 'secret'
|
|
411
586
|
for (const envName of ['DSH_CONFIG_SYNC_GH_TOKEN', 'GITHUB_TOKEN', 'GH_TOKEN']) {
|
|
412
587
|
const val = String(process.env[envName] || '').trim()
|
|
413
588
|
if (val.length >= 12 && text.includes(val)) return 'secret'
|
|
@@ -453,7 +628,7 @@ export async function uploadRepo(w, localRepo, { dryRun = false, onProgress = nu
|
|
|
453
628
|
// 现在改为:递归列远端全部文件 + 逐个比 sha256,内容真相同才跳过。
|
|
454
629
|
const remote = await listRemote(w, '')
|
|
455
630
|
if (!remote) {
|
|
456
|
-
return { ok: false, uploaded, skipped, errors: [...errors,
|
|
631
|
+
return { ok: false, uploaded, skipped, errors: [...errors, `读不到云端目录(PROPFIND 失败):${w.lastError || '未知原因'} / Cannot list the cloud folder`] }
|
|
457
632
|
}
|
|
458
633
|
|
|
459
634
|
const remoteMeta = remote.exists ? await listRemoteMeta(w, '') : new Map()
|
|
@@ -539,7 +714,7 @@ export async function downloadRepo(w, localRepo, { dryRun = false } = {}) {
|
|
|
539
714
|
|
|
540
715
|
const remote = await listRemote(w, '')
|
|
541
716
|
if (!remote) {
|
|
542
|
-
return { ok: false, downloaded, skipped, conflicts, errors: [
|
|
717
|
+
return { ok: false, downloaded, skipped, conflicts, errors: [`读不到云端目录(PROPFIND 失败):${w.lastError || '未知原因'} / Cannot list the cloud folder`] }
|
|
543
718
|
}
|
|
544
719
|
if (!remote.exists) {
|
|
545
720
|
return { ok: true, downloaded, skipped, conflicts, errors: [], empty: true }
|
|
@@ -682,12 +857,23 @@ function isSafeRemoteRel(rel) {
|
|
|
682
857
|
|
|
683
858
|
/** 连通性测试(面板「测试连接」与探云端是否为空共用)。 */
|
|
684
859
|
export async function testConnection(w) {
|
|
685
|
-
if (!w.enabled) return { ok: false, error: '未配置 WebDAV 地址' }
|
|
860
|
+
if (!w.enabled) return { ok: false, error: '未配置 WebDAV 地址 / WebDAV URL is not set' }
|
|
686
861
|
if (!isSecureUrl(w.url)) {
|
|
687
|
-
return { ok: false, error: '地址不是 https(明文传输密码有风险);确需使用请设 DSH_SYNC_ALLOW_INSECURE=1'
|
|
862
|
+
return { ok: false, error: '地址不是 https(明文传输密码有风险);确需使用请设 DSH_SYNC_ALLOW_INSECURE=1'
|
|
863
|
+
+ ' / Not https (credentials would travel in clear text); set DSH_SYNC_ALLOW_INSECURE=1 to allow it' }
|
|
688
864
|
}
|
|
689
865
|
const res = await listRemote(w, '')
|
|
690
|
-
|
|
866
|
+
// 0.6.48:失败要说清是哪一类(401/403/404/405/超时/证书),并把用到的 UA 一起报出来 ——
|
|
867
|
+
// 排查「服务按客户端过滤」时,第一件事就是确认我们发出去的到底是什么。
|
|
868
|
+
if (!res) {
|
|
869
|
+
return {
|
|
870
|
+
ok: false,
|
|
871
|
+
error: String(w.lastError || '连不上或认证失败(PROPFIND 无响应) / Cannot reach the server or auth failed (PROPFIND gave no answer)'),
|
|
872
|
+
url: w.url,
|
|
873
|
+
userAgent: w.ua || '',
|
|
874
|
+
status: Number(w.lastStatus || 0),
|
|
875
|
+
}
|
|
876
|
+
}
|
|
691
877
|
const dirs = res.exists ? await listRemoteDirs(w, '') : []
|
|
692
878
|
return {
|
|
693
879
|
ok: true,
|
|
@@ -696,6 +882,7 @@ export async function testConnection(w) {
|
|
|
696
882
|
rootFiles: res.entries.size,
|
|
697
883
|
rootDirs: dirs.length,
|
|
698
884
|
url: w.url,
|
|
885
|
+
userAgent: w.ua || '',
|
|
699
886
|
}
|
|
700
887
|
}
|
|
701
888
|
|
|
@@ -754,6 +941,38 @@ export async function deletePrefixes(w, prefixes = []) {
|
|
|
754
941
|
return { ok: errors.length === 0, deleted, errors }
|
|
755
942
|
}
|
|
756
943
|
|
|
944
|
+
/** 云端必须被清掉的「历史脏数据」前缀:新版不再同步的浏览器剖面(含 Login Data / Cookies)。 */
|
|
945
|
+
export const FORBIDDEN_CLOUD_PREFIXES = ['plugin-data/browser-profiles', 'plugin-data/User Data', 'plugin-data/user data']
|
|
946
|
+
|
|
947
|
+
/**
|
|
948
|
+
* 推送时顺带清掉云端的历史锁文件:`conversations/sessions/<目录>/session.lock`(旧版连运行期锁一起传了)。
|
|
949
|
+
*
|
|
950
|
+
* 这些是运行期标记(哪个进程正打开这个会话),0.6.49 之前被一并抓进仓库上传了。
|
|
951
|
+
* 铺回另一台机器就成了一条指向不存在 pid 的陈旧锁,所以按后缀精确删,不动别的东西。
|
|
952
|
+
*/
|
|
953
|
+
export async function purgeStaleLocksFromCloud(w) {
|
|
954
|
+
const deleted = [], errors = []
|
|
955
|
+
if (!w || !w.enabled) return { ok: true, deleted, errors }
|
|
956
|
+
const meta = await listRemoteMeta(w, '')
|
|
957
|
+
if (!meta || typeof meta.keys !== 'function') return { ok: true, deleted, errors }
|
|
958
|
+
for (const k of meta.keys()) {
|
|
959
|
+
if (!/(^|\/)session\.lock$/.test(String(k))) continue
|
|
960
|
+
const r = await deleteRemote(w, k)
|
|
961
|
+
if (r && r.ok) deleted.push(k)
|
|
962
|
+
else errors.push(`${k}: ${(r && (r.error || r.status)) || '删除失败'}`)
|
|
963
|
+
}
|
|
964
|
+
return { ok: errors.length === 0, deleted, errors }
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
export async function purgeForbiddenFromCloud(w, prefixes = FORBIDDEN_CLOUD_PREFIXES) {
|
|
968
|
+
const deleted = [], errors = []
|
|
969
|
+
if (!w || !w.enabled) return { ok: true, deleted, errors }
|
|
970
|
+
const r = await deletePrefixes(w, prefixes)
|
|
971
|
+
deleted.push(...r.deleted)
|
|
972
|
+
errors.push(...r.errors)
|
|
973
|
+
return { ok: errors.length === 0, deleted, errors }
|
|
974
|
+
}
|
|
975
|
+
|
|
757
976
|
export async function runWebdavCli(argv) {
|
|
758
977
|
const [cmd, ...rest] = argv
|
|
759
978
|
const a = parseCliArgs(rest)
|
|
@@ -789,6 +1008,10 @@ export async function runWebdavCli(argv) {
|
|
|
789
1008
|
}
|
|
790
1009
|
},
|
|
791
1010
|
})
|
|
1011
|
+
const purge = await purgeForbiddenFromCloud(w)
|
|
1012
|
+
const lockPurge = await purgeStaleLocksFromCloud(w)
|
|
1013
|
+
if (purge.deleted.length) console.log(`云端清理:删除 ${purge.deleted.length} 个历史文件(浏览器剖面)`)
|
|
1014
|
+
if (lockPurge.deleted.length) console.log(`云端清理:删除 ${lockPurge.deleted.length} 个历史 session.lock(陈旧锁)`)
|
|
792
1015
|
console.log(`WebDAV 上传:上传 ${r.uploaded.length} · 跳过 ${r.skipped.length} · 错误 ${r.errors.length}`)
|
|
793
1016
|
for (const e of r.errors.slice(0, 20)) console.error(` [!] ${e}`)
|
|
794
1017
|
return r.ok ? 0 : 1
|
package/runtime/zip.mjs
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
// 最小 ZIP 读写 —— 只为「本地源码插件」那一组用(打包成 `local-plugins/<名字>.zip`,换机解回去)。
|
|
2
|
+
//
|
|
3
|
+
// 为什么不引第三方包:插件本身是零依赖的(只能 import node:*),也不该为了打个 zip 拉一个库进来。
|
|
4
|
+
// 为什么不只发 .tgz:另一台机器可能是 Windows,那边 apply.ps1 用 Expand-Archive 只会解 zip。
|
|
5
|
+
//
|
|
6
|
+
// 支持范围(够用就行,不做 zip64 / 加密 / 多卷):
|
|
7
|
+
// - 写:deflate(method 8),压不动就存(method 0),UTF-8 文件名(bit 11)
|
|
8
|
+
// - 读:method 0 / 8,按中央目录读,跳过目录项
|
|
9
|
+
|
|
10
|
+
import { deflateRawSync, inflateRawSync } from 'node:zlib'
|
|
11
|
+
import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
|
|
12
|
+
import { dirname, join } from 'node:path'
|
|
13
|
+
|
|
14
|
+
const CRC_TABLE = (() => {
|
|
15
|
+
const table = new Int32Array(256)
|
|
16
|
+
for (let i = 0; i < 256; i += 1) {
|
|
17
|
+
let c = i
|
|
18
|
+
for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1
|
|
19
|
+
table[i] = c
|
|
20
|
+
}
|
|
21
|
+
return table
|
|
22
|
+
})()
|
|
23
|
+
|
|
24
|
+
export function crc32(buf) {
|
|
25
|
+
let c = 0 ^ -1
|
|
26
|
+
for (let i = 0; i < buf.length; i += 1) c = (c >>> 8) ^ CRC_TABLE[(c ^ buf[i]) & 0xff]
|
|
27
|
+
return (c ^ -1) >>> 0
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** 当前时间转 MS-DOS 的 (date, time) 两个 16 位整数。 */
|
|
31
|
+
function dosStamp(d = new Date()) {
|
|
32
|
+
const year = Math.max(1980, d.getFullYear())
|
|
33
|
+
const date = ((year - 1980) << 9) | ((d.getMonth() + 1) << 5) | d.getDate()
|
|
34
|
+
const time = (d.getHours() << 11) | (d.getMinutes() << 5) | (d.getSeconds() >> 1)
|
|
35
|
+
return { date, time }
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* 打包。
|
|
40
|
+
* @param {{name:string, data:Buffer, mtime?:Date}[]} entries name 用 `/` 分隔、相对归档根
|
|
41
|
+
* @returns {Buffer}
|
|
42
|
+
*/
|
|
43
|
+
export function zipBuild(entries) {
|
|
44
|
+
const locals = []
|
|
45
|
+
const centrals = []
|
|
46
|
+
let offset = 0
|
|
47
|
+
for (const entry of entries) {
|
|
48
|
+
const nameBuf = Buffer.from(String(entry.name).replace(/\\/g, '/'), 'utf8')
|
|
49
|
+
const data = Buffer.isBuffer(entry.data) ? entry.data : Buffer.from(entry.data || '')
|
|
50
|
+
const crc = crc32(data)
|
|
51
|
+
const deflated = deflateRawSync(data)
|
|
52
|
+
const useDeflate = deflated.length < data.length
|
|
53
|
+
const body = useDeflate ? deflated : data
|
|
54
|
+
const method = useDeflate ? 8 : 0
|
|
55
|
+
const { date, time } = dosStamp(entry.mtime instanceof Date ? entry.mtime : new Date())
|
|
56
|
+
|
|
57
|
+
const local = Buffer.alloc(30)
|
|
58
|
+
local.writeUInt32LE(0x04034b50, 0)
|
|
59
|
+
local.writeUInt16LE(20, 4) // version needed
|
|
60
|
+
local.writeUInt16LE(0x0800, 6) // UTF-8 文件名
|
|
61
|
+
local.writeUInt16LE(method, 8)
|
|
62
|
+
local.writeUInt16LE(time, 10)
|
|
63
|
+
local.writeUInt16LE(date, 12)
|
|
64
|
+
local.writeUInt32LE(crc, 14)
|
|
65
|
+
local.writeUInt32LE(body.length, 18)
|
|
66
|
+
local.writeUInt32LE(data.length, 22)
|
|
67
|
+
local.writeUInt16LE(nameBuf.length, 26)
|
|
68
|
+
local.writeUInt16LE(0, 28) // extra
|
|
69
|
+
locals.push(local, nameBuf, body)
|
|
70
|
+
|
|
71
|
+
const central = Buffer.alloc(46)
|
|
72
|
+
central.writeUInt32LE(0x02014b50, 0)
|
|
73
|
+
central.writeUInt16LE(20, 4) // version made by
|
|
74
|
+
central.writeUInt16LE(20, 6) // version needed
|
|
75
|
+
central.writeUInt16LE(0x0800, 8)
|
|
76
|
+
central.writeUInt16LE(method, 10)
|
|
77
|
+
central.writeUInt16LE(time, 12)
|
|
78
|
+
central.writeUInt16LE(date, 14)
|
|
79
|
+
central.writeUInt32LE(crc, 16)
|
|
80
|
+
central.writeUInt32LE(body.length, 20)
|
|
81
|
+
central.writeUInt32LE(data.length, 24)
|
|
82
|
+
central.writeUInt16LE(nameBuf.length, 28)
|
|
83
|
+
central.writeUInt16LE(0, 30) // extra len
|
|
84
|
+
central.writeUInt16LE(0, 32) // comment len
|
|
85
|
+
central.writeUInt16LE(0, 34) // disk start
|
|
86
|
+
central.writeUInt16LE(0, 36) // internal attrs
|
|
87
|
+
central.writeUInt32LE(0, 38) // external attrs
|
|
88
|
+
central.writeUInt32LE(offset, 42) // local header offset
|
|
89
|
+
centrals.push(central, nameBuf)
|
|
90
|
+
|
|
91
|
+
offset += local.length + nameBuf.length + body.length
|
|
92
|
+
}
|
|
93
|
+
const centralBuf = Buffer.concat(centrals)
|
|
94
|
+
const end = Buffer.alloc(22)
|
|
95
|
+
end.writeUInt32LE(0x06054b50, 0)
|
|
96
|
+
end.writeUInt16LE(0, 4)
|
|
97
|
+
end.writeUInt16LE(0, 6)
|
|
98
|
+
end.writeUInt16LE(entries.length, 8)
|
|
99
|
+
end.writeUInt16LE(entries.length, 10)
|
|
100
|
+
end.writeUInt32LE(centralBuf.length, 12)
|
|
101
|
+
end.writeUInt32LE(offset, 16)
|
|
102
|
+
end.writeUInt16LE(0, 20)
|
|
103
|
+
return Buffer.concat([...locals, centralBuf, end])
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** 从 EOCD 找到中央目录的位置(容忍尾部注释)。 */
|
|
107
|
+
function findEocd(buf) {
|
|
108
|
+
const min = Math.max(0, buf.length - 22 - 0xffff)
|
|
109
|
+
for (let i = buf.length - 22; i >= min; i -= 1) {
|
|
110
|
+
if (buf.readUInt32LE(i) === 0x06054b50) return i
|
|
111
|
+
}
|
|
112
|
+
return -1
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* 解包到目录。
|
|
117
|
+
* @returns {{files:number, names:string[]}}
|
|
118
|
+
*/
|
|
119
|
+
export function zipExtract(buf, destDir) {
|
|
120
|
+
const eocd = findEocd(buf)
|
|
121
|
+
if (eocd < 0) throw new Error('不是 zip 文件(找不到中央目录结尾)')
|
|
122
|
+
const count = buf.readUInt16LE(eocd + 10)
|
|
123
|
+
let p = buf.readUInt32LE(eocd + 16)
|
|
124
|
+
let files = 0
|
|
125
|
+
const names = []
|
|
126
|
+
for (let i = 0; i < count; i += 1) {
|
|
127
|
+
if (buf.readUInt32LE(p) !== 0x02014b50) throw new Error(`中央目录项 ${i} 标记不对`)
|
|
128
|
+
const method = buf.readUInt16LE(p + 10)
|
|
129
|
+
const crcExpect = buf.readUInt32LE(p + 16)
|
|
130
|
+
const compSize = buf.readUInt32LE(p + 20)
|
|
131
|
+
const nameLen = buf.readUInt16LE(p + 28)
|
|
132
|
+
const extraLen = buf.readUInt16LE(p + 30)
|
|
133
|
+
const commentLen = buf.readUInt16LE(p + 32)
|
|
134
|
+
const localOffset = buf.readUInt32LE(p + 42)
|
|
135
|
+
const name = buf.subarray(p + 46, p + 46 + nameLen).toString('utf8')
|
|
136
|
+
p += 46 + nameLen + extraLen + commentLen
|
|
137
|
+
|
|
138
|
+
if (name.endsWith('/')) continue
|
|
139
|
+
// 防目录穿越:解出来的路径必须落在 destDir 里
|
|
140
|
+
const target = join(destDir, ...name.split('/'))
|
|
141
|
+
if (!target.startsWith(destDir)) throw new Error(`归档里有可疑路径:${name}`)
|
|
142
|
+
|
|
143
|
+
if (buf.readUInt32LE(localOffset) !== 0x04034b50) throw new Error(`本地头标记不对:${name}`)
|
|
144
|
+
const lNameLen = buf.readUInt16LE(localOffset + 26)
|
|
145
|
+
const lExtraLen = buf.readUInt16LE(localOffset + 28)
|
|
146
|
+
const dataStart = localOffset + 30 + lNameLen + lExtraLen
|
|
147
|
+
const body = buf.subarray(dataStart, dataStart + compSize)
|
|
148
|
+
const data = method === 0 ? Buffer.from(body) : inflateRawSync(body)
|
|
149
|
+
if (crc32(data) !== crcExpect) throw new Error(`CRC 校验失败:${name}`)
|
|
150
|
+
if (!existsSync(dirname(target))) mkdirSync(dirname(target), { recursive: true })
|
|
151
|
+
writeFileSync(target, data)
|
|
152
|
+
files += 1
|
|
153
|
+
names.push(name)
|
|
154
|
+
}
|
|
155
|
+
return { files, names }
|
|
156
|
+
}
|