dsh-profile-config-sync 0.5.0 → 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 +569 -278
- 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 +1049 -189
- 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 +192 -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
|
@@ -70,7 +70,7 @@ function Save-SyncNotices {
|
|
|
70
70
|
byKind = $byKind
|
|
71
71
|
items = @($script:SyncNoticeItems)
|
|
72
72
|
}
|
|
73
|
-
|
|
73
|
+
Write-FileAtomic $p ($obj | ConvertTo-Json -Depth 4) (New-Object Text.UTF8Encoding $false)
|
|
74
74
|
} catch { }
|
|
75
75
|
}
|
|
76
76
|
|
|
@@ -129,6 +129,20 @@ function Get-SyncNoticesSummary($notices) {
|
|
|
129
129
|
return ($parts -join '、')
|
|
130
130
|
}
|
|
131
131
|
|
|
132
|
+
# ---------- 环境自愈:模块路径被别的 PowerShell 版本抢走时,先把 5.1 自己的目录顶到最前 ----------
|
|
133
|
+
# 实测:DSH 从 pwsh 启动 → 子进程 5.1 继承 PS7 的 PSModulePath → Microsoft.PowerShell.Utility 优先
|
|
134
|
+
# 解析到 PS7 的 7.0.0.0 清单(5.1 装不进去)→ Get-FileHash / Invoke-WebRequest 直接「无法识别」,
|
|
135
|
+
# 连带 Compress-Archive / Expand-Archive(插件快照、还原)一起失效。必须在任何模块 cmdlet 之前修。
|
|
136
|
+
try {
|
|
137
|
+
if ($PSVersionTable -and $PSVersionTable.PSEdition -ne 'Core') {
|
|
138
|
+
$selfModules = Join-Path $PSHOME 'Modules'
|
|
139
|
+
if ($selfModules -and (Test-Path -LiteralPath $selfModules)) {
|
|
140
|
+
$cur = [string]$env:PSModulePath
|
|
141
|
+
$rest = @($cur -split ';' | Where-Object { $_ -and ($_.TrimEnd('\') -ne $selfModules.TrimEnd('\')) })
|
|
142
|
+
$env:PSModulePath = (@($selfModules) + $rest) -join ';'
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
} catch { }
|
|
132
146
|
# Windows PowerShell 5.1 的模块自动加载偶尔拿不到 Get-FileHash(PSModulePath 被别的版本目录污染时,
|
|
133
147
|
# 会先撞上一个装不进 5.1 的同名模块,之后这个 cmdlet 就"不存在"了,脚本直接 CommandNotFound 崩掉)。
|
|
134
148
|
# 同步链路全靠它判断"文件要不要覆盖",所以缺了就补一个等价实现,不让一个 cmdlet 决定整条链路生死。
|
|
@@ -270,13 +284,55 @@ function Read-TextPreserveBom([string]$path) {
|
|
|
270
284
|
return $text
|
|
271
285
|
}
|
|
272
286
|
|
|
287
|
+
# 原子落盘:先写同目录临时文件,再 Move-Item -Force 覆盖目标。
|
|
288
|
+
# 为什么必须:apply 会写 storages\workspace.json、profiles\<名字>\package.json 这些
|
|
289
|
+
# DSH 启动就要解析的文件。裸 WriteAllText 是「先截断再写」,进程在中间被杀(关机、
|
|
290
|
+
# 任务管理器结束进程、断电)就会留下半截 JSON,客户端下次启动直接读不出来。
|
|
291
|
+
# Move-Item 在同卷上走 MoveFileEx + REPLACE_EXISTING,是原子的;目标被别的进程占用时
|
|
292
|
+
# 会短暂失败,所以带递增重试,最后实在换不掉才退回直写(并清临时文件)。
|
|
293
|
+
# 读 JSON 时容忍「极短的占用窗口」:面板保存走原子写(rename),读者正好撞上那一瞬
|
|
294
|
+
# 会拿到 share violation。这里短重试;重试用尽返回 $null —— 调用方必须把 $null 与
|
|
295
|
+
# 「文件本来就不存在」区分开,否则一次临时失败会被误读成「没配置」。
|
|
296
|
+
function Read-JsonFileWithRetry([string]$path, [int]$tries = 6, [int]$baseMs = 20) {
|
|
297
|
+
if (-not $path -or -not (Test-Path -LiteralPath $path)) { return $null }
|
|
298
|
+
for ($i = 0; $i -lt $tries; $i++) {
|
|
299
|
+
try { return (Get-Content -LiteralPath $path -Raw -Encoding utf8 -ErrorAction Stop | ConvertFrom-Json) } catch {
|
|
300
|
+
if ($i -eq ($tries - 1)) { return $null }
|
|
301
|
+
Start-Sleep -Milliseconds ($baseMs * ($i + 1))
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
return $null
|
|
305
|
+
}
|
|
306
|
+
function Write-FileAtomic([string]$path, [string]$text, $encoding) {
|
|
307
|
+
if (-not $encoding) { $encoding = New-Object Text.UTF8Encoding($false, $false) }
|
|
308
|
+
$dir = Split-Path -Parent $path
|
|
309
|
+
if ($dir -and -not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null }
|
|
310
|
+
$tmp = $path + ".tmp-" + $PID + "-" + ([guid]::NewGuid().ToString("N").Substring(0, 6))
|
|
311
|
+
[IO.File]::WriteAllText($tmp, $text, $encoding)
|
|
312
|
+
for ($i = 0; $i -lt 25; $i++) {
|
|
313
|
+
try {
|
|
314
|
+
Move-Item -LiteralPath $tmp -Destination $path -Force -ErrorAction Stop
|
|
315
|
+
return $true
|
|
316
|
+
} catch {
|
|
317
|
+
Start-Sleep -Milliseconds (8 * ($i + 1))
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
try {
|
|
321
|
+
[IO.File]::WriteAllText($path, $text, $encoding)
|
|
322
|
+
return $false
|
|
323
|
+
} finally {
|
|
324
|
+
if (Test-Path -LiteralPath $tmp) { Remove-Item -LiteralPath $tmp -Force -ErrorAction SilentlyContinue }
|
|
325
|
+
}
|
|
326
|
+
}
|
|
273
327
|
function Write-TextPreserveBom([string]$path, [string]$text) {
|
|
274
328
|
$hasBom = $false
|
|
275
329
|
if (Test-Path -LiteralPath $path) {
|
|
276
330
|
$b = [IO.File]::ReadAllBytes($path)
|
|
277
331
|
$hasBom = ($b.Length -ge 3 -and $b[0] -eq 0xEF -and $b[1] -eq 0xBB -and $b[2] -eq 0xBF)
|
|
278
332
|
}
|
|
279
|
-
|
|
333
|
+
# 这个函数写的是 DSH 启动就要解析的文件(cordis.yml / cordis.patch.yml / profile\package.json /
|
|
334
|
+
# AGENTS.md / skills),半截写入会让宿主直接 fatal —— 所以走原子写。BOM 选择语义不变。
|
|
335
|
+
Write-FileAtomic $path $text (New-Object Text.UTF8Encoding($hasBom, $false))
|
|
280
336
|
}
|
|
281
337
|
|
|
282
338
|
# ---------- 宿主版本 ----------
|
|
@@ -466,7 +522,12 @@ function Get-HostElectronVersion([string]$appRoot) {
|
|
|
466
522
|
function Test-AppRootDir([string]$path) {
|
|
467
523
|
if ([string]::IsNullOrWhiteSpace($path)) { return $false }
|
|
468
524
|
$p = $path.TrimEnd('\', '/')
|
|
469
|
-
|
|
525
|
+
# 这里拿到的是「候选路径」:可能指向不存在的盘(换过盘的机器、探测列表里的 G:\DSH)。
|
|
526
|
+
# PS 5.1 的 Join-Path 对不存在的盘符会抛 DriveNotFoundException,$ErrorActionPreference=Stop 时
|
|
527
|
+
# 直接把调用它的脚本(restore / sync)打断。字符串拼接 + SilentlyContinue 更稳。
|
|
528
|
+
$asar = $p + '\resources\app.asar'
|
|
529
|
+
$plain = $p + '\resources\app\package.json'
|
|
530
|
+
return (Test-Path -LiteralPath $asar -ErrorAction SilentlyContinue) -or (Test-Path -LiteralPath $plain -ErrorAction SilentlyContinue)
|
|
470
531
|
}
|
|
471
532
|
|
|
472
533
|
function Get-InstalledAppLocation([string]$namePattern) {
|
|
@@ -532,10 +593,39 @@ $SyncScopeGroups = @('profile', 'prompt', 'skills', 'presets', 'storages-record'
|
|
|
532
593
|
# 排除名单可改、单文件上限可改(硬顶 100MB —— GitHub 单文件超过 100MB 会被拒收,调大也没用)。
|
|
533
594
|
$SyncExtraHardMaxBytes = 104857600
|
|
534
595
|
|
|
596
|
+
# 安全必需项:用户自己的 config-sync-extra.json 不能把它们去掉。
|
|
597
|
+
# 起因(本机实测):设置文件里的 exclude / skipDirs 是**整份替换**语义,用户早先存下的 50 条旧快照
|
|
598
|
+
# 会让 0.6.12 新增的 browser-profiles 规则整条失效 —— 那目录里有 3,696 个文件 / 297MB,含密码库。
|
|
599
|
+
# 这两个字段可以在面板里删改某一条,但下面这些名字不允许消失。
|
|
600
|
+
$SyncExtraMandatorySkipDirs = @(
|
|
601
|
+
'browser-profiles'
|
|
602
|
+
)
|
|
603
|
+
$SyncExtraMandatoryExcludes = @(
|
|
604
|
+
'browser-profiles', 'User Data', 'Login Data', 'Cookies', 'Web Data', 'Local State'
|
|
605
|
+
)
|
|
606
|
+
|
|
607
|
+
# 浏览器剖面 / 凭据库:插件把 CDP 用的 Edge/Chrome 用户目录放在这里,本机实测
|
|
608
|
+
# <DshHome>\plugin-data\browser-profiles 有 3,696 个文件 / 297 MB,含 Login Data(密码库)、
|
|
609
|
+
# Cookies(登录态)、Web Data(自动填充)。这些一旦进仓库就等于把登录态搬走,
|
|
610
|
+
# 而且体积足够让一次 push 直接失败。按**路径段**判定,深层嵌套也拦得住。
|
|
611
|
+
$SyncBlockedProfileSegments = @(
|
|
612
|
+
'browser-profiles', 'user data', 'login data', 'login data for account',
|
|
613
|
+
'cookies', 'cookies-journal', 'web data', 'web data-journal', 'secure preferences',
|
|
614
|
+
'local state', 'history', 'history-journal', 'top sites', 'current session', 'current tabs'
|
|
615
|
+
)
|
|
616
|
+
|
|
617
|
+
function Test-BlockedProfilePath([string]$rel) {
|
|
618
|
+
if (-not $rel) { return $false }
|
|
619
|
+
foreach ($seg in @($rel -split '[\\/]' | Where-Object { $_ })) {
|
|
620
|
+
if ($SyncBlockedProfileSegments -contains $seg.ToLowerInvariant()) { return $true }
|
|
621
|
+
}
|
|
622
|
+
return $false
|
|
623
|
+
}
|
|
624
|
+
|
|
535
625
|
$SyncExtraDefaultSkipDirs = @(
|
|
536
626
|
'profiles', 'skills', '.agent-presets', 'storages', 'sessions', 'attachments', 'logs', 'backups',
|
|
537
627
|
'update-staging', 'electron', 'dsh-runtimes', 'dsh-market', '.dsh-plugin-market', 'dsh-session-manager',
|
|
538
|
-
'im', 'node_modules'
|
|
628
|
+
'browser-profiles', 'im', 'node_modules'
|
|
539
629
|
)
|
|
540
630
|
|
|
541
631
|
$SyncExtraDefaultExclude = @(
|
|
@@ -543,29 +633,129 @@ $SyncExtraDefaultExclude = @(
|
|
|
543
633
|
'*.node', '*.exe', '*.dll', '*.asar', '*.pak', '*.bin', '*.iso', '*.img',
|
|
544
634
|
'*.zip', '*.7z', '*.rar', '*.tar', '*.gz', '*.tgz', '*.mp4', '*.mkv', '*.avi',
|
|
545
635
|
'*.log', '*.log.*', '*.tmp', '*.bak', '*.bak-*', '*.old', '*.orig', '*.swp',
|
|
636
|
+
'*.env', '.env*', 'config-sync-gh.json', 'config-sync-feedback-outbox.json', 'dsh-config-sync.json', 'dsh-ssh-master.key',
|
|
546
637
|
'api-key', '*.pem', '*.key', '*.p12', '*.pfx', '*.crt',
|
|
547
638
|
'*cache*', '*token*', '*secret*', '*credential*', '*password*', '*vault*',
|
|
639
|
+
'browser-profiles', 'User Data', 'Login Data', 'Cookies', 'Web Data', 'Local State',
|
|
548
640
|
'node_modules', '.git', '.cache', '__pycache__', '.venv'
|
|
549
641
|
)
|
|
550
642
|
|
|
551
|
-
#
|
|
552
|
-
|
|
643
|
+
# 本机私有文件名黑名单:绝不允许抓进同步仓库或推到云端
|
|
644
|
+
$SyncPrivateFileNames = @(
|
|
645
|
+
'config-sync-gh.json',
|
|
646
|
+
'config-sync-feedback-outbox.json',
|
|
647
|
+
'dsh-config-sync.json',
|
|
648
|
+
'config-sync-state.json',
|
|
649
|
+
'config-sync-roots.json',
|
|
650
|
+
'config-sync-scope.json',
|
|
651
|
+
'config-sync-delete-cloud.json',
|
|
652
|
+
'config-sync-extra.json',
|
|
653
|
+
'sync-notices.json',
|
|
654
|
+
'.credentials.yaml',
|
|
655
|
+
'.env',
|
|
656
|
+
'dsh-ssh-master.key'
|
|
657
|
+
)
|
|
658
|
+
|
|
659
|
+
function Test-PrivateSecretFileName([string]$path) {
|
|
660
|
+
if (-not $path) { return $false }
|
|
661
|
+
$leaf = ([IO.Path]::GetFileName($path)).ToLowerInvariant()
|
|
662
|
+
if (-not $leaf) { return $false }
|
|
663
|
+
if ($SyncPrivateFileNames -contains $leaf) { return $true }
|
|
664
|
+
if ($leaf -like '.env.*' -or $leaf -like '*.pem' -or $leaf -like '*.key' -or $leaf -like '*.p12' -or $leaf -like '*.pfx') { return $true }
|
|
665
|
+
return $false
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
# 凭据内容嗅探:名字看不出、内容里却带登录态或 GitHub 令牌的文件不能进仓库。
|
|
553
669
|
$SyncExtraSecretMarkers = @(
|
|
554
670
|
'"accesstoken"', '"refreshtoken"', '"idtoken"', '"apikey"', '"api_key"',
|
|
555
|
-
'"clientsecret"', '"privatekey"', '"password"', '
|
|
671
|
+
'"clientsecret"', '"privatekey"', '"password"', '"webdavpass"', '"updatetoken"',
|
|
672
|
+
'authorization: bearer', 'github_token=', 'gh_token='
|
|
556
673
|
)
|
|
674
|
+
$SyncGitHubTokenPattern = 'gh[pousr]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,}'
|
|
675
|
+
|
|
676
|
+
$script:ActiveSecretCache = $null
|
|
677
|
+
function Get-ActiveRuntimeSecrets([string]$DshHomeHint = '') {
|
|
678
|
+
if ($null -ne $script:ActiveSecretCache) { return $script:ActiveSecretCache }
|
|
679
|
+
$list = New-Object System.Collections.Generic.List[string]
|
|
680
|
+
$add = {
|
|
681
|
+
param([string]$v)
|
|
682
|
+
if ($v) {
|
|
683
|
+
$t = $v.Trim()
|
|
684
|
+
if ($t.Length -ge 12 -and -not $t.StartsWith('$') -and $t -notmatch '^env:') {
|
|
685
|
+
if (-not $list.Contains($t)) { [void]$list.Add($t) }
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
foreach ($n in @('DSH_CONFIG_SYNC_GH_TOKEN', 'GITHUB_TOKEN', 'GH_TOKEN')) {
|
|
690
|
+
& $add ([Environment]::GetEnvironmentVariable($n))
|
|
691
|
+
& $add ([Environment]::GetEnvironmentVariable($n, 'User'))
|
|
692
|
+
& $add ([Environment]::GetEnvironmentVariable($n, 'Machine'))
|
|
693
|
+
}
|
|
694
|
+
$dh = if ($DshHomeHint) { $DshHomeHint } elseif ($env:DSH_HOME) { $env:DSH_HOME } else { (Join-Path $HOME '.dsh') }
|
|
695
|
+
if ($dh) {
|
|
696
|
+
foreach ($fn in @('config-sync-gh.json', 'dsh-config-sync.json')) {
|
|
697
|
+
$p = Join-Path $dh $fn
|
|
698
|
+
if (Test-Path -LiteralPath $p) {
|
|
699
|
+
try {
|
|
700
|
+
$j = Read-JsonFileWithRetry $p
|
|
701
|
+
if ($j.token) { & $add ([string]$j.token) }
|
|
702
|
+
if ($j.updateToken) { & $add ([string]$j.updateToken) }
|
|
703
|
+
if ($j.webdavPass) { & $add ([string]$j.webdavPass) }
|
|
704
|
+
if ($j.tokenEnv) {
|
|
705
|
+
$en = [string]$j.tokenEnv
|
|
706
|
+
& $add ([Environment]::GetEnvironmentVariable($en))
|
|
707
|
+
& $add ([Environment]::GetEnvironmentVariable($en, 'User'))
|
|
708
|
+
}
|
|
709
|
+
} catch { }
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
$script:ActiveSecretCache = @($list)
|
|
714
|
+
return $script:ActiveSecretCache
|
|
715
|
+
}
|
|
557
716
|
|
|
558
|
-
function Test-SyncExtraSecret([string]$file) {
|
|
717
|
+
function Test-SyncExtraSecret([string]$file, [string]$DshHomeHint = '') {
|
|
559
718
|
try {
|
|
560
|
-
if (
|
|
561
|
-
$
|
|
562
|
-
if ($
|
|
563
|
-
|
|
564
|
-
if ($
|
|
565
|
-
|
|
719
|
+
if (Test-PrivateSecretFileName $file) { return $true }
|
|
720
|
+
$item = Get-Item -LiteralPath $file -Force
|
|
721
|
+
if ($item.PSIsContainer) { return $false } # 目录由调用方逐文件判定
|
|
722
|
+
$len = [long]$item.Length
|
|
723
|
+
if ($len -le 2100000) {
|
|
724
|
+
$sample = [IO.File]::ReadAllBytes($file)
|
|
725
|
+
} else {
|
|
726
|
+
# 旧写法对 >8MB 直接 return $false —— 一个大 JSON 导出、把令牌记在末尾的日志就能绕过
|
|
727
|
+
# 唯一一道门禁原样进仓库。改成头尾各抽 512KB(令牌一般落在配置头部或日志尾部)。
|
|
728
|
+
$fs = [IO.File]::OpenRead($file)
|
|
729
|
+
try {
|
|
730
|
+
$chunk = [int](512 * 1024)
|
|
731
|
+
$headLen = [int][Math]::Min($chunk, $len)
|
|
732
|
+
$head = New-Object byte[] $headLen
|
|
733
|
+
$headRead = $fs.Read($head, 0, $headLen)
|
|
734
|
+
$tailStart = [long][Math]::Max(0, $len - $chunk)
|
|
735
|
+
[void]$fs.Seek($tailStart, [IO.SeekOrigin]::Begin)
|
|
736
|
+
$tailLen = [int][Math]::Min($chunk, $len - $tailStart)
|
|
737
|
+
$tail = New-Object byte[] $tailLen
|
|
738
|
+
$tailRead = $fs.Read($tail, 0, $tailLen)
|
|
739
|
+
$sample = New-Object byte[] ($headRead + $tailRead)
|
|
740
|
+
[Array]::Copy($head, 0, $sample, 0, $headRead)
|
|
741
|
+
[Array]::Copy($tail, 0, $sample, $headRead, $tailRead)
|
|
742
|
+
} finally { $fs.Dispose() }
|
|
743
|
+
}
|
|
744
|
+
# 用 latin1(码位 = 字节)解码:二进制文件里的 ASCII 令牌照样能命中,
|
|
745
|
+
# 也不会因为非法 UTF-8 序列抛错。旧写法「含 NUL 就 return $false」等于给二进制开后门。
|
|
746
|
+
$rawText = [Text.Encoding]::GetEncoding(28591).GetString($sample)
|
|
747
|
+
if ($rawText -match $SyncGitHubTokenPattern) { return $true }
|
|
748
|
+
foreach ($sec in (Get-ActiveRuntimeSecrets $DshHomeHint)) {
|
|
749
|
+
if ($rawText.Contains($sec)) { return $true }
|
|
750
|
+
}
|
|
751
|
+
$text = $rawText.ToLowerInvariant()
|
|
566
752
|
foreach ($m in $SyncExtraSecretMarkers) { if ($text.Contains($m)) { return $true } }
|
|
567
753
|
return $false
|
|
568
|
-
} catch {
|
|
754
|
+
} catch {
|
|
755
|
+
# 读不了 = 判不了。旧写法 catch 里 return $false,等于「读不了就放行」:超长路径、被独占、
|
|
756
|
+
# 权限不足的文件会静默进仓库。这里改成宁可跳过(调用方会记进未同步清单并告警)。
|
|
757
|
+
return $true
|
|
758
|
+
}
|
|
569
759
|
}
|
|
570
760
|
|
|
571
761
|
# 自动枚举时被凭据嗅探挡下的文件:抓完集中 Warn 一次,用户知道"这些没进来、为什么"
|
|
@@ -573,6 +763,79 @@ $script:SyncExtraSecretSkips = New-Object System.Collections.ArrayList
|
|
|
573
763
|
function Reset-SyncExtraSecretSkips { $script:SyncExtraSecretSkips.Clear() }
|
|
574
764
|
function Get-SyncExtraSecretSkips { return @($script:SyncExtraSecretSkips) }
|
|
575
765
|
|
|
766
|
+
# 仓库里的 settings\xxx.json ↔ 本机实际路径。三处(capture / apply / restore)共用这一份,
|
|
767
|
+
# 否则「从仓库还原」会把文件放错目录:实测 dsh-workspaces.json 被丢到 ~/.dsh 根,
|
|
768
|
+
# 而 DSH 读的是 ~/.dsh\storages\workspace.json,工作区看起来全部消失。
|
|
769
|
+
# 同一 DSH 目录的同步互斥:capture 和 apply 都可能被「面板按钮 / 自动 watcher / 定时任务」同时触发,
|
|
770
|
+
# 两个进程撞同一个文件会抛 .NET IOException(实测 package.json「being used by another process」)。
|
|
771
|
+
# 命名 Mutex 在进程退出时自动释放,崩溃也不会留下死锁文件。
|
|
772
|
+
# 返回 $true 表示拿到锁;$false 表示已有同步在跑,调用方应明确告知用户本次没有执行(退出码非 0,不假绿)。
|
|
773
|
+
function Lock-SyncRun([string]$DshHome, [string]$Label) {
|
|
774
|
+
try {
|
|
775
|
+
$sha1 = [System.Security.Cryptography.SHA1]::Create()
|
|
776
|
+
$bytes = [Text.Encoding]::UTF8.GetBytes(([string]$DshHome).ToLowerInvariant())
|
|
777
|
+
$hash = -join ($sha1.ComputeHash($bytes) | ForEach-Object { $_.ToString("x2") })
|
|
778
|
+
$sha1.Dispose()
|
|
779
|
+
$name = "Local\dsh-config-sync-" + $hash.Substring(0, 16)
|
|
780
|
+
$script:SyncRunMutex = New-Object System.Threading.Mutex($false, $name)
|
|
781
|
+
try {
|
|
782
|
+
return $script:SyncRunMutex.WaitOne(0)
|
|
783
|
+
} catch [System.Threading.AbandonedMutexException] {
|
|
784
|
+
# 上一个进程崩了,锁被系统留给我们:视为拿到(这正是 Mutex 比锁文件好的地方)
|
|
785
|
+
return $true
|
|
786
|
+
}
|
|
787
|
+
} catch {
|
|
788
|
+
# 拿不到互斥能力(极老系统 / 受限环境)时不能因此阻止同步:放行并留一句警告
|
|
789
|
+
Warn ("无法启用同步互斥(" + $_.Exception.Message + "),本次 " + $Label + " 继续执行")
|
|
790
|
+
return $true
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
# 只探测「有没有别的同步动作正在跑」,不持有锁:
|
|
795
|
+
# pull 会先下载/快进仓库、再调 apply 落地配置。如果等到 apply 才发现锁被占用,
|
|
796
|
+
# 仓库已经变了而配置没变 —— 半截状态。所以拉取要在动手前先问一句。
|
|
797
|
+
# 探测本身有极小竞态(问完到 apply 抢锁之间),但 apply 那层仍然是权威判据。
|
|
798
|
+
function Test-SyncRunBusy([string]$DshHome) {
|
|
799
|
+
$hash = [System.Security.Cryptography.SHA1]::Create()
|
|
800
|
+
try {
|
|
801
|
+
$bytes = [Text.Encoding]::UTF8.GetBytes(([string]$DshHome).ToLowerInvariant())
|
|
802
|
+
$hex = (($hash.ComputeHash($bytes) | ForEach-Object { $_.ToString("x2") }) -join "")
|
|
803
|
+
$name = "Local\dsh-config-sync-" + $hex.Substring(0, 16)
|
|
804
|
+
$m = New-Object System.Threading.Mutex($false, $name)
|
|
805
|
+
} catch {
|
|
806
|
+
# 建不出互斥时不要挡住用户:宁可放行(apply 那层还会再判一次)
|
|
807
|
+
return $false
|
|
808
|
+
} finally { try { $hash.Dispose() } catch { } }
|
|
809
|
+
try {
|
|
810
|
+
try {
|
|
811
|
+
if ($m.WaitOne(0)) { try { $m.ReleaseMutex() } catch { }; return $false }
|
|
812
|
+
return $true
|
|
813
|
+
} catch [System.Threading.AbandonedMutexException] {
|
|
814
|
+
# 上一个持锁进程崩了:锁是空的,别把它当占用
|
|
815
|
+
try { $m.ReleaseMutex() } catch { }
|
|
816
|
+
return $false
|
|
817
|
+
}
|
|
818
|
+
} catch { return $false } finally { try { $m.Dispose() } catch { } }
|
|
819
|
+
}
|
|
820
|
+
function Get-SyncSettingsMap([string]$DshHome, [string]$ProfileName) {
|
|
821
|
+
return @(
|
|
822
|
+
@{ Repo = 'settings\our-free-model.json'; Src = (Join-Path $DshHome 'our-free-model\settings.json'); Label = 'our-free-model 插件设置' }
|
|
823
|
+
@{ Repo = 'settings\comfyui-workflows.json'; Src = (Join-Path $DshHome 'data\dsh-comfyui\workflows.json'); Label = 'ComfyUI 工作流库' }
|
|
824
|
+
@{ Repo = 'settings\dsh-pet-main-config.jsonc'; Src = (Join-Path $DshHome 'dsh-pet\main-config.jsonc'); Label = '桌宠配置' }
|
|
825
|
+
@{ Repo = 'settings\dsh-market-state.json'; Src = (Join-Path $DshHome ("profiles\" + $ProfileName + '\.dsh-market\state.json')); Label = '插件市场状态' }
|
|
826
|
+
@{ Repo = 'settings\dsh-pet-memory.json'; Src = (Join-Path $DshHome 'dsh-pet\memory.json'); Label = '桌宠记忆' }
|
|
827
|
+
@{ Repo = 'settings\our-free-model-picks.json'; Src = (Join-Path $DshHome 'our-free-model\picks.json'); Label = 'our-free-model 收藏' }
|
|
828
|
+
@{ Repo = 'settings\dsh-im-interface-language.json'; Src = (Join-Path $DshHome 'integrations\dsh-im\interface-language.json'); Label = 'dsh-im 界面语言' }
|
|
829
|
+
@{ Repo = 'settings\dsh-qq-config.json'; Src = (Join-Path $DshHome 'integrations\dsh-qq\config.json'); Label = 'QQ 集成配置' }
|
|
830
|
+
@{ Repo = 'settings\dsh-qq-workspaces.json'; Src = (Join-Path $DshHome 'integrations\dsh-qq\workspaces.json'); Label = 'QQ 集成工作区' }
|
|
831
|
+
@{ Repo = 'settings\redteam-preset-declare.json'; Src = (Join-Path $DshHome 'redteam\preset-declare.json'); Label = '红队预设声明' }
|
|
832
|
+
@{ Repo = 'settings\task-board-ledger.json'; Src = (Join-Path $DshHome 'task-board\ledger-v2.json'); Label = '任务板台账' }
|
|
833
|
+
@{ Repo = 'settings\task-board-scheduler.json'; Src = (Join-Path $DshHome 'task-board\scheduler-v2.json'); Label = '任务板调度' }
|
|
834
|
+
@{ Repo = 'settings\dsh-workspaces.json'; Src = (Join-Path $DshHome 'storages\workspace.json'); Label = 'DSH 工作区登记' }
|
|
835
|
+
@{ Repo = 'settings\workspace-archives.json'; Src = (Join-Path $DshHome 'dsh-session-manager\workspace-archives.v1.json'); Label = 'DSH 工作区隐藏状态' }
|
|
836
|
+
)
|
|
837
|
+
}
|
|
838
|
+
|
|
576
839
|
function Get-SyncExtraPath([string]$DshHome) { return (Join-Path $DshHome 'config-sync-extra.json') }
|
|
577
840
|
|
|
578
841
|
function Get-SyncExtraConfig([string]$DshHome) {
|
|
@@ -586,8 +849,11 @@ function Get-SyncExtraConfig([string]$DshHome) {
|
|
|
586
849
|
$f = $null
|
|
587
850
|
if ($DshHome) { $f = Get-SyncExtraPath $DshHome }
|
|
588
851
|
if ($f -and (Test-Path -LiteralPath $f)) {
|
|
852
|
+
# 这份文件是面板写的(走原子 rename):撞上极短占用窗口时要重试,别直接退回默认规则
|
|
589
853
|
try {
|
|
590
|
-
$j =
|
|
854
|
+
$j = Read-JsonFileWithRetry $f
|
|
855
|
+
# 重试用尽返回 $null:文件确实读不出/坏了,仍要人话告知,别静默退回默认规则
|
|
856
|
+
if ($null -eq $j) { throw "重试 $SyncExtraReadTries 次仍读不出(文件可能损坏,或被别的进程长期占用)" }
|
|
591
857
|
if ($j.pluginData) {
|
|
592
858
|
if ($null -ne $j.pluginData.PSObject.Properties['enabled']) { $pd.enabled = ($j.pluginData.enabled -ne $false) }
|
|
593
859
|
if ($null -ne $j.pluginData.PSObject.Properties['maxFileBytes']) {
|
|
@@ -611,6 +877,19 @@ function Get-SyncExtraConfig([string]$DshHome) {
|
|
|
611
877
|
Warn ("config-sync-extra.json 解析失败,按默认规则处理:" + $_.Exception.Message)
|
|
612
878
|
}
|
|
613
879
|
}
|
|
880
|
+
# 必需项补齐:用户文件可以改别的东西,但这些名字必须留着
|
|
881
|
+
$addedSkip = @()
|
|
882
|
+
foreach ($must in $SyncExtraMandatorySkipDirs) {
|
|
883
|
+
if (-not ($pd.skipDirs -contains $must)) { $pd.skipDirs = @($pd.skipDirs) + @($must); $addedSkip += $must }
|
|
884
|
+
}
|
|
885
|
+
$addedExcl = @()
|
|
886
|
+
foreach ($must in $SyncExtraMandatoryExcludes) {
|
|
887
|
+
if (-not ($pd.exclude -contains $must)) { $pd.exclude = @($pd.exclude) + @($must); $addedExcl += $must }
|
|
888
|
+
}
|
|
889
|
+
if ($addedSkip.Count -gt 0 -or $addedExcl.Count -gt 0) {
|
|
890
|
+
# 不静默:告诉用户他的规则文件少了安全项、这次按内置名单补齐了(文件本身不改,面板里保存时才写)
|
|
891
|
+
Warn ("你的 config-sync-extra.json 缺少安全必需项,本次已按内置名单补齐:跳过目录 " + $(if ($addedSkip.Count) { ($addedSkip -join ",") } else { "无" }) + ";排除 " + $(if ($addedExcl.Count) { ($addedExcl -join ",") } else { "无" }))
|
|
892
|
+
}
|
|
614
893
|
return [pscustomobject]@{ version = 1; pluginData = $pd; extra = $ex }
|
|
615
894
|
}
|
|
616
895
|
|
|
@@ -629,7 +908,7 @@ function Save-SyncExtraConfig([string]$DshHome, $cfg) {
|
|
|
629
908
|
}
|
|
630
909
|
}
|
|
631
910
|
$f = Get-SyncExtraPath $DshHome
|
|
632
|
-
|
|
911
|
+
Write-FileAtomic $f ($j | ConvertTo-Json -Depth 6) (New-Object Text.UTF8Encoding($false))
|
|
633
912
|
return $f
|
|
634
913
|
}
|
|
635
914
|
|
|
@@ -637,6 +916,8 @@ function Save-SyncExtraConfig([string]$DshHome, $cfg) {
|
|
|
637
916
|
function Test-SyncExtraSkip([string]$relName, [long]$size, $cfg) {
|
|
638
917
|
$max = [Math]::Min([int64]$cfg.pluginData.maxFileBytes, [int64]$SyncExtraHardMaxBytes)
|
|
639
918
|
if ($size -gt $max) { return 'too-big' }
|
|
919
|
+
# 浏览器剖面 / 凭据库:抓取阶段就不收(与 webdav.mjs 的上传门禁同一份名单)
|
|
920
|
+
if (Test-BlockedProfilePath $relName) { return 'blocked-profile' }
|
|
640
921
|
if (-not $relName) { return '' }
|
|
641
922
|
$parts = @($relName -split '[\\/]' | Where-Object { $_ })
|
|
642
923
|
$name = if ($parts.Count -gt 0) { $parts[$parts.Count - 1] } else { $relName }
|
|
@@ -764,10 +1045,32 @@ function Test-SyncDeleteCloud($Scope) {
|
|
|
764
1045
|
return ($Scope.deleteCloud -eq $true)
|
|
765
1046
|
}
|
|
766
1047
|
|
|
1048
|
+
$script:SyncDeleteCloudPrefixes = New-Object System.Collections.Generic.List[string]
|
|
1049
|
+
|
|
1050
|
+
function Add-SyncDeleteCloudPrefix([string]$rel) {
|
|
1051
|
+
if (-not $rel) { return }
|
|
1052
|
+
$norm = $rel.Replace('\', '/').Trim('/')
|
|
1053
|
+
if ($norm -and -not $script:SyncDeleteCloudPrefixes.Contains($norm)) {
|
|
1054
|
+
[void]$script:SyncDeleteCloudPrefixes.Add($norm)
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
function Save-SyncDeleteCloudQueue([string]$DshHome) {
|
|
1059
|
+
if (-not $DshHome) { return }
|
|
1060
|
+
$qPath = Join-Path $DshHome 'config-sync-delete-cloud.json'
|
|
1061
|
+
if ($script:SyncDeleteCloudPrefixes.Count -eq 0) {
|
|
1062
|
+
if (Test-Path -LiteralPath $qPath) { try { Remove-Item -LiteralPath $qPath -Force } catch { } }
|
|
1063
|
+
return
|
|
1064
|
+
}
|
|
1065
|
+
$json = ([ordered]@{ prefixes = @($script:SyncDeleteCloudPrefixes) } | ConvertTo-Json -Depth 3)
|
|
1066
|
+
[void](Write-FileAtomic $qPath $json (New-Object Text.UTF8Encoding($false, $false)))
|
|
1067
|
+
}
|
|
1068
|
+
|
|
767
1069
|
# 整组被跳过时调用:deleteCloud 打开就把仓库里那份删掉;默认什么都不做(留着,以后勾回来接着用)
|
|
768
1070
|
function Skip-SyncGroup($Scope, [string]$RepoRoot, [string]$Group) {
|
|
769
1071
|
Warn ("跳过(未勾选同步):" + $Group)
|
|
770
1072
|
if (-not (Test-SyncDeleteCloud $Scope)) { return }
|
|
1073
|
+
Add-SyncDeleteCloudPrefix $Group
|
|
771
1074
|
$target = Join-Path $RepoRoot $Group
|
|
772
1075
|
if (Test-Path -LiteralPath $target) {
|
|
773
1076
|
Remove-Item -LiteralPath $target -Recurse -Force
|
|
@@ -778,6 +1081,7 @@ function Skip-SyncGroup($Scope, [string]$RepoRoot, [string]$Group) {
|
|
|
778
1081
|
# 组内单项被跳过时调用(item 是仓库里的相对路径,如 skills\foo、settings\x.json)
|
|
779
1082
|
function Skip-SyncItem($Scope, [string]$RepoRoot, [string]$Group, [string]$Item, [string]$RepoRel) {
|
|
780
1083
|
if (-not (Test-SyncDeleteCloud $Scope) -or -not $RepoRel) { return }
|
|
1084
|
+
Add-SyncDeleteCloudPrefix $RepoRel
|
|
781
1085
|
$target = Join-Path $RepoRoot $RepoRel
|
|
782
1086
|
if (Test-Path -LiteralPath $target) {
|
|
783
1087
|
Remove-Item -LiteralPath $target -Recurse -Force
|
|
@@ -908,7 +1212,8 @@ function Get-SyncRoots([string]$DshHome, [string]$AppRoot = '', [string]$Workspa
|
|
|
908
1212
|
$f = Get-SyncRootsPath $DshHome
|
|
909
1213
|
if (Test-Path -LiteralPath $f) {
|
|
910
1214
|
try {
|
|
911
|
-
$j =
|
|
1215
|
+
$j = Read-JsonFileWithRetry $f
|
|
1216
|
+
if ($null -eq $j) { throw "config-sync-roots.json 重试后仍读不出" }
|
|
912
1217
|
if ($j.appRoot) { $o.appRoot = [string]$j.appRoot }
|
|
913
1218
|
if ($j.dshHome) { $o.dshHome = [string]$j.dshHome }
|
|
914
1219
|
if ($j.workspaceHome) { $o.workspaceHome = [string]$j.workspaceHome }
|
|
@@ -938,7 +1243,7 @@ function Save-SyncRoots([string]$DshHome, $roots) {
|
|
|
938
1243
|
confirmed = @($roots.confirmed)
|
|
939
1244
|
updatedAt = $roots.updatedAt
|
|
940
1245
|
}
|
|
941
|
-
|
|
1246
|
+
Write-FileAtomic $f ($j | ConvertTo-Json -Depth 6) (New-Object Text.UTF8Encoding($false))
|
|
942
1247
|
return $f
|
|
943
1248
|
}
|
|
944
1249
|
|
|
@@ -1007,7 +1312,7 @@ function Get-MissingTokens([string]$text) {
|
|
|
1007
1312
|
function Write-PendingPaths([string]$DshHome, $items) {
|
|
1008
1313
|
$f = Get-PendingPathsPath $DshHome
|
|
1009
1314
|
$j = [ordered]@{ generatedAt = (Get-Date).ToString('s'); missing = @($items) }
|
|
1010
|
-
|
|
1315
|
+
Write-FileAtomic $f ($j | ConvertTo-Json -Depth 6) (New-Object Text.UTF8Encoding($false))
|
|
1011
1316
|
return $f
|
|
1012
1317
|
}
|
|
1013
1318
|
|
|
@@ -1103,7 +1408,7 @@ function Invoke-SessionLogGuard {
|
|
|
1103
1408
|
[ordered]@{ src = [string]$_.Src; dst = [string]$_.Dst; writeTo = [string]$_.WriteTo }
|
|
1104
1409
|
})
|
|
1105
1410
|
}
|
|
1106
|
-
|
|
1411
|
+
Write-FileAtomic $jobPath ($spec | ConvertTo-Json -Depth 5 -Compress) (New-Object Text.UTF8Encoding($false))
|
|
1107
1412
|
|
|
1108
1413
|
$oldRunAsNode = $env:ELECTRON_RUN_AS_NODE
|
|
1109
1414
|
try {
|
|
@@ -1216,7 +1521,7 @@ function Invoke-BiliStateSync {
|
|
|
1216
1521
|
}
|
|
1217
1522
|
if ($BiliDir) { $spec.biliDir = [string]$BiliDir }
|
|
1218
1523
|
if ($Sessions -and @($Sessions).Count -gt 0) { $spec.sessions = @($Sessions | ForEach-Object { [string]$_ }) }
|
|
1219
|
-
|
|
1524
|
+
Write-FileAtomic $specPath ($spec | ConvertTo-Json -Depth 5 -Compress) (New-Object Text.UTF8Encoding($false))
|
|
1220
1525
|
|
|
1221
1526
|
$oldRunAsNode = $env:ELECTRON_RUN_AS_NODE
|
|
1222
1527
|
try {
|
|
@@ -1293,3 +1598,37 @@ function Write-BiliStateSyncReport($State, [string]$DshHome) {
|
|
|
1293
1598
|
if ($DshHome) { Add-SyncNotice -Kind 'context-state' -Path $sid -Reason ('billion-context 压缩状态搬运失败:' + [string]$f.error) }
|
|
1294
1599
|
}
|
|
1295
1600
|
}
|
|
1601
|
+
|
|
1602
|
+
|
|
1603
|
+
# ---------- 版本比较 / 契约新旧判定(capture 与 apply 共用) ----------
|
|
1604
|
+
# 比较两个版本字符串的「三段数字」:a>b 返回 1,a<b 返回 -1,相等返回 0,解析不出来返回 $null。
|
|
1605
|
+
# 预发布后缀(-rc.5)不参与比较,只按三段数字;需要区分时由 Test-ContractStale 处理。
|
|
1606
|
+
function Compare-SyncVersion([string]$a, [string]$b) {
|
|
1607
|
+
$pa = $null; $pb = $null
|
|
1608
|
+
if ($a -match '^v?(\d+)\.(\d+)\.(\d+)') { $pa = @([int]$matches[1], [int]$matches[2], [int]$matches[3]) }
|
|
1609
|
+
if ($b -match '^v?(\d+)\.(\d+)\.(\d+)') { $pb = @([int]$matches[1], [int]$matches[2], [int]$matches[3]) }
|
|
1610
|
+
if ((-not $pa) -or (-not $pb)) { return $null }
|
|
1611
|
+
for ($i = 0; $i -lt 3; $i++) { if ($pa[$i] -gt $pb[$i]) { return 1 }; if ($pa[$i] -lt $pb[$i]) { return -1 } }
|
|
1612
|
+
return 0
|
|
1613
|
+
}
|
|
1614
|
+
|
|
1615
|
+
# 仓库契约是不是「该按本机版本重写」。
|
|
1616
|
+
# 三条依据:
|
|
1617
|
+
# 1) 老格式(缺少 electronVersion / platforms):上游手写契约常把 Electron 版本写进 appVersion
|
|
1618
|
+
# (实测 44.7.0),拿它跟本机 app 比永远不一致 → 另一台 pull 被永久拦住。这种契约不可信,重写。
|
|
1619
|
+
# 2) 本机版本更新(三段数字更大)→ 重写;本机更旧 → 保留,别把契约拉低。
|
|
1620
|
+
# 3) 三段数字相同但只有预发布后缀差异:正式版优先(0.2.2 > 0.2.2-rc.5)。
|
|
1621
|
+
function Test-ContractStale($Doc, [string]$HostVer) {
|
|
1622
|
+
if (-not $Doc) { return $true }
|
|
1623
|
+
$names = @($Doc.PSObject.Properties.Name)
|
|
1624
|
+
if (-not (($names -contains 'electronVersion') -or ($names -contains 'platforms'))) { return $true }
|
|
1625
|
+
$repoVer = [string]$Doc.appVersion
|
|
1626
|
+
if (-not $repoVer) { return $true }
|
|
1627
|
+
if ($repoVer -eq $HostVer) { return $false }
|
|
1628
|
+
$cmp = Compare-SyncVersion $HostVer $repoVer
|
|
1629
|
+
if ($null -eq $cmp) { return $true }
|
|
1630
|
+
if ($cmp -gt 0) { return $true }
|
|
1631
|
+
if ($cmp -lt 0) { return $false }
|
|
1632
|
+
if (($repoVer -match '-') -and ($HostVer -notmatch '-')) { return $true }
|
|
1633
|
+
return $false
|
|
1634
|
+
}
|
|
@@ -35,6 +35,92 @@ if (-not $LogFile) {
|
|
|
35
35
|
if (-not (Test-Path -LiteralPath $logDir)) { New-Item -ItemType Directory -Path $logDir -Force | Out-Null }
|
|
36
36
|
$LogFile = Join-Path $logDir ("plugin-install-{0}.log" -f $stamp)
|
|
37
37
|
}
|
|
38
|
+
# ---------- 环境自愈:模块被别的 PowerShell 版本抢走时,这一步决定后面还能不能跑 ----------
|
|
39
|
+
# 实测:DSH 从 pwsh(PowerShell 7)里启动时,子进程 powershell.exe 5.1 继承了 PS7 的 PSModulePath,
|
|
40
|
+
# 自动加载先撞上 PS7 的 Microsoft.PowerShell.Utility(7.0.0.0,5.1 装不进去),于是
|
|
41
|
+
# Get-FileHash / Invoke-WebRequest 直接「无法识别」——更新流程把空 hash 当校验失败,永远装不上。
|
|
42
|
+
try {
|
|
43
|
+
if ($PSVersionTable -and $PSVersionTable.PSEdition -ne 'Core') {
|
|
44
|
+
$selfModules = Join-Path $PSHOME 'Modules'
|
|
45
|
+
if ($selfModules -and (Test-Path -LiteralPath $selfModules)) {
|
|
46
|
+
$cur = [string]$env:PSModulePath
|
|
47
|
+
$rest = @($cur -split ';' | Where-Object { $_ -and ($_.TrimEnd('\') -ne $selfModules.TrimEnd('\')) })
|
|
48
|
+
$env:PSModulePath = (@($selfModules) + $rest) -join ';'
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
} catch { }
|
|
52
|
+
|
|
53
|
+
# Get-FileHash 的 .NET 等价实现:模块加载失败时也别让一个 cmdlet 决定整条链路生死
|
|
54
|
+
if (-not (Get-Command Get-FileHash -ErrorAction SilentlyContinue)) {
|
|
55
|
+
function Get-FileHash {
|
|
56
|
+
param(
|
|
57
|
+
[Parameter(Mandatory = $true)][string]$LiteralPath,
|
|
58
|
+
[ValidateSet('SHA256', 'SHA1', 'MD5')][string]$Algorithm = 'SHA256'
|
|
59
|
+
)
|
|
60
|
+
$algo = [System.Security.Cryptography.HashAlgorithm]::Create($Algorithm)
|
|
61
|
+
$fs = [System.IO.File]::Open($LiteralPath, 'Open', 'Read', 'ReadWrite')
|
|
62
|
+
try { $bytes = $algo.ComputeHash($fs) } finally { $fs.Dispose(); $algo.Dispose() }
|
|
63
|
+
[pscustomobject]@{
|
|
64
|
+
Algorithm = $Algorithm
|
|
65
|
+
Hash = (($bytes | ForEach-Object { $_.ToString('X2') }) -join '')
|
|
66
|
+
Path = $LiteralPath
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
# 下载兜底:Invoke-WebRequest 不可用(或被策略挡掉)时直接用 .NET,带上同样的头与超时
|
|
72
|
+
function Save-UrlToFile {
|
|
73
|
+
param(
|
|
74
|
+
[Parameter(Mandatory = $true)][string]$Uri,
|
|
75
|
+
[Parameter(Mandatory = $true)][string]$OutFile,
|
|
76
|
+
[hashtable]$Headers = @{},
|
|
77
|
+
[int]$TimeoutSec = 180
|
|
78
|
+
)
|
|
79
|
+
# 这个兜底实现(HttpWebRequest)在 5.1 里会把 Authorization 头吃掉(实测:头存进对象但发不出去),
|
|
80
|
+
# 所以带令牌的下载宁可直接报错并给出办法,也不让用户对着一个没头没脑的 401 猜。
|
|
81
|
+
foreach ($hk in @($Headers.Keys)) {
|
|
82
|
+
if ([string]$hk -ieq 'Authorization') {
|
|
83
|
+
throw '当前 PowerShell 环境不支持带令牌下载(模块被别的 PowerShell 版本占用了):请在面板里用「更新」,或从开始菜单/桌面重新启动 DSH 后重试'
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
$req = [System.Net.HttpWebRequest]::Create($Uri)
|
|
87
|
+
$req.Timeout = $TimeoutSec * 1000
|
|
88
|
+
$req.ReadWriteTimeout = $TimeoutSec * 1000
|
|
89
|
+
$req.UserAgent = 'dsh-profile-config-sync'
|
|
90
|
+
foreach ($k in @($Headers.Keys)) {
|
|
91
|
+
$v = [string]$Headers[$k]
|
|
92
|
+
if ($k -eq 'User-Agent') { $req.UserAgent = $v } else { $req.Headers[$k] = $v }
|
|
93
|
+
}
|
|
94
|
+
$resp = $req.GetResponse()
|
|
95
|
+
try {
|
|
96
|
+
$in = $resp.GetResponseStream()
|
|
97
|
+
$out = [System.IO.File]::Create($OutFile)
|
|
98
|
+
try { $in.CopyTo($out) } finally { $out.Dispose() }
|
|
99
|
+
} finally { $resp.Close() }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
# 统一下载入口:优先 cmdlet,缺失时自动走 Save-UrlToFile
|
|
103
|
+
function Invoke-DownloadFile {
|
|
104
|
+
param(
|
|
105
|
+
[Parameter(Mandatory = $true)][string]$Uri,
|
|
106
|
+
[Parameter(Mandatory = $true)][string]$OutFile,
|
|
107
|
+
[hashtable]$Headers = @{},
|
|
108
|
+
[int]$TimeoutSec = 180
|
|
109
|
+
)
|
|
110
|
+
Remove-Item -LiteralPath $OutFile -Force -ErrorAction SilentlyContinue
|
|
111
|
+
# 注意:Get-Command 只表示「命令能被发现」,不代表能执行 —— PS7 的模块目录排在 PSModulePath 前面时,
|
|
112
|
+
# Invoke-WebRequest 会被解析到装不进 5.1 的版本,调用当场抛装配错误(实测)。所以必须 try/catch 兜底,
|
|
113
|
+
# 而不是只看命令在不在。
|
|
114
|
+
if (Get-Command Invoke-WebRequest -ErrorAction SilentlyContinue) {
|
|
115
|
+
try {
|
|
116
|
+
Invoke-WebRequest -Uri $Uri -Headers $Headers -OutFile $OutFile -UseBasicParsing -TimeoutSec $TimeoutSec
|
|
117
|
+
return
|
|
118
|
+
} catch {
|
|
119
|
+
Remove-Item -LiteralPath $OutFile -Force -ErrorAction SilentlyContinue
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
Save-UrlToFile -Uri $Uri -OutFile $OutFile -Headers $Headers -TimeoutSec $TimeoutSec
|
|
123
|
+
}
|
|
38
124
|
function Log([string]$text) {
|
|
39
125
|
$line = "[{0}] {1}" -f (Get-Date -Format 'HH:mm:ss'), $text
|
|
40
126
|
try { Add-Content -LiteralPath $LogFile -Value $line -Encoding utf8 } catch { }
|
|
@@ -90,7 +176,7 @@ if ($TgzFile -and (Test-Path -LiteralPath $TgzFile)) {
|
|
|
90
176
|
foreach ($u in $urls) {
|
|
91
177
|
Log ("尝试下载:{0}" -f $u)
|
|
92
178
|
try {
|
|
93
|
-
Invoke-
|
|
179
|
+
Invoke-DownloadFile -Uri $u.Trim() -OutFile $tmp -TimeoutSec 90
|
|
94
180
|
if ((Test-Path -LiteralPath $tmp) -and ((Get-Item -LiteralPath $tmp).Length -gt 0)) {
|
|
95
181
|
$pkgPath = $tmp
|
|
96
182
|
Log ("下载成功:{0:N0} 字节" -f (Get-Item -LiteralPath $tmp).Length)
|
|
@@ -110,8 +196,13 @@ if ($TgzFile -and (Test-Path -LiteralPath $TgzFile)) {
|
|
|
110
196
|
}
|
|
111
197
|
|
|
112
198
|
if ($Sha256) {
|
|
113
|
-
$hash =
|
|
114
|
-
|
|
199
|
+
$hash = ''
|
|
200
|
+
try { $hash = [string]((Get-FileHash -LiteralPath $pkgPath -Algorithm SHA256).Hash) } catch { $hash = '' }
|
|
201
|
+
$hash = $hash.Trim().ToLower()
|
|
202
|
+
Log ("sha256:{0}" -f $(if ($hash) { $hash } else { '(算不出来)' }))
|
|
203
|
+
if (-not $hash) {
|
|
204
|
+
EmitResult $false '本机 PowerShell 无法计算安装包 sha256(Get-FileHash 不可用且 .NET 回退也失败)' ''
|
|
205
|
+
}
|
|
115
206
|
if ($hash -ne $Sha256.ToLower()) {
|
|
116
207
|
Log 'sha256 与清单不一致,放弃安装'
|
|
117
208
|
Remove-Item -LiteralPath $tmp -Force -ErrorAction SilentlyContinue
|