dsh-profile-config-sync 0.4.1 → 0.6.40
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/LICENSE +2 -1
- package/README.en.md +167 -738
- package/README.md +238 -571
- package/client.js +721 -269
- package/cordis.patch.yml +1 -1
- package/docs/CHANGELOG.en.md +28 -0
- package/docs/CHANGELOG.md +80 -0
- package/docs/HISTORY.en.md +221 -0
- package/docs/HISTORY.md +252 -0
- package/docs/MULTI-PLATFORM.md +165 -0
- package/docs/REFERENCE.md +172 -0
- package/index.js +1247 -190
- package/package.json +11 -5
- package/runtime/apply.ps1 +79 -33
- package/runtime/atomic-write.mjs +57 -0
- package/runtime/capture.ps1 +188 -37
- package/runtime/contract.mjs +59 -7
- package/runtime/dsh-sync-common.ps1 +361 -22
- package/runtime/install-plugin.ps1 +94 -3
- package/runtime/live-log.mjs +75 -0
- package/runtime/platform.mjs +35 -0
- package/runtime/post-exit.ps1 +201 -28
- package/runtime/restore.ps1 +76 -8
- package/runtime/sync-engine.mjs +1324 -857
- package/runtime/sync.ps1 +192 -82
- package/runtime/tools/fix-session-cwd.mjs +12 -3
- package/runtime/tools/workspace-view.mjs +7 -3
- package/runtime/webdav.mjs +269 -23
package/runtime/webdav.mjs
CHANGED
|
@@ -115,9 +115,24 @@ async function request(url, w, init = {}, timeoutMs = 30000) {
|
|
|
115
115
|
}
|
|
116
116
|
}
|
|
117
117
|
|
|
118
|
+
/**
|
|
119
|
+
* 读完响应体,带**独立**超时。
|
|
120
|
+
*
|
|
121
|
+
* fetch 的超时(request() 里的 AbortController)只管到「响应头到手」,之后 body 卡住不会再有超时:
|
|
122
|
+
* 实测遇到服务端先回 200 再停住不发的 PROPFIND,整条同步流水线就永久挂着(进程不退、面板一直转)。
|
|
123
|
+
* 所以读 body 单独计时。
|
|
124
|
+
*/
|
|
125
|
+
function withBodyTimeout(promise, timeoutMs = 30000, label = '读取响应体') {
|
|
126
|
+
let timer = null
|
|
127
|
+
const timeout = new Promise((_, reject) => {
|
|
128
|
+
timer = setTimeout(() => reject(new Error(`${label}超时(${Math.round(timeoutMs / 1000)}s)`)), timeoutMs)
|
|
129
|
+
})
|
|
130
|
+
return Promise.race([promise, timeout]).finally(() => { if (timer) clearTimeout(timer) })
|
|
131
|
+
}
|
|
132
|
+
|
|
118
133
|
/** 文本响应(错误信息里要带服务端原文,便于定位)。 */
|
|
119
134
|
async function textOf(res) {
|
|
120
|
-
try { return (await res.text()).slice(0, 400) } catch { return '' }
|
|
135
|
+
try { return (await withBodyTimeout(res.text(), 30000, '读取错误响应')).slice(0, 400) } catch { return '' }
|
|
121
136
|
}
|
|
122
137
|
|
|
123
138
|
/**
|
|
@@ -181,10 +196,12 @@ export async function listRemote(w, relDir = '') {
|
|
|
181
196
|
if (res.status === 404) return { entries: new Map(), exists: false }
|
|
182
197
|
return null
|
|
183
198
|
}
|
|
184
|
-
const xml = await res.text()
|
|
185
|
-
//
|
|
186
|
-
|
|
187
|
-
|
|
199
|
+
const xml = await withBodyTimeout(res.text(), 60000, `PROPFIND 响应`)
|
|
200
|
+
// 解析基准必须是**请求 URL 的真实路径**,不能只用 w.dir:
|
|
201
|
+
// WebDAV 根经常带路径前缀(Nextcloud 的 /remote.php/dav/files/<user>、坚果云的 /dav、Alist 的 /dav),
|
|
202
|
+
// 服务端回的 href 里带着那段前缀,只拿 dir 去比 parent 永远对不上 → 列目录恒为空,
|
|
203
|
+
// 后果是 pull 报「云端还是空的」、push 每轮全量重传。
|
|
204
|
+
const base = requestPathBase(url, w, relDir)
|
|
188
205
|
return { entries: parsePropfind(xml, w, base), exists: true }
|
|
189
206
|
} catch {
|
|
190
207
|
return null
|
|
@@ -212,7 +229,15 @@ function parsePropfind(xml, w, relDir) {
|
|
|
212
229
|
if (!clean) continue
|
|
213
230
|
const lastSlash = clean.lastIndexOf('/')
|
|
214
231
|
const parent = lastSlash >= 0 ? clean.slice(0, lastSlash) : ''
|
|
215
|
-
|
|
232
|
+
// 基准对齐:正常情况 parent 精确等于基准;反向代理把路径改写成别的前缀时,
|
|
233
|
+
// 两者可能互为后缀(请求 /dav/dsh-config-sync,href 却是 /dsh-config-sync/x),也认。
|
|
234
|
+
// 直接返回「不带斜杠的相对 href」时 parent 为空,同样属于当前目录。
|
|
235
|
+
const flat = lastSlash < 0
|
|
236
|
+
const sameDir = flat
|
|
237
|
+
|| parent === baseDir
|
|
238
|
+
|| (baseDir && parent.endsWith('/' + baseDir))
|
|
239
|
+
|| (parent && baseDir.endsWith('/' + parent))
|
|
240
|
+
if (!sameDir) continue
|
|
216
241
|
const name = lastSlash >= 0 ? clean.slice(lastSlash + 1) : clean
|
|
217
242
|
if (!name) continue
|
|
218
243
|
// 目录(collection)跳过:我们只同步文件
|
|
@@ -238,6 +263,20 @@ function normalizeHrefs(p) {
|
|
|
238
263
|
return String(p).replace(/\/{2,}/g, '/').replace(/^\/+|\/+$/g, '')
|
|
239
264
|
}
|
|
240
265
|
|
|
266
|
+
/**
|
|
267
|
+
* PROPFIND 响应里的 href 是「服务端视角的绝对路径」,可能带着 WebDAV 根的路径前缀。
|
|
268
|
+
* 解析基准必须取自**本次请求 URL 的真实路径**,不能用 w.dir:带前缀的服务器
|
|
269
|
+
* (Nextcloud / 坚果云 / Alist)会因此一个子目录都列不出来。
|
|
270
|
+
*/
|
|
271
|
+
function requestPathBase(url, w, relDir) {
|
|
272
|
+
try {
|
|
273
|
+
return normalizeHrefs(decodeURIComponent(new URL(url).pathname))
|
|
274
|
+
} catch {
|
|
275
|
+
return [String(w && w.dir ? w.dir : '').replace(/^\/+|\/+$/g, ''), String(relDir || '').replace(/^\/+|\/+$/g, '')]
|
|
276
|
+
.filter(Boolean).join('/')
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
241
280
|
/** 取某个标签的内容(容忍前缀)。 */
|
|
242
281
|
function matchTag(block, tag) {
|
|
243
282
|
const re = new RegExp(`<(?:\\w+:)?${tag}(?:\\s[^>]*)?>([\\s\\S]*?)</(?:\\w+:)?${tag}>`, 'i')
|
|
@@ -267,7 +306,7 @@ export async function getFile(w, relPath) {
|
|
|
267
306
|
try {
|
|
268
307
|
const res = await request(url, w, {}, 120000)
|
|
269
308
|
if (!res.ok) return null
|
|
270
|
-
const buf = Buffer.from(await res.arrayBuffer())
|
|
309
|
+
const buf = Buffer.from(await withBodyTimeout(res.arrayBuffer(), 120000, `下载响应`))
|
|
271
310
|
return buf
|
|
272
311
|
} catch {
|
|
273
312
|
return null
|
|
@@ -303,7 +342,90 @@ export function listLocalFiles(root) {
|
|
|
303
342
|
return out
|
|
304
343
|
}
|
|
305
344
|
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* 浏览器剖面 / 凭据库:这些东西一旦进仓库就等于把登录态搬走了。
|
|
348
|
+
* 需要的只是插件的小配置,不需要整份 Edge/Chrome 用户目录。
|
|
349
|
+
* browser-profiles —— 插件把 CDP 用的剖面存在这里(本机实测 297 MB、3,696 个文件);
|
|
350
|
+
* User Data —— Chromium 系默认剖面目录名;
|
|
351
|
+
* Login Data / Cookies / Web Data / Secure Preferences / Local State / History —— 密码库、
|
|
352
|
+
* 登录态、自动填充、受保护设置、浏览器主库。
|
|
353
|
+
* 只看路径段(不区分大小写),所以深层嵌套也拦得住。
|
|
354
|
+
*/
|
|
355
|
+
const BLOCKED_PROFILE_SEGMENTS = new Set([
|
|
356
|
+
'browser-profiles', 'user data', 'login data', 'login data for account',
|
|
357
|
+
'cookies', 'cookies-journal', 'web data', 'web data-journal', 'secure preferences',
|
|
358
|
+
'local state', 'history', 'history-journal', 'top sites', 'current session', 'current tabs',
|
|
359
|
+
])
|
|
360
|
+
/** 单文件上限:超过就别传(NAS 与 git 都受不了,且这类文件基本是缓存/数据库)。 */
|
|
361
|
+
const MAX_SYNC_FILE_BYTES = 32 * 1024 * 1024
|
|
362
|
+
|
|
363
|
+
function blockedProfilePath(rel) {
|
|
364
|
+
const parts = String(rel || '').split('/').filter(Boolean)
|
|
365
|
+
return parts.some((seg) => BLOCKED_PROFILE_SEGMENTS.has(String(seg).toLowerCase()))
|
|
366
|
+
}
|
|
367
|
+
const PRIVATE_SECRET_FILES = new Set([
|
|
368
|
+
'config-sync-gh.json',
|
|
369
|
+
'config-sync-feedback-outbox.json',
|
|
370
|
+
'dsh-config-sync.json',
|
|
371
|
+
'config-sync-state.json',
|
|
372
|
+
'config-sync-roots.json',
|
|
373
|
+
'config-sync-scope.json',
|
|
374
|
+
'config-sync-delete-cloud.json',
|
|
375
|
+
'config-sync-extra.json',
|
|
376
|
+
'sync-notices.json',
|
|
377
|
+
'.credentials.yaml',
|
|
378
|
+
'.env',
|
|
379
|
+
'dsh-ssh-master.key',
|
|
380
|
+
])
|
|
381
|
+
const SELF_RUNTIME_FILES = new Set([
|
|
382
|
+
'apply.ps1', 'capture.ps1', 'dsh-sync-common.ps1', 'post-exit.ps1',
|
|
383
|
+
'restore.ps1', 'sync.ps1', 'webdav.mjs', 'sync-engine.mjs',
|
|
384
|
+
])
|
|
385
|
+
const GH_TOKEN_RE = /gh[pousr]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,}/
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* 上传前的拦截判定,**带原因**。
|
|
389
|
+
*
|
|
390
|
+
* 以前只返回 true/false,调用方统一打印「安全拦截:跳过含令牌或本机私有凭据的文件」。
|
|
391
|
+
* 但「体积超过 32MB」和「浏览器剖面」都不是凭据问题,用同一句话会把用户吓去查令牌 ——
|
|
392
|
+
* 实测一个 40MB 的插件数据文件会得到「含令牌」的指控。所以这里把原因分开:
|
|
393
|
+
* secret —— 真的像凭据(文件名/内容命中)
|
|
394
|
+
* profile —— 浏览器剖面 / 凭据库(Login Data、Cookies…)
|
|
395
|
+
* too-big —— 超过单文件上限,不是安全问题,只是不该走 WebDAV
|
|
396
|
+
*/
|
|
397
|
+
export function secretSkipReason(rel, buf) {
|
|
398
|
+
const leaf = String(rel || '').split('/').pop().toLowerCase()
|
|
399
|
+
if (PRIVATE_SECRET_FILES.has(leaf) || leaf.startsWith('.env.') || /\.(pem|key|p12|pfx)$/.test(leaf)) return 'secret'
|
|
400
|
+
// 浏览器剖面 / 凭据库:无论它是怎么进到仓库里的(老版本抓的、手动拷的),都不上传
|
|
401
|
+
if (blockedProfilePath(rel)) return 'profile'
|
|
402
|
+
// 超大文件不上传:NAS 扛不住,且这类体积基本是缓存/数据库(不是安全问题,别冤枉用户的令牌)
|
|
403
|
+
if (buf && buf.length > MAX_SYNC_FILE_BYTES) return 'too-big'
|
|
404
|
+
// 插件自己的运行脚本不拦(它们本身就含 env 名,容易命中下面的内容扫描)
|
|
405
|
+
if (SELF_RUNTIME_FILES.has(String(rel || '').replace(/^\.\//, ''))) return ''
|
|
406
|
+
if (!buf || buf.length > 8 * 1024 * 1024) return ''
|
|
407
|
+
const slice = buf.subarray(0, Math.min(buf.length, 65536))
|
|
408
|
+
if (slice.includes(0)) return ''
|
|
409
|
+
const text = slice.toString('utf8')
|
|
410
|
+
if (GH_TOKEN_RE.test(text)) return 'secret'
|
|
411
|
+
for (const envName of ['DSH_CONFIG_SYNC_GH_TOKEN', 'GITHUB_TOKEN', 'GH_TOKEN']) {
|
|
412
|
+
const val = String(process.env[envName] || '').trim()
|
|
413
|
+
if (val.length >= 12 && text.includes(val)) return 'secret'
|
|
414
|
+
}
|
|
415
|
+
return ''
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/** 兼容包装:只需要「拦不拦」的调用方继续用它。 */
|
|
419
|
+
function isSecretLeakCandidate(rel, buf) {
|
|
420
|
+
return secretSkipReason(rel, buf) !== ''
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
|
|
306
424
|
/** 文件内容哈希(用于判断是否需要上传/下载)。 */
|
|
425
|
+
export function isBlockedProfilePath(rel) { return blockedProfilePath(rel) }
|
|
426
|
+
export const BLOCKED_SEGMENTS = BLOCKED_PROFILE_SEGMENTS
|
|
427
|
+
export const MAX_FILE_BYTES = MAX_SYNC_FILE_BYTES
|
|
428
|
+
|
|
307
429
|
export function contentHash(buf) {
|
|
308
430
|
return createHash('sha256').update(buf).digest('hex')
|
|
309
431
|
}
|
|
@@ -315,7 +437,7 @@ export function contentHash(buf) {
|
|
|
315
437
|
* —— 那可能是另一台机器推上去的,删了就等于抢别人的配置。
|
|
316
438
|
* 返回 { ok, uploaded, skipped, errors }。
|
|
317
439
|
*/
|
|
318
|
-
export async function uploadRepo(w, localRepo, { dryRun = false } = {}) {
|
|
440
|
+
export async function uploadRepo(w, localRepo, { dryRun = false, onProgress = null } = {}) {
|
|
319
441
|
const uploaded = [], skipped = [], errors = []
|
|
320
442
|
if (!w.enabled) return { ok: false, uploaded, skipped, errors: ['WebDAV 未配置'] }
|
|
321
443
|
|
|
@@ -334,17 +456,30 @@ export async function uploadRepo(w, localRepo, { dryRun = false } = {}) {
|
|
|
334
456
|
return { ok: false, uploaded, skipped, errors: [...errors, '读不到云端目录(PROPFIND 失败)'] }
|
|
335
457
|
}
|
|
336
458
|
|
|
337
|
-
const
|
|
338
|
-
const
|
|
339
|
-
const
|
|
459
|
+
const remoteMeta = remote.exists ? await listRemoteMeta(w, '') : new Map()
|
|
460
|
+
const remoteSet = new Set(remoteMeta.keys())
|
|
461
|
+
const ensuredDirs = new Set()
|
|
340
462
|
|
|
341
463
|
const files = listLocalFiles(localRepo)
|
|
342
|
-
|
|
464
|
+
if (typeof onProgress === 'function') {
|
|
465
|
+
try { onProgress({ phase: 'scan', done: 0, total: files.length, uploaded: 0, skipped: 0, errors: 0 }) } catch { }
|
|
466
|
+
}
|
|
467
|
+
let lastReportAt = 0
|
|
468
|
+
for (let idx = 0; idx < files.length; idx++) {
|
|
469
|
+
const rel = files[idx]
|
|
343
470
|
let buf
|
|
344
471
|
try { buf = readFileSync(join(localRepo, fromRepoRel(rel))) } catch (e) {
|
|
345
472
|
errors.push(`${rel}: ${e && e.message ? e.message : e}`)
|
|
346
473
|
continue
|
|
347
474
|
}
|
|
475
|
+
const skipReason = secretSkipReason(rel, buf)
|
|
476
|
+
if (skipReason) {
|
|
477
|
+
skipped.push(rel)
|
|
478
|
+
if (skipReason === 'secret') console.log(` [!] 安全拦截:跳过含令牌或本机私有凭据的文件 ${rel}(绝不上传)`)
|
|
479
|
+
else if (skipReason === 'profile') console.log(` [!] 安全拦截:跳过浏览器剖面 / 凭据库文件 ${rel}(含登录态,绝不上传)`)
|
|
480
|
+
else console.log(` [!] 体积超限:${rel} 超过单文件上限 ${Math.round(MAX_SYNC_FILE_BYTES / 1048576)}MB,未上传(不是安全问题;需要它请用 git 模式)`)
|
|
481
|
+
continue
|
|
482
|
+
}
|
|
348
483
|
// 远端有同名文件:只在内容**真的**相同时跳过。
|
|
349
484
|
//
|
|
350
485
|
// 不能信 etag(审核实测):"强 etag"只保证对同一资源的表示唯一,不保证按内容算。
|
|
@@ -355,18 +490,39 @@ export async function uploadRepo(w, localRepo, { dryRun = false } = {}) {
|
|
|
355
490
|
const meta = remoteMeta.get(rel)
|
|
356
491
|
if (meta && meta.size === buf.length) {
|
|
357
492
|
const remoteBuf = await getFile(w, rel)
|
|
358
|
-
if (remoteBuf && contentHash(remoteBuf) === contentHash(buf)) {
|
|
493
|
+
if (remoteBuf && contentHash(remoteBuf) === contentHash(buf)) {
|
|
494
|
+
skipped.push(rel)
|
|
495
|
+
if (typeof onProgress === 'function') {
|
|
496
|
+
const now = Date.now()
|
|
497
|
+
if (idx + 1 === files.length || now - lastReportAt >= 1200) {
|
|
498
|
+
lastReportAt = now
|
|
499
|
+
try { onProgress({ phase: 'upload', done: idx + 1, total: files.length, uploaded: uploaded.length, skipped: skipped.length, errors: errors.length, current: rel }) } catch { }
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
continue
|
|
503
|
+
}
|
|
359
504
|
}
|
|
360
505
|
}
|
|
361
506
|
if (dryRun) { uploaded.push(rel); continue }
|
|
362
507
|
const dir = dirname(rel).split('/').filter(Boolean)
|
|
363
|
-
// 逐级建目录(WebDAV
|
|
508
|
+
// 逐级建目录(WebDAV 不自动建父级),同一会话内缓存已建路径避免重复 MKCOL
|
|
364
509
|
for (let i = 1; i <= dir.length; i++) {
|
|
365
|
-
|
|
510
|
+
const sub = dir.slice(0, i).join('/')
|
|
511
|
+
if (!ensuredDirs.has(sub)) {
|
|
512
|
+
const mr = await ensureRemoteDir(w, sub)
|
|
513
|
+
if (mr.ok) ensuredDirs.add(sub)
|
|
514
|
+
}
|
|
366
515
|
}
|
|
367
516
|
const r = await putFile(w, rel, buf)
|
|
368
517
|
if (r.ok) uploaded.push(rel)
|
|
369
518
|
else errors.push(`${rel}: ${r.error || r.status}`)
|
|
519
|
+
if (typeof onProgress === 'function') {
|
|
520
|
+
const now = Date.now()
|
|
521
|
+
if (idx + 1 === files.length || now - lastReportAt >= 1200) {
|
|
522
|
+
lastReportAt = now
|
|
523
|
+
try { onProgress({ phase: 'upload', done: idx + 1, total: files.length, uploaded: uploaded.length, skipped: skipped.length, errors: errors.length, current: rel }) } catch { }
|
|
524
|
+
}
|
|
525
|
+
}
|
|
370
526
|
}
|
|
371
527
|
return { ok: errors.length === 0, uploaded, skipped, errors, hashHint: files.length }
|
|
372
528
|
}
|
|
@@ -392,6 +548,11 @@ export async function downloadRepo(w, localRepo, { dryRun = false } = {}) {
|
|
|
392
548
|
// 递归列云端全部文件(PROPFIND Depth:1 只给一层,这里逐目录下钻)
|
|
393
549
|
const all = await listRemoteRecursive(w, '')
|
|
394
550
|
for (const rel of all) {
|
|
551
|
+
// 先判路径再取内容:越界路径连请求都不该发(`..` 会把 URL 拼成上一级,白拿一次 404)
|
|
552
|
+
if (!isSafeRemoteRel(rel)) {
|
|
553
|
+
errors.push(`${rel}: 云端返回了越界路径(可能指向仓库之外),已拒绝写入`)
|
|
554
|
+
continue
|
|
555
|
+
}
|
|
395
556
|
const buf = await getFile(w, rel)
|
|
396
557
|
if (!buf) { errors.push(`${rel}: 下载失败`); continue }
|
|
397
558
|
const localPath = join(localRepo, fromRepoRel(rel))
|
|
@@ -462,9 +623,9 @@ async function listRemoteDirs(w, relDir = '') {
|
|
|
462
623
|
}, 45000)
|
|
463
624
|
if (!res.ok && res.status !== 207) return []
|
|
464
625
|
if (res.status === 404) return []
|
|
465
|
-
const xml = await res.text()
|
|
466
|
-
|
|
467
|
-
|
|
626
|
+
const xml = await withBodyTimeout(res.text(), 60000, `PROPFIND 响应`)
|
|
627
|
+
// 与 listRemote 共用基准:必须取请求 URL 的真实路径,否则带前缀的 WebDAV 永远列不到子目录
|
|
628
|
+
const baseDir = requestPathBase(url, w, relDir)
|
|
468
629
|
const dirs = []
|
|
469
630
|
const blocks = String(xml).split(/<(?:\w+:)?response[\s>]/i).slice(1)
|
|
470
631
|
for (const block of blocks) {
|
|
@@ -477,7 +638,13 @@ async function listRemoteDirs(w, relDir = '') {
|
|
|
477
638
|
const lastSlash = clean.lastIndexOf('/')
|
|
478
639
|
const parent = lastSlash >= 0 ? clean.slice(0, lastSlash) : ''
|
|
479
640
|
const name = lastSlash >= 0 ? clean.slice(lastSlash + 1) : clean
|
|
480
|
-
|
|
641
|
+
// 反向代理改写前缀时,两者可能互为后缀;不带斜杠的裸 href 视为当前目录
|
|
642
|
+
const flat = lastSlash < 0
|
|
643
|
+
const sameDir = flat
|
|
644
|
+
|| parent === baseDir
|
|
645
|
+
|| (baseDir && parent.endsWith('/' + baseDir))
|
|
646
|
+
|| (parent && baseDir.endsWith('/' + parent))
|
|
647
|
+
if (!name || !sameDir) continue
|
|
481
648
|
const isCollection = /<(?:\w+:)?collection\s*\/?>/i.test(block)
|
|
482
649
|
if (isCollection) dirs.push(name)
|
|
483
650
|
}
|
|
@@ -497,6 +664,22 @@ function fromRepoRel(rel) {
|
|
|
497
664
|
return String(rel).split('/').join(SEP)
|
|
498
665
|
}
|
|
499
666
|
|
|
667
|
+
/**
|
|
668
|
+
* 远端给的相对路径必须真的留在仓库目录内。
|
|
669
|
+
*
|
|
670
|
+
* href 是服务端可控字符串:配置错误/恶意的 WebDAV(或被改写的反代)可以回
|
|
671
|
+
* `..%2F..%2Fevil.txt`,直接 join 就会写到仓库外面。这里按段判定,
|
|
672
|
+
* 越界(.. / 空段 / 绝对路径 / 盘符 / NUL)一律拒收。
|
|
673
|
+
*/
|
|
674
|
+
function isSafeRemoteRel(rel) {
|
|
675
|
+
const s = String(rel || '')
|
|
676
|
+
if (!s || s.length > 1024) return false
|
|
677
|
+
if (s.includes('\0')) return false
|
|
678
|
+
if (/^[\\/]/.test(s)) return false
|
|
679
|
+
if (/^[A-Za-z]:/.test(s)) return false
|
|
680
|
+
return !s.split(/[\\/]/).some((seg) => seg === '..' || seg === '')
|
|
681
|
+
}
|
|
682
|
+
|
|
500
683
|
/** 连通性测试(面板「测试连接」与探云端是否为空共用)。 */
|
|
501
684
|
export async function testConnection(w) {
|
|
502
685
|
if (!w.enabled) return { ok: false, error: '未配置 WebDAV 地址' }
|
|
@@ -531,19 +714,54 @@ function parseCliArgs(argv) {
|
|
|
531
714
|
return out
|
|
532
715
|
}
|
|
533
716
|
|
|
717
|
+
/** 只认识的参数;打错字(-DshHme)时明确提示,而不是静默用默认值跑错目录。 */
|
|
718
|
+
function warnUnknownArgs(args, known, usage) {
|
|
719
|
+
const extra = Object.keys(args).filter((k) => !known.includes(k))
|
|
720
|
+
if (!extra.length) return
|
|
721
|
+
console.error(`[!] 未知参数:${extra.map((k) => '-' + k).join(', ')}(已忽略;用法:${usage})`)
|
|
722
|
+
}
|
|
723
|
+
|
|
534
724
|
function readLocalSettings(dshHome) {
|
|
535
725
|
const p = join(dshHome, 'dsh-config-sync.json')
|
|
536
726
|
if (!existsSync(p)) return {}
|
|
537
|
-
|
|
727
|
+
try {
|
|
728
|
+
const doc = JSON.parse(readFileSync(p, 'utf8').replace(/^\uFEFF/, ''))
|
|
729
|
+
return doc && typeof doc === 'object' ? doc : {}
|
|
730
|
+
} catch (e) {
|
|
731
|
+
// 设置文件被手改坏(多一个逗号 / 截断)时不要整个同步崩掉:
|
|
732
|
+
// 走默认值(= 未配置 WebDAV)并明确说清楚,否则 CLI 只吐一堆 JSON 解析堆栈,用户看不懂。
|
|
733
|
+
console.error(`设置文件不是合法 JSON:${p}(${e && e.message ? e.message : e});按未配置 WebDAV 处理`)
|
|
734
|
+
return {}
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
export async function deletePrefixes(w, prefixes = []) {
|
|
739
|
+
const clean = [...new Set((prefixes || []).map((p) => String(p || '').replace(/\\/g, '/').replace(/^\/+|\/+$/g, '')).filter(Boolean))]
|
|
740
|
+
const deleted = [], errors = []
|
|
741
|
+
if (!w.enabled || !clean.length) return { ok: true, deleted, errors }
|
|
742
|
+
for (const p of clean) {
|
|
743
|
+
if (!isSafeRemoteRel(p)) { errors.push(`${p}: 越界路径,已拒绝`); continue }
|
|
744
|
+
}
|
|
745
|
+
const remoteMeta = await listRemoteMeta(w, '')
|
|
746
|
+
const keys = [...remoteMeta.keys()]
|
|
747
|
+
for (const k of keys) {
|
|
748
|
+
if (clean.some((p) => k === p || k.startsWith(p + '/'))) {
|
|
749
|
+
const r = await deleteRemote(w, k)
|
|
750
|
+
if (r.ok) deleted.push(k)
|
|
751
|
+
else errors.push(`${k}: ${r.error || r.status}`)
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
return { ok: errors.length === 0, deleted, errors }
|
|
538
755
|
}
|
|
539
756
|
|
|
540
757
|
export async function runWebdavCli(argv) {
|
|
541
758
|
const [cmd, ...rest] = argv
|
|
542
759
|
const a = parseCliArgs(rest)
|
|
760
|
+
warnUnknownArgs(a, ['DshHome', 'dshHome', 'RepoRoot', 'repoRoot', 'PathsFile', 'pathsFile'], 'node webdav.mjs <probe|upload|download|delete-paths> -DshHome <dir> -RepoRoot <dir>')
|
|
543
761
|
const dshHome = a.DshHome || a.dshHome || process.env.DSH_HOME || join(homedir(), '.dsh')
|
|
544
762
|
const repoRoot = a.RepoRoot || a.repoRoot || process.cwd()
|
|
545
|
-
if (!cmd || !['probe', 'upload', 'download'].includes(cmd)) {
|
|
546
|
-
console.error('用法:node webdav.mjs <probe|upload|download> -DshHome <dir> -RepoRoot <dir>')
|
|
763
|
+
if (!cmd || !['probe', 'upload', 'download', 'delete-paths'].includes(cmd)) {
|
|
764
|
+
console.error('用法:node webdav.mjs <probe|upload|download|delete-paths> -DshHome <dir> -RepoRoot <dir>')
|
|
547
765
|
return 2
|
|
548
766
|
}
|
|
549
767
|
const settings = readLocalSettings(dshHome)
|
|
@@ -562,7 +780,15 @@ export async function runWebdavCli(argv) {
|
|
|
562
780
|
console.error('WebDAV 地址不是 https(明文传输密码有风险);确需使用请设 DSH_SYNC_ALLOW_INSECURE=1')
|
|
563
781
|
return 1
|
|
564
782
|
}
|
|
565
|
-
const r = await uploadRepo(w, repoRoot
|
|
783
|
+
const r = await uploadRepo(w, repoRoot, {
|
|
784
|
+
onProgress: (p) => {
|
|
785
|
+
if (p.phase === 'scan') {
|
|
786
|
+
console.log(`上传扫描:共 ${p.total} 个文件`)
|
|
787
|
+
} else {
|
|
788
|
+
console.log(`上传进度:${p.done}/${p.total}(已上传 ${p.uploaded} · 跳过 ${p.skipped}${p.errors ? ` · 失败 ${p.errors}` : ''})`)
|
|
789
|
+
}
|
|
790
|
+
},
|
|
791
|
+
})
|
|
566
792
|
console.log(`WebDAV 上传:上传 ${r.uploaded.length} · 跳过 ${r.skipped.length} · 错误 ${r.errors.length}`)
|
|
567
793
|
for (const e of r.errors.slice(0, 20)) console.error(` [!] ${e}`)
|
|
568
794
|
return r.ok ? 0 : 1
|
|
@@ -577,6 +803,26 @@ export async function runWebdavCli(argv) {
|
|
|
577
803
|
for (const e of r.errors.slice(0, 20)) console.error(` [!] ${e}`)
|
|
578
804
|
return r.ok ? 0 : 1
|
|
579
805
|
}
|
|
806
|
+
if (cmd === 'delete-paths') {
|
|
807
|
+
if (!isSecureUrl(w.url)) {
|
|
808
|
+
console.error('WebDAV 地址不是 https(明文传输密码有风险);确需使用请设 DSH_SYNC_ALLOW_INSECURE=1')
|
|
809
|
+
return 1
|
|
810
|
+
}
|
|
811
|
+
const pf = a.PathsFile || a.pathsFile || join(dshHome, 'config-sync-delete-cloud.json')
|
|
812
|
+
let prefixes = []
|
|
813
|
+
if (existsSync(pf)) {
|
|
814
|
+
try {
|
|
815
|
+
const doc = JSON.parse(readFileSync(pf, 'utf8').replace(/^\uFEFF/, ''))
|
|
816
|
+
if (Array.isArray(doc?.prefixes)) prefixes = doc.prefixes
|
|
817
|
+
} catch { }
|
|
818
|
+
}
|
|
819
|
+
const r = await deletePrefixes(w, prefixes)
|
|
820
|
+
if (r.deleted.length || r.errors.length) {
|
|
821
|
+
console.log(`WebDAV 清理云端未勾选副本:删除 ${r.deleted.length} · 错误 ${r.errors.length}`)
|
|
822
|
+
}
|
|
823
|
+
for (const e of r.errors.slice(0, 20)) console.error(` [!] ${e}`)
|
|
824
|
+
return r.ok ? 0 : 1
|
|
825
|
+
}
|
|
580
826
|
return 2
|
|
581
827
|
}
|
|
582
828
|
|