| 1 | #requires -Version 5.1 |
| 2 | [CmdletBinding()] |
| 3 | param( |
| 4 | [Parameter(Mandatory)][string]$Profile, |
| 5 | [Parameter(Mandatory)][string]$ManifestPath, |
| 6 | [Parameter(Mandatory)][ValidatePattern('^[0-9A-Fa-f]{64}$')][string]$ManifestSHA256, |
| 7 | [switch]$Tools, |
| 8 | [switch]$HostOnly, |
| 9 | [string]$BindingSHA256, |
| 10 | [pscredential]$GuestAdministrator |
| 11 | ) |
| 12 | $ErrorActionPreference='Stop' |
| 13 | $ProgressPreference='SilentlyContinue' |
| 14 | [Console]::OutputEncoding=[Text.UTF8Encoding]::new($false) |
| 15 | # Fixed process exits carry the failed stage across RunAs without a writable |
| 16 | # result file. The ordinary parent reports the same stage to the workbench. |
| 17 | $maintenanceFailures=@{ |
| 18 | 1=@('FAILED','Windows 维护未完成。请从 Cage 重新发起原操作,仍失败时导出诊断包。') |
| 19 | 41=@('VALIDATION','Windows 环境绑定或组件清单未通过校验。请重新发起原操作,组件包仍无法核验时重新安装完整 Cage 应用。') |
| 20 | 42=@('HOST_MANAGER','Windows 系统管理助手安装未完成。请重试修复系统助手,仍失败时检查系统服务或安全软件记录并导出诊断包。') |
| 21 | 43=@('GUEST_CONNECTION','Windows 客机连接未完成。请启动并登录已绑定客机,使用该客机的管理员账户重试。') |
| 22 | 44=@('GUEST_COMPONENTS','Windows 客机组件安装未完成。请保持原客机运行,重试同步环境组件,仍失败时导出诊断包。') |
| 23 | 45=@('HOST_RELAY','Windows 主机连接组件更新未完成。请关闭占用连接组件的程序,再重试同步环境组件。') |
| 24 | 46=@('PACKAGE_PREPARATION','Windows 组件包准备未完成。请检查应用目录和系统盘空间后重试,更新工具时同时检查已选代理。') |
| 25 | 47=@('AUTHORIZATION','Windows 管理员授权窗口未能打开。请从本机 Cage 重新发起操作,并使用可完成管理员授权的 Windows 账户。') |
| 26 | 48=@('AUTHORIZATION_CANCELED','已取消 Windows 管理员授权。请重新发起原操作,并在 Windows 系统授权窗口中确认。') |
| 27 | } |
| 28 | $maintenanceExitCode=41 |
| 29 | trap { |
| 30 | if ($maintenanceExitCode -eq 47) { |
| 31 | for ($cause=$_.Exception; $cause; $cause=$cause.InnerException) { |
| 32 | if ($cause -is [ComponentModel.Win32Exception] -and $cause.NativeErrorCode -eq 1223) { $maintenanceExitCode=48; break } |
| 33 | } |
| 34 | } |
| 35 | if (!$maintenanceFailures.ContainsKey($maintenanceExitCode)) { $maintenanceExitCode=1 } |
| 36 | $failure=$maintenanceFailures[$maintenanceExitCode] |
| 37 | [Console]::Error.WriteLine(('CAGE_WINDOWS_MAINTENANCE_'+$failure[0]+' '+$failure[1])) |
| 38 | [Console]::Error.WriteLine($_.Exception.Message) |
| 39 | exit $maintenanceExitCode |
| 40 | } |
| 41 | |
| 42 | function Invoke-CageMaintenanceElevation([string]$ScriptPath,[hashtable]$Parameters) { |
| 43 | $payload=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes(($Parameters|ConvertTo-Json -Compress))) |
| 44 | $script=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($ScriptPath)) |
| 45 | $command='$ErrorActionPreference=''Stop'';$p=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('''+$payload+'''))|ConvertFrom-Json;$a=@{};$p.PSObject.Properties|ForEach-Object{$a[$_.Name]=$_.Value};$s=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('''+$script+'''));try{$global:LASTEXITCODE=0;& $s @a;exit $LASTEXITCODE}catch{Write-Error $_ -ErrorAction Continue;exit 1}' |
| 46 | $encoded=[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($command)) |
| 47 | $process=Start-Process -FilePath (Join-Path ([Environment]::GetFolderPath('System')) 'WindowsPowerShell/v1.0/powershell.exe') -ArgumentList @('-NoLogo','-NoProfile','-ExecutionPolicy','RemoteSigned','-EncodedCommand',$encoded) -Verb RunAs -PassThru |
| 48 | try { |
| 49 | # Retain the native handle before waiting. Windows PowerShell 5.1 can |
| 50 | # otherwise return a null ExitCode after a successful child exit. |
| 51 | $null=$process.Handle |
| 52 | $process.WaitForExit() |
| 53 | if ($null -eq $process.ExitCode) { throw '无法读取系统授权进程的退出状态,请重新发起操作。' } |
| 54 | return [int]$process.ExitCode |
| 55 | } finally { $process.Dispose() } |
| 56 | } |
| 57 | |
| 58 | $bindingPath=Join-Path $Profile 'windows-guest.json' |
| 59 | $item=Get-Item -LiteralPath $bindingPath -Force |
| 60 | if ($item -isnot [IO.FileInfo] -or $item.Length -gt 16384 -or $item.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw '已绑定的 Windows 环境记录无法核验。' } |
| 61 | $bindingHash=(Get-FileHash -LiteralPath $bindingPath -Algorithm SHA256).Hash |
| 62 | if ($BindingSHA256 -and $BindingSHA256 -ne $bindingHash) { throw 'Windows 环境绑定已变化,请重新发起更新。' } |
| 63 | if ((Get-FileHash -LiteralPath $ManifestPath -Algorithm SHA256).Hash -ne $ManifestSHA256) { throw '组件清单已变化,请重新发起更新。' } |
| 64 | $maintenanceExitCode=47 |
| 65 | $identity=[Security.Principal.WindowsIdentity]::GetCurrent() |
| 66 | if (![Security.Principal.WindowsPrincipal]::new($identity).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { |
| 67 | $parameters=@{Profile=$Profile;ManifestPath=$ManifestPath;ManifestSHA256=$ManifestSHA256;BindingSHA256=$bindingHash;Tools=[bool]$Tools;HostOnly=[bool]$HostOnly} |
| 68 | $maintenanceExitCode=Invoke-CageMaintenanceElevation -ScriptPath $PSCommandPath -Parameters $parameters |
| 69 | if ($maintenanceExitCode -ne 0) { throw '提升权限后的 Windows 维护进程未完成。' } |
| 70 | exit 0 |
| 71 | } |
| 72 | $maintenanceExitCode=41 |
| 73 | $binding=Get-Content -LiteralPath $bindingPath -Raw | ConvertFrom-Json |
| 74 | if ($binding.version -ne 1 -or [guid]$binding.vm_id -eq [guid]::Empty) { throw 'Windows 客机绑定无法核验。' } |
| 75 | if (!$HostOnly) { |
| 76 | $maintenanceExitCode=43 |
| 77 | $vm=Hyper-V\Get-VM -Id ([guid]$binding.vm_id) |
| 78 | if ($vm.State -ne 'Running') { throw '请先启动并登录已绑定的 Windows 客机。' } |
| 79 | $maintenanceExitCode=41 |
| 80 | $disks=@($vm | Hyper-V\Get-VMHardDiskDrive) |
| 81 | $pairDirectory=[IO.Path]::GetDirectoryName($binding.relay_executable) |
| 82 | $stagedPairDirectory=Join-Path $binding.instance_directory 'cage-workbench\pair' |
| 83 | if ($binding.version -ne 1 -or $vm.Id -eq [guid]::Empty -or |
| 84 | $binding.gui_user_sid -notmatch '^S-1-5-21-' -or @(Hyper-V\Get-VMNetworkAdapter -VM $vm).Count -ne 0 -or |
| 85 | $disks.Count -ne 1 -or $disks[0].Path -ine (Join-Path $binding.instance_directory 'system.vhdx') -or |
| 86 | ($pairDirectory -ine $stagedPairDirectory -and $pairDirectory -ine $item.Directory.FullName) -or |
| 87 | $binding.relay_executable -ine (Join-Path $pairDirectory 'Cage.GuestClipboard.exe') -or |
| 88 | $binding.pairing_file -ine (Join-Path $pairDirectory 'pairing.dpapi')) { |
| 89 | throw '当前运行的 Windows 客机与保留的绑定不一致。' |
| 90 | } |
| 91 | for ($entry=Get-Item -LiteralPath $binding.relay_executable -Force; $entry; $entry=if ($entry -is [IO.FileInfo]) {$entry.Directory} else {$entry.Parent}) { |
| 92 | if ($entry.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw '主机连接组件路径包含文件链接。' } |
| 93 | } |
| 94 | } else { |
| 95 | $vm=[pscustomobject]@{Id=[guid]$binding.vm_id} |
| 96 | } |
| 97 | $manifest=Get-Content -LiteralPath $ManifestPath -Raw | ConvertFrom-Json |
| 98 | if ($manifest.protocol -ne 1 -or $manifest.system -cne 'windows-11' -or $manifest.revision -notmatch '^[a-f0-9]{64}$' -or @($manifest.files).Count -notin 1..10000) { throw '原生组件清单无效。' } |
| 99 | $kit=[IO.Path]::GetFullPath($PSScriptRoot).TrimEnd('\')+'\' |
| 100 | foreach ($entry in $manifest.files) { |
| 101 | $source=[IO.Path]::GetFullPath((Join-Path $kit $entry.source)) |
| 102 | if (!$source.StartsWith($kit,[StringComparison]::OrdinalIgnoreCase) -or (Get-Item -LiteralPath $source -Force).Attributes -band [IO.FileAttributes]::ReparsePoint -or |
| 103 | (Get-FileHash -LiteralPath $source -Algorithm SHA256).Hash -ne $entry.sha256) { throw '应用组件包已变化,请重新安装完整 Cage 应用。' } |
| 104 | } |
| 105 | # The native host helper is part of the same checked component package. Update |
| 106 | # its fixed-VM service during the existing administrator-authorized maintenance. |
| 107 | # The protected registration supplies the original host user across UAC. |
| 108 | $managerBindingPath=Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) ('Cage\HyperVManager\'+$vm.Id.ToString('D')+'\binding.json') |
| 109 | $managerBindingFile=Get-Item -LiteralPath $managerBindingPath -Force |
| 110 | if ($managerBindingFile.Attributes -band [IO.FileAttributes]::ReparsePoint -or $managerBindingFile.Length -gt 65536) { throw 'Windows 管理助手的登记文件无法核验。' } |
| 111 | $managerBinding=Get-Content -LiteralPath $managerBindingPath -Raw | ConvertFrom-Json |
| 112 | if ([guid]$managerBinding.vm_id -ne $vm.Id -or $managerBinding.host_sid -notmatch '^S-1-(5-21|12-1)-(\d+-){3}\d+$') { throw 'Windows 管理助手的用户或客机身份不匹配。' } |
| 113 | $managerPayload=Join-Path $kit 'payload/Cage.HyperVManager.exe' |
| 114 | $maintenanceExitCode=42 |
| 115 | & (Join-Path $kit 'install-windows-host-manager.ps1') -VMId $vm.Id -HostSID $managerBinding.host_sid -PayloadExecutable $managerPayload -PayloadSHA256 (Get-FileHash -LiteralPath $managerPayload -Algorithm SHA256).Hash -Confirm:$false | Out-Null |
| 116 | if ($HostOnly) { |
| 117 | Write-Output 'Windows 系统管理助手已恢复,可以继续恢复存储迁移。' |
| 118 | exit 0 |
| 119 | } |
| 120 | $maintenanceExitCode=46 |
| 121 | $work=Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) ('Cage\ComponentMaintenance\'+$vm.Id.ToString('D')) |
| 122 | for ($parent=$work; $parent; $parent=[IO.Path]::GetDirectoryName($parent)) { |
| 123 | if ((Test-Path -LiteralPath $parent) -and (Get-Item -LiteralPath $parent -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw '组件维护目录包含文件链接。' } |
| 124 | } |
| 125 | $null=New-Item -ItemType Directory -Path $work -Force |
| 126 | $acl=[Security.AccessControl.DirectorySecurity]::new() |
| 127 | $acl.SetAccessRuleProtection($true,$false) |
| 128 | $acl.SetOwner([Security.Principal.SecurityIdentifier]::new('S-1-5-32-544')) |
| 129 | foreach ($sid in @('S-1-5-18','S-1-5-32-544')) { $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($sid),'FullControl','ContainerInherit,ObjectInherit','None','Allow')) } |
| 130 | Set-Acl -LiteralPath $work -AclObject $acl |
| 131 | $lock=[IO.File]::Open((Join-Path $work 'maintenance.lock'),'OpenOrCreate','ReadWrite','None') |
| 132 | $stage=Join-Path $work ([guid]::NewGuid().ToString('N')) |
| 133 | $session=$null |
| 134 | $remote=$null |
| 135 | $completed=$false |
| 136 | try { |
| 137 | $null=New-Item -ItemType Directory -Path $stage |
| 138 | $files=Join-Path $stage 'files' |
| 139 | $null=New-Item -ItemType Directory -Path $files |
| 140 | foreach ($entry in $manifest.files) { |
| 141 | if (!$entry.target) { continue } |
| 142 | if ($entry.target -notmatch '^(bridge|network)/[^:]+$' -or $entry.target -match '(^|/)\.\.?(/|$)|\\') { throw '组件安装位置无效。' } |
| 143 | $target=Join-Path $files $entry.target |
| 144 | $null=New-Item -ItemType Directory -Path ([IO.Path]::GetDirectoryName($target)) -Force |
| 145 | Copy-Item -LiteralPath (Join-Path $kit $entry.source) -Destination $target |
| 146 | if ((Get-FileHash -LiteralPath $target).Hash -ne $entry.installed_sha256) { throw '复制后的组件摘要不匹配。' } |
| 147 | } |
| 148 | [IO.File]::WriteAllText((Join-Path $stage 'native-components.json'),($manifest | ConvertTo-Json -Depth 8),[Text.UTF8Encoding]::new($false)) |
| 149 | $packages=Get-Content -LiteralPath (Join-Path $kit 'payload/windows-workbench-packages.json') -Raw | ConvertFrom-Json |
| 150 | $cli=Get-Content -LiteralPath (Join-Path $kit 'payload/cli-dependencies.json') -Raw | ConvertFrom-Json |
| 151 | if ($Tools) { |
| 152 | . (Join-Path $kit 'windows-workbench-packages.ps1') |
| 153 | $cache=Join-Path $work 'packages' |
| 154 | $null=New-Item -ItemType Directory -Path $cache -Force |
| 155 | $downloads=@{} |
| 156 | foreach ($spec in @($packages.PSObject.Properties)+@($cli.PSObject.Properties)) { $downloads[$spec.Name]=Get-PinnedPackage $spec.Value $cache } |
| 157 | Add-Type -AssemblyName System.IO.Compression.FileSystem |
| 158 | $bridge=Join-Path $stage 'runtime' |
| 159 | $null=New-Item -ItemType Directory -Path $bridge |
| 160 | $archive=[IO.Compression.ZipFile]::OpenRead($downloads.node) |
| 161 | try { [IO.Compression.ZipFileExtensions]::ExtractToFile($archive.GetEntry('node-v24.22.2-win-x64/node.exe'),(Join-Path $bridge 'node.exe')) } finally { $archive.Dispose() } |
| 162 | Expand-PinnedTar $downloads.playwright (Join-Path $bridge 'playwright') |
| 163 | Expand-PinnedTar $downloads.playwrightCore (Join-Path $bridge 'playwright/node_modules/playwright-core') |
| 164 | [IO.Compression.ZipFile]::ExtractToDirectory($downloads.editorCLI,(Join-Path $bridge 'vscode-cli')) |
| 165 | Expand-PinnedTar $downloads.editorServer (Join-Path $bridge 'vscode-server') |
| 166 | [IO.File]::WriteAllText((Join-Path $bridge 'editor-runtime.json'),'{"commit":"261c84cb1eddf11235f9e2c921425e9663fbe556"}') |
| 167 | $toolStage=Join-Path $stage 'tools' |
| 168 | $null=New-Item -ItemType Directory -Path $toolStage |
| 169 | foreach ($name in @('desktop','winfsp','sshfs','uv','python','claude','git')) { Copy-Item -LiteralPath $downloads[$name] -Destination $toolStage } |
| 170 | & (Join-Path $env:SystemRoot 'System32/tar.exe') -a -cf (Join-Path $toolStage 'extras.zip') -C $bridge . |
| 171 | if ($LASTEXITCODE) { throw '无法准备经过校验的环境工具包。' } |
| 172 | } |
| 173 | $maintenanceExitCode=43 |
| 174 | if (!$GuestAdministrator) { $GuestAdministrator=Get-Credential -Message 'Cage:请输入当前 Windows 客机的管理员账户以更新组件。' } |
| 175 | if (!$GuestAdministrator) { throw '已取消 Windows 组件更新。' } |
| 176 | $session=New-PSSession -VMId $vm.Id -Credential $GuestAdministrator |
| 177 | $remote=Invoke-Command -Session $session -ArgumentList $vm.Id -ScriptBlock { |
| 178 | param($expected) |
| 179 | if ([guid](Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters').VirtualMachineId -ne $expected) { throw 'guest_identity_mismatch' } |
| 180 | $path=Join-Path $env:ProgramFiles ('Cage Component Update\'+[guid]::NewGuid().ToString('N')) |
| 181 | $null=New-Item -ItemType Directory -Path $path -Force |
| 182 | $acl=[Security.AccessControl.DirectorySecurity]::new();$acl.SetAccessRuleProtection($true,$false);$acl.SetOwner([Security.Principal.SecurityIdentifier]::new('S-1-5-32-544')) |
| 183 | foreach ($sid in @('S-1-5-18','S-1-5-32-544')) { $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($sid),'FullControl','ContainerInherit,ObjectInherit','None','Allow')) } |
| 184 | Set-Acl -LiteralPath $path -AclObject $acl |
| 185 | $path |
| 186 | } |
| 187 | $maintenanceExitCode=44 |
| 188 | $archive=Join-Path $work ([guid]::NewGuid().ToString('N')+'.zip') |
| 189 | try { |
| 190 | $entries=@('files','native-components.json') |
| 191 | if ($Tools) { $entries+='tools' } |
| 192 | & (Join-Path $env:SystemRoot 'System32/tar.exe') -a -cf $archive -C $stage @entries |
| 193 | if ($LASTEXITCODE) { throw '无法打包客机组件。' } |
| 194 | Copy-Item -LiteralPath $archive -Destination (Join-Path $remote 'update.zip') -ToSession $session |
| 195 | $hash=(Get-FileHash -LiteralPath $archive).Hash |
| 196 | } finally { if (Test-Path -LiteralPath $archive) { Remove-Item -LiteralPath $archive } } |
| 197 | Copy-Item -LiteralPath (Join-Path $kit 'install-windows-workbench-components.ps1') -Destination $remote -ToSession $session |
| 198 | Invoke-Command -Session $session -FilePath (Join-Path $kit 'update-windows-workbench-components.ps1') -ArgumentList $vm.Id,$binding.gui_user_sid,$remote,$hash,([bool]$Tools),($packages|ConvertTo-Json -Depth 6 -Compress),($cli|ConvertTo-Json -Depth 6 -Compress) |
| 199 | # The host relay is an application file. Pairing bytes and the binding are retained. |
| 200 | $maintenanceExitCode=45 |
| 201 | $relayStage=$binding.relay_executable+'.'+[guid]::NewGuid().ToString('N')+'.tmp' |
| 202 | try { |
| 203 | Copy-Item -LiteralPath (Join-Path $files 'bridge/Cage.GuestClipboard.exe') -Destination $relayStage |
| 204 | Set-Acl -LiteralPath $relayStage -AclObject (Get-Acl -LiteralPath $binding.relay_executable) |
| 205 | [IO.File]::Replace($relayStage,$binding.relay_executable,[Management.Automation.Language.NullString]::Value) |
| 206 | } finally { if (Test-Path -LiteralPath $relayStage) { Remove-Item -LiteralPath $relayStage } } |
| 207 | $maintenanceExitCode=41 |
| 208 | if (@(Hyper-V\Get-VMNetworkAdapter -VM (Hyper-V\Get-VM -Id $vm.Id)).Count -ne 0) { throw '更新期间客机网络配置发生变化。' } |
| 209 | $maintenanceExitCode=44 |
| 210 | $completed=$true |
| 211 | } finally { |
| 212 | if ($session) { |
| 213 | if ($remote -and $completed) { Invoke-Command -Session $session -ArgumentList $remote -ScriptBlock { param($path) Remove-Item -LiteralPath $path -Recurse -Force } -ErrorAction Continue } |
| 214 | elseif ($remote) { Write-Warning ('组件恢复材料保留在客机 '+$remote+',重试会继续使用原环境。') } |
| 215 | Remove-PSSession $session |
| 216 | } |
| 217 | if (Test-Path -LiteralPath $stage) { Remove-Item -LiteralPath $stage -Recurse -Force } |
| 218 | $lock.Dispose() |
| 219 | } |
| 220 | Write-Output 'Windows 客机组件已完成文件核验,已保留账户、项目和配对资料。' |
| 221 | exit 0 |