| 1 | # Executed by the authenticated, fixed-VM PowerShell Direct maintenance session. |
| 2 | param([guid]$VMId,[string]$GUIUserSID,[string]$Stage,[string]$ArchiveSHA256,[bool]$Tools,[string]$PackagesJSON,[string]$CLIJSON) |
| 3 | $ErrorActionPreference='Stop' |
| 4 | $ProgressPreference='SilentlyContinue' |
| 5 | if ([guid](Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters').VirtualMachineId -ne $VMId -or |
| 6 | $GUIUserSID -notmatch '^S-1-5-21-' -or $Stage -notlike (Join-Path $env:ProgramFiles 'Cage Component Update\*')) { throw '组件更新目标与客机身份不一致。' } |
| 7 | function Assert-LocalFile([string]$Path) { |
| 8 | for ($entry=Get-Item -LiteralPath $Path -Force; $entry; $entry=if ($entry -is [IO.FileInfo]) {$entry.Directory} else {$entry.Parent}) { |
| 9 | if ($entry.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw '组件目录包含文件链接。' } |
| 10 | } |
| 11 | } |
| 12 | Assert-LocalFile $Stage |
| 13 | $archive=Join-Path $Stage 'update.zip' |
| 14 | if ((Get-FileHash -LiteralPath $archive).Hash -ne $ArchiveSHA256) { throw '传入客机的组件包校验失败。' } |
| 15 | & (Join-Path $env:SystemRoot 'System32/tar.exe') -xf $archive -C $Stage |
| 16 | if ($LASTEXITCODE) { throw '无法展开已校验的组件包。' } |
| 17 | $manifest=Get-Content -LiteralPath (Join-Path $Stage 'native-components.json') -Raw | ConvertFrom-Json |
| 18 | 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 '客机组件清单无效。' } |
| 19 | $roots=@{bridge=(Join-Path $env:ProgramFiles ('Cage Guest Bridge\'+$VMId));network=(Join-Path $env:ProgramFiles ('Cage Guest Network\'+$VMId))} |
| 20 | foreach ($root in $roots.Values) { Assert-LocalFile $root } |
| 21 | $targets=@{} |
| 22 | foreach ($file in Get-ChildItem -LiteralPath (Join-Path $Stage 'files') -File -Recurse -Force) { |
| 23 | Assert-LocalFile $file.FullName |
| 24 | $relative=$file.FullName.Substring((Join-Path $Stage 'files').Length+1) |
| 25 | $parts=$relative -split '\\',2 |
| 26 | if ($parts.Count -ne 2 -or !$roots.ContainsKey($parts[0]) -or $parts[1] -match '(^|\\)\.\.?(\\|$)|:') { throw '组件安装位置无效。' } |
| 27 | $targets[$relative.Replace('\','/')]=Join-Path $roots[$parts[0]] $parts[1] |
| 28 | } |
| 29 | foreach ($entry in $manifest.files) { |
| 30 | if (!$entry.target) { continue } |
| 31 | if (!$targets.ContainsKey($entry.target) -or (Get-FileHash -LiteralPath (Join-Path $Stage ('files/'+$entry.target))).Hash -ne $entry.installed_sha256) { throw '待安装组件与清单不一致。' } |
| 32 | } |
| 33 | $guiTask="Cage-GUI-Bridge-$VMId-$GUIUserSID" |
| 34 | $networkTask="Cage-Packet-Bridge-$VMId" |
| 35 | $tasks=@() |
| 36 | foreach ($spec in @(@($guiTask,'bridge','Cage.GuestClipboard.exe',"Cage protected GUI bridge $VMId $GUIUserSID"),@($networkTask,'network','Cage.GuestNetwork.exe',"Cage protected packet bridge $VMId $GUIUserSID"))) { |
| 37 | $task=Get-ScheduledTask -TaskName $spec[0] |
| 38 | if ($task.Description -cne $spec[3] -or $task.Actions.Count -ne 1 -or $task.Actions[0].Execute -ine (Join-Path $roots[$spec[1]] $spec[2])) { throw '客机后台任务与已绑定组件不一致。' } |
| 39 | $tasks+=@{Name=$spec[0];Active=($task.State -eq 'Running')} |
| 40 | } |
| 41 | $bootName='Cage-Workbench-Boot-'+$VMId.ToString('D') |
| 42 | $boot=Get-CimInstance Win32_Service -Filter "Name='$bootName'" |
| 43 | if ($boot -and ($boot.StartName -ne 'LocalSystem' -or $boot.PathName -cne ('"'+(Join-Path $roots.bridge 'cage-guest-boot.exe')+'" '+$VMId.ToString('D')))) { throw '客机启动服务与已绑定组件不一致。' } |
| 44 | $backup=Join-Path $Stage 'backup' |
| 45 | $null=New-Item -ItemType Directory -Path $backup |
| 46 | $changed=[Collections.Generic.List[object]]::new() |
| 47 | $runtimes=[Collections.Generic.List[object]]::new() |
| 48 | $stopped=[Collections.Generic.List[string]]::new() |
| 49 | $bootStopped=$false |
| 50 | $committed=$false |
| 51 | function Set-ComponentAccess([string]$Path) { |
| 52 | $acl=[Security.AccessControl.FileSecurity]::new();$acl.SetAccessRuleProtection($true,$false);$acl.SetOwner([Security.Principal.SecurityIdentifier]::new('S-1-5-32-544')) |
| 53 | foreach ($sid in @('S-1-5-18','S-1-5-32-544')) { $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($sid),'FullControl','Allow')) } |
| 54 | $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($GUIUserSID),'ReadAndExecute','Allow')) |
| 55 | Set-Acl -LiteralPath $Path -AclObject $acl |
| 56 | } |
| 57 | function Install-Component([string]$Source,[string]$Target) { |
| 58 | $parent=[IO.Path]::GetDirectoryName($Target) |
| 59 | $null=New-Item -ItemType Directory -Path $parent -Force |
| 60 | Assert-LocalFile $parent |
| 61 | $saved=Join-Path $backup ([string]$changed.Count) |
| 62 | $exists=Test-Path -LiteralPath $Target |
| 63 | if ($exists) { Assert-LocalFile $Target; Copy-Item -LiteralPath $Target -Destination $saved; Set-Acl -LiteralPath $saved -AclObject (Get-Acl -LiteralPath $Target) } |
| 64 | $changed.Add(@{Target=$Target;Saved=$saved;Existed=$exists}) |
| 65 | $next=$Target+'.'+[guid]::NewGuid().ToString('N')+'.tmp' |
| 66 | try { |
| 67 | Copy-Item -LiteralPath $Source -Destination $next |
| 68 | Set-ComponentAccess $next |
| 69 | if ($exists) { [IO.File]::Replace($next,$Target,[Management.Automation.Language.NullString]::Value) } |
| 70 | else { [IO.File]::Move($next,$Target) } |
| 71 | } finally { if (Test-Path -LiteralPath $next) { Remove-Item -LiteralPath $next } } |
| 72 | } |
| 73 | try { |
| 74 | foreach ($task in $tasks) { |
| 75 | if (!$task.Active) { continue } |
| 76 | Stop-ScheduledTask -TaskName $task.Name |
| 77 | $stopped.Add($task.Name) |
| 78 | $deadline=[DateTime]::UtcNow.AddSeconds(15) |
| 79 | while ((Get-ScheduledTask -TaskName $task.Name).State -eq 'Running' -and [DateTime]::UtcNow -lt $deadline) { Start-Sleep -Milliseconds 100 } |
| 80 | if ((Get-ScheduledTask -TaskName $task.Name).State -eq 'Running') { throw '后台组件仍在退出,已保留原文件,请稍后重试。' } |
| 81 | } |
| 82 | if ($boot -and $boot.State -eq 'Running') { Stop-Service -Name $bootName; $bootStopped=$true } |
| 83 | foreach ($relative in $targets.Keys) { Install-Component (Join-Path $Stage ('files/'+$relative)) $targets[$relative] } |
| 84 | if ($Tools) { |
| 85 | $toolStage=Join-Path $roots.bridge 'setup-packages' |
| 86 | $null=New-Item -ItemType Directory -Path $toolStage -Force |
| 87 | Assert-LocalFile $toolStage |
| 88 | foreach ($file in Get-ChildItem -LiteralPath (Join-Path $Stage 'tools') -File) { Copy-Item -LiteralPath $file.FullName -Destination $toolStage -Force } |
| 89 | # Keep long editor paths inside their directory throughout publication. |
| 90 | # Stage under the protected bridge so the paired user inherits read access. |
| 91 | $runtime=Join-Path $roots.bridge ('.runtime-'+[guid]::NewGuid().ToString('N')) |
| 92 | $null=New-Item -ItemType Directory -Path $runtime |
| 93 | & (Join-Path $env:SystemRoot 'System32/tar.exe') -xf (Join-Path $toolStage 'extras.zip') -C $runtime |
| 94 | if ($LASTEXITCODE) { throw '环境工具解压失败。' } |
| 95 | foreach ($name in @('node.exe','playwright','vscode-cli','vscode-server','editor-runtime.json')) { |
| 96 | $source=Join-Path $runtime $name |
| 97 | Assert-LocalFile $source |
| 98 | $destination=Join-Path $roots.bridge $name |
| 99 | $saved=Join-Path $backup $name |
| 100 | $exists=Test-Path -LiteralPath $destination |
| 101 | if ($exists) { Assert-LocalFile $destination; Move-Item -LiteralPath $destination -Destination $saved } |
| 102 | $runtimes.Add(@{Target=$destination;Saved=$saved;Existed=$exists;Name=$name}) |
| 103 | Move-Item -LiteralPath $source -Destination $destination |
| 104 | } |
| 105 | $installer=Join-Path $Stage 'install-windows-workbench-components.ps1' |
| 106 | $options=@($VMId,$GUIUserSID,$roots.bridge,$toolStage,$PackagesJSON,$CLIJSON,(Get-FileHash -LiteralPath (Join-Path $toolStage 'extras.zip')).Hash) |
| 107 | & $installer @options 'Prepare' -RuntimeInstalled |
| 108 | & $installer @options 'UserTools' |
| 109 | # UserTools may start the GUI task. All updated binaries are already installed. |
| 110 | } |
| 111 | foreach ($entry in $manifest.files) { |
| 112 | if ($entry.target -and (Get-FileHash -LiteralPath $targets[$entry.target]).Hash -ne $entry.installed_sha256) { throw '安装后的组件校验失败。' } |
| 113 | } |
| 114 | & (Join-Path $roots.bridge 'Cage.GuestClipboard.exe') self-test | Out-Null |
| 115 | if ($LASTEXITCODE) { throw '新客机连接组件未通过自检。' } |
| 116 | Install-Component (Join-Path $Stage 'native-components.json') (Join-Path $roots.bridge 'native-components.json') |
| 117 | foreach ($name in $stopped) { Start-ScheduledTask -TaskName $name } |
| 118 | if ($bootStopped) { Start-Service -Name $bootName } |
| 119 | $committed=$true |
| 120 | } finally { |
| 121 | if (!$committed) { |
| 122 | foreach ($name in $stopped) { Stop-ScheduledTask -TaskName $name -ErrorAction Continue } |
| 123 | if ($bootStopped) { Stop-Service -Name $bootName -ErrorAction Continue } |
| 124 | for ($index=$runtimes.Count-1; $index -ge 0; $index--) { |
| 125 | $item=$runtimes[$index] |
| 126 | if (Test-Path -LiteralPath $item.Target) { Move-Item -LiteralPath $item.Target -Destination (Join-Path $Stage ('failed-'+$item.Name)) } |
| 127 | if ($item.Existed) { Move-Item -LiteralPath $item.Saved -Destination $item.Target } |
| 128 | } |
| 129 | for ($index=$changed.Count-1; $index -ge 0; $index--) { |
| 130 | $item=$changed[$index] |
| 131 | if ($item.Existed) { Copy-Item -LiteralPath $item.Saved -Destination $item.Target -Force; Set-Acl -LiteralPath $item.Target -AclObject (Get-Acl -LiteralPath $item.Saved) } |
| 132 | elseif (Test-Path -LiteralPath $item.Target) { Remove-Item -LiteralPath $item.Target } |
| 133 | } |
| 134 | foreach ($name in $stopped) { Start-ScheduledTask -TaskName $name -ErrorAction Continue } |
| 135 | if ($bootStopped) { Start-Service -Name $bootName -ErrorAction Continue } |
| 136 | } |
| 137 | if ($runtime -and (Test-Path -LiteralPath $runtime)) { Move-Item -LiteralPath $runtime -Destination (Join-Path $Stage 'runtime-staging') } |
| 138 | } |
| 139 | Write-Output '客机组件已同步,原配对密钥和用户目录已保留。' |