| 1 | #requires -Version 5.1 |
| 2 | #requires -RunAsAdministrator |
| 3 | [CmdletBinding()] |
| 4 | param( |
| 5 | [Parameter(Mandatory)][guid]$VMId, |
| 6 | [Parameter(Mandatory)][string]$InstanceDirectory, |
| 7 | [Parameter(Mandatory)][string]$HostProfileDirectory, |
| 8 | [pscredential]$GuestAdministrator, |
| 9 | [string]$HostUserSID = ([Security.Principal.WindowsIdentity]::GetCurrent().User.Value), |
| 10 | [string]$StateDirectory, |
| 11 | [string]$ManifestPath, |
| 12 | [string]$ManifestSHA256, |
| 13 | [object]$HostEnrollment |
| 14 | ) |
| 15 | $ErrorActionPreference = 'Stop' |
| 16 | $ProgressPreference = 'SilentlyContinue' |
| 17 | $payload = Join-Path $PSScriptRoot 'payload' |
| 18 | $bridgeScripts = Join-Path $PSScriptRoot 'guest-clipboard-windows' |
| 19 | $componentManifest=$null |
| 20 | if ($ManifestPath) { |
| 21 | $manifestFile=Get-Item -LiteralPath $ManifestPath -Force |
| 22 | if ($ManifestSHA256 -notmatch '^[a-fA-F0-9]{64}$' -or $manifestFile -isnot [IO.FileInfo] -or $manifestFile.Length -gt 4MB -or |
| 23 | $manifestFile.Attributes -band [IO.FileAttributes]::ReparsePoint -or (Get-FileHash -LiteralPath $ManifestPath).Hash -ne $ManifestSHA256) { |
| 24 | throw '组件清单无法核验,请从 Cage 重新继续安装。' |
| 25 | } |
| 26 | $componentManifest=Get-Content -LiteralPath $ManifestPath -Raw | ConvertFrom-Json |
| 27 | if ($componentManifest.protocol -ne 1 -or $componentManifest.system -cne 'windows-11' -or $componentManifest.revision -notmatch '^[a-f0-9]{64}$') { throw '原生组件清单无效。' } |
| 28 | $kitRoot=[IO.Path]::GetFullPath($PSScriptRoot).TrimEnd('\')+'\' |
| 29 | foreach ($entry in $componentManifest.files) { |
| 30 | $source=[IO.Path]::GetFullPath((Join-Path $kitRoot $entry.source)) |
| 31 | if (!$source.StartsWith($kitRoot,[StringComparison]::OrdinalIgnoreCase) -or (Get-FileHash -LiteralPath $source).Hash -ne $entry.sha256) { |
| 32 | throw '当前应用组件包已变化,请重新继续安装。' |
| 33 | } |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | function Get-LocalDirectory([string]$Path) { |
| 38 | $dir = Get-Item -LiteralPath $Path -Force |
| 39 | if ($dir -isnot [IO.DirectoryInfo] -or $dir.FullName.StartsWith('\\') -or |
| 40 | [IO.DriveInfo]::new($dir.Root.FullName).DriveType -ne 'Fixed') { throw 'A local fixed-disk directory is required.' } |
| 41 | for ($parent=$dir; $parent; $parent=$parent.Parent) { |
| 42 | if ($parent.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'The installation path crosses a filesystem link.' } |
| 43 | } |
| 44 | return $dir.FullName |
| 45 | } |
| 46 | |
| 47 | . (Join-Path $PSScriptRoot 'windows-workbench-packages.ps1') |
| 48 | . (Join-Path $PSScriptRoot 'windows-host-image.ps1') |
| 49 | |
| 50 | function Read-CageBinding([string]$Path) { |
| 51 | $item=Get-Item -LiteralPath $Path -Force |
| 52 | if ($item -isnot [IO.FileInfo] -or $item.Attributes -band [IO.FileAttributes]::ReparsePoint -or $item.Length -gt 16384) { throw 'Invalid existing Windows guest binding.' } |
| 53 | $data=Get-Content -LiteralPath $item.FullName -Raw | ConvertFrom-Json |
| 54 | if ($data.version -ne 1 -or [guid]$data.vm_id -ne $VMId -or $data.instance_directory -ne $instance -or |
| 55 | $data.relay_executable -ne (Join-Path $pairDirectory 'Cage.GuestClipboard.exe') -or |
| 56 | $data.pairing_file -ne (Join-Path $pairDirectory 'pairing.dpapi') -or |
| 57 | ($data.network_pairing_file -and $data.network_pairing_file -ne (Join-Path $pairDirectory 'packet.dpapi'))) { |
| 58 | throw 'A different guest is already bound. Its disk and pairing were preserved.' |
| 59 | } |
| 60 | return $data |
| 61 | } |
| 62 | |
| 63 | # The current package's own relay performs the proof, regardless of the path |
| 64 | # stored in the staged profile. A cold bridge may need a few seconds after its |
| 65 | # logon task restarts. Never turn a missing registration into a ready profile. |
| 66 | function Ensure-HostManager { |
| 67 | $manager=Join-Path $payload 'Cage.HyperVManager.exe' |
| 68 | if(!(Test-Path -LiteralPath $manager -PathType Leaf)){throw 'The complete Windows host-manager payload is required.'} |
| 69 | & (Join-Path $PSScriptRoot 'install-windows-host-manager.ps1') -VMId $VMId -HostSID $HostUserSID -PayloadExecutable $manager -PayloadSHA256 (Get-FileHash -LiteralPath $manager -Algorithm SHA256).Hash -Confirm:$false | Out-Null |
| 70 | } |
| 71 | |
| 72 | function Restore-MissingHostEnrollmentKeys($Binding) { |
| 73 | if(!$HostEnrollment){return} |
| 74 | . (Join-Path $PSScriptRoot 'windows-host-enrollment.ps1') |
| 75 | foreach($kind in @('gui','packet')){ |
| 76 | $path=if($kind -ceq 'gui'){$Binding.pairing_file}else{$Binding.network_pairing_file} |
| 77 | if(!$path -or (Test-Path -LiteralPath $path)){continue} |
| 78 | # Only this fresh VM's fixed Cage keys are recovered. Existing host |
| 79 | # DPAPI bytes and model credentials are never replaced or read here. |
| 80 | $key=Invoke-Command -Session $session -ArgumentList $VMId,$Binding.gui_user_sid,$kind -ScriptBlock { |
| 81 | param($expected,$sid,$kind) |
| 82 | if([guid](Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters').VirtualMachineId -ne $expected){throw 'guest_identity_mismatch'} |
| 83 | $name=if($kind -ceq 'gui'){'GuestBridge'}else{'GuestNetwork'} |
| 84 | $file=if($kind -ceq 'gui'){'pairing.bin'}else{'packet.bin'} |
| 85 | $path=Join-Path (Join-Path (Join-Path $env:ProgramData 'Cage') $name) ($expected.ToString('D')+'\'+$file) |
| 86 | $item=Get-Item -LiteralPath $path -Force |
| 87 | if($item -isnot [IO.FileInfo] -or $item.Length -ne 32 -or $item.Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'fresh_pairing_invalid'} |
| 88 | [IO.File]::ReadAllBytes($path) |
| 89 | } |
| 90 | $bytes=[byte[]]$key |
| 91 | try{if($bytes.Length -ne 32){throw 'The retained fresh Cage pairing is invalid.'};Send-CageHostEnrollmentKey $HostEnrollment $kind $Binding.gui_user_sid $bytes}finally{[Array]::Clear($bytes,0,$bytes.Length)} |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | function Complete-CloneSetup([string]$Binding) { |
| 96 | if ($choice.source.host.system -cne 'windows-11') { return } |
| 97 | $answerPath = Join-Path $instance 'windows-guest-tools.iso' |
| 98 | $vm | Hyper-V\Get-VMDvdDrive | Where-Object Path -eq $answerPath | Hyper-V\Remove-VMDvdDrive |
| 99 | [IO.File]::Delete($answerPath) |
| 100 | Remove-CageSetupCredential $VMId $GuestAdministrator $profile $installID $Binding |
| 101 | } |
| 102 | |
| 103 | function Publish-ReadyBinding { |
| 104 | $binding=Read-CageBinding $stageBinding |
| 105 | if (!$binding.network_pairing_file) { throw 'The protected packet pairing is unavailable.' } |
| 106 | if($HostEnrollment){ |
| 107 | Ensure-HostManager |
| 108 | . (Join-Path $PSScriptRoot 'windows-host-enrollment.ps1') |
| 109 | Complete-CloneSetup $stageBinding |
| 110 | Complete-CageHostEnrollment $HostEnrollment $binding.gui_user_sid |
| 111 | return |
| 112 | } |
| 113 | $relay=Join-Path $payload 'Cage.GuestClipboard.exe' |
| 114 | $deadline=[DateTime]::UtcNow.AddSeconds(30) |
| 115 | $ready=$false |
| 116 | do { |
| 117 | # Windows PowerShell 5.1 turns native stderr into a terminating error |
| 118 | # under Stop, even when redirected. A cold relay must reach the retry. |
| 119 | $savedPreference=$ErrorActionPreference |
| 120 | try { $ErrorActionPreference='Continue'; $raw=& $relay --relay-profile $stageBinding status 2>$null } |
| 121 | finally { $ErrorActionPreference=$savedPreference } |
| 122 | if ($LASTEXITCODE -eq 0 -and $raw) { |
| 123 | $state=$raw | ConvertFrom-Json |
| 124 | if ($state.available -and [guid]$state.vm_id -eq $VMId -and $state.gui_user_sid -eq $binding.gui_user_sid -and |
| 125 | $state.browser.installed -and $state.browser.editor_installed -and |
| 126 | $state.capabilities -contains 'cli' -and $state.capabilities -contains 'project-mount' -and $state.capabilities -contains 'desktop') { |
| 127 | try { $ErrorActionPreference='Continue'; $raw='{"action":"status"}' | & $relay --relay-profile $stageBinding desktop 2>$null } |
| 128 | finally { $ErrorActionPreference=$savedPreference } |
| 129 | if ($LASTEXITCODE -eq 0 -and $raw -and ($raw | ConvertFrom-Json).installed) { $ready=$true; break } |
| 130 | } |
| 131 | } |
| 132 | Start-Sleep -Seconds 1 |
| 133 | } while ([DateTime]::UtcNow -lt $deadline) |
| 134 | if (!$ready) { throw 'Sign out and sign back in to the paired standard guest account to finish Windows app registration. Resume setup from Cage.' } |
| 135 | # The ordinary host controller uses only this protected fixed-VM service. |
| 136 | # Host identity is distinct from the GUI account inside the Windows guest. |
| 137 | Ensure-HostManager |
| 138 | # Complete retirement before exposing a ready profile. The staged pairing |
| 139 | # proves an already retired account when a prior publish was interrupted. |
| 140 | Complete-CloneSetup $stageBinding |
| 141 | $tempBinding=Join-Path $profile ('windows-guest.'+[guid]::NewGuid()+'.tmp') |
| 142 | try { |
| 143 | [IO.File]::Copy($stageBinding,$tempBinding,$false) |
| 144 | Set-Acl -LiteralPath $tempBinding -AclObject (Get-Acl -LiteralPath $stageBinding) |
| 145 | [IO.File]::Move($tempBinding,$finalBinding) |
| 146 | } finally { if ([IO.File]::Exists($tempBinding)) { [IO.File]::Delete($tempBinding) } } |
| 147 | } |
| 148 | |
| 149 | $instance=Get-LocalDirectory $InstanceDirectory |
| 150 | $profile=Get-LocalDirectory $HostProfileDirectory |
| 151 | $null=Get-LocalDirectory $payload |
| 152 | $choice=Get-Content -LiteralPath (Join-Path $profile 'guest-install.json') -Raw | ConvertFrom-Json |
| 153 | $installID=[guid]$choice.id |
| 154 | $anchor=Get-Item -LiteralPath (Join-Path $profile 'state') -Force |
| 155 | if(!$StateDirectory){$StateDirectory=if($anchor.Attributes -band [IO.FileAttributes]::ReparsePoint){$targets=@($anchor.Target);if($targets.Count -ne 1){throw 'The selected physical state directory changed.'};$targets[0]}else{$anchor.FullName}} |
| 156 | $physicalState=Get-LocalDirectory $StateDirectory |
| 157 | if($anchor.Attributes -band [IO.FileAttributes]::ReparsePoint){$targets=@($anchor.Target);if($targets.Count -ne 1 -or [IO.Path]::GetFullPath($targets[0]) -ine $physicalState){throw 'The selected physical state directory changed.'}} |
| 158 | elseif($anchor.FullName -ine $physicalState){throw 'The selected physical state directory changed.'} |
| 159 | if ($installID -eq [guid]::Empty -or $choice.system -ne 'windows-11' -or $choice.editor_terms -ne $true -or |
| 160 | [guid][IO.File]::ReadAllText((Join-Path $profile 'windows-install-vm.txt')) -ne $VMId -or |
| 161 | $instance -ine (Join-Path $physicalState ('windows-'+$installID.ToString('N')))) { |
| 162 | throw 'Automatic boot sign-in is restricted to the new VM in this first-run installation.' |
| 163 | } |
| 164 | if($HostEnrollment -and ($HostEnrollment.HostSID -cne $HostUserSID -or [guid]$HostEnrollment.VMID -ne $VMId -or [guid]$HostEnrollment.InstallationID -ne $installID -or |
| 165 | [IO.Path]::GetFullPath($HostEnrollment.Profile) -ine $profile -or [IO.Path]::GetFullPath($HostEnrollment.State) -ine $physicalState)){throw 'Original user enrollment does not match this fixed installation.'} |
| 166 | $vm=Hyper-V\Get-VM -Id $VMId |
| 167 | if ($VMId -eq [guid]::Empty -or $vm.Name -cne ('Cage-'+$installID.ToString('N')) -or $vm.Id -ne $VMId -or $vm.State -ne 'Running' -or $vm.Generation -ne 2 -or |
| 168 | !($vm.ConfigurationLocation -eq $instance -or $vm.ConfigurationLocation.StartsWith($instance.TrimEnd('\')+'\',[StringComparison]::OrdinalIgnoreCase)) -or |
| 169 | @(Hyper-V\Get-VMNetworkAdapter -VM $vm).Count -ne 0 -or @($vm | Hyper-V\Get-VMHardDiskDrive).Count -ne 1 -or |
| 170 | ($vm | Hyper-V\Get-VMHardDiskDrive).Path -ne (Join-Path $instance 'system.vhdx')) { |
| 171 | throw 'Start the selected, isolated Windows guest and finish Windows Setup in its console.' |
| 172 | } |
| 173 | |
| 174 | $workRoot=Join-Path $instance 'cage-workbench' |
| 175 | $pairDirectory=Join-Path $workRoot 'pair' |
| 176 | $stageBinding=Join-Path $pairDirectory 'windows-guest.json' |
| 177 | $completionMarker=Join-Path $pairDirectory 'workbench-components-ready' |
| 178 | $finalBinding=Join-Path $profile 'windows-guest.json' |
| 179 | if (Test-Path -LiteralPath $finalBinding) { |
| 180 | $existing=Read-CageBinding $finalBinding |
| 181 | if (!$existing.network_pairing_file) { throw 'The existing published profile is missing its network pairing.' } |
| 182 | if (Test-Path -LiteralPath (Join-Path $profile ('windows-setup-'+$installID.ToString('N')+'.dpapi'))) { |
| 183 | Complete-CloneSetup $finalBinding |
| 184 | } |
| 185 | Ensure-HostManager |
| 186 | return |
| 187 | } |
| 188 | if([Security.Principal.WindowsIdentity]::GetCurrent().User.Value -cne $HostUserSID -and !$HostEnrollment){throw 'Fresh setup for another host user requires the original user enrollment process.'} |
| 189 | |
| 190 | $null=New-Item -ItemType Directory -Force $workRoot |
| 191 | $null=Get-LocalDirectory $workRoot |
| 192 | $lockPath=Join-Path $workRoot 'setup.lock' |
| 193 | if ((Test-Path -LiteralPath $lockPath) -and ((Get-Item -LiteralPath $lockPath -Force).Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw 'Invalid setup lock.' } |
| 194 | $lock=[IO.File]::Open($lockPath,'OpenOrCreate','ReadWrite','None') |
| 195 | $session=$null |
| 196 | $scratch=$null |
| 197 | try { |
| 198 | if ((Test-Path -LiteralPath $completionMarker) -and (Test-Path -LiteralPath $stageBinding)) { |
| 199 | Publish-ReadyBinding |
| 200 | return |
| 201 | } |
| 202 | if (!$GuestAdministrator) { |
| 203 | Write-Output 'CAGE_GUEST_STAGE windows-11 credentials' |
| 204 | $GuestAdministrator=Get-Credential -Message '先在虚拟机连接窗口完成 Windows 设置并登录桌面,再输入客机管理员账户。新建 ISO 安装请使用安装前设置的本地账户。请保持此 PowerShell 安装窗口开启。' |
| 205 | } else { Write-Output 'CAGE_GUEST_STAGE windows-11 services' } |
| 206 | if (!$GuestAdministrator) { throw 'Windows guest setup canceled.' } |
| 207 | $session=New-PSSession -VMId $VMId -Credential $GuestAdministrator |
| 208 | if ($choice.source.host.system -cne 'windows-11') { Remove-CageISOAnswer $vm $session $instance } |
| 209 | Write-Output 'CAGE_GUEST_STAGE windows-11 services' |
| 210 | $target=Invoke-Command -Session $session -FilePath (Join-Path $PSScriptRoot 'initialize-windows-workbench-user.ps1') -ArgumentList $VMId |
| 211 | $firstBoot=Join-Path $pairDirectory 'first-account-boot' |
| 212 | if (!$target.AlreadySignedIn -and (Test-Path -LiteralPath $firstBoot) -and [IO.File]::ReadAllText($firstBoot) -ne $target.BootID) { |
| 213 | throw 'The guest has rebooted. Wait for the dedicated workbench account to sign in, or use the Windows sign-in screen if it was manually locked.' |
| 214 | } |
| 215 | |
| 216 | if (Test-Path -LiteralPath $stageBinding) { |
| 217 | $staged=Read-CageBinding $stageBinding |
| 218 | if ($staged.gui_user_sid -ne $target.SID) { throw 'Sign in to the already paired Windows guest account to resume.' } |
| 219 | } |
| 220 | $cache=Join-Path $workRoot 'downloads' |
| 221 | $null=New-Item -ItemType Directory -Force $cache |
| 222 | $null=Get-LocalDirectory $cache |
| 223 | $packages=Get-Content -LiteralPath (Join-Path $payload 'windows-workbench-packages.json') -Raw | ConvertFrom-Json |
| 224 | $cli=Get-Content -LiteralPath (Join-Path $payload 'cli-dependencies.json') -Raw | ConvertFrom-Json |
| 225 | $files=@{} |
| 226 | Write-Output 'CAGE_GUEST_STAGE windows-11 media' |
| 227 | foreach ($spec in @($packages.PSObject.Properties)+@($cli.PSObject.Properties)) { |
| 228 | $files[$spec.Name]=Get-PinnedPackage $spec.Value $cache |
| 229 | } |
| 230 | |
| 231 | Write-Output 'CAGE_GUEST_STAGE windows-11 tools' |
| 232 | $scratch=Join-Path $workRoot ('stage-'+[guid]::NewGuid()) |
| 233 | $null=New-Item -ItemType Directory $scratch |
| 234 | $core=Join-Path $scratch 'core' |
| 235 | $null=New-Item -ItemType Directory $core |
| 236 | foreach ($name in @('Cage.GuestClipboard.exe','cage-guest-files.exe','cage-guest-boot.exe')) { Copy-Item -LiteralPath (Join-Path $payload $name) -Destination $core } |
| 237 | if (!(Test-Path -LiteralPath $stageBinding)) { |
| 238 | $null=& (Join-Path $bridgeScripts 'install.ps1') -VMId $VMId -InstanceDirectory $instance -GUIUserSID $target.SID -GuestAdministrator $GuestAdministrator -PayloadDirectory $core -HostProfileDirectory $pairDirectory -HostUserSID $HostUserSID -HostEnrollment $HostEnrollment -Confirm:$false |
| 239 | } |
| 240 | $staged=Read-CageBinding $stageBinding |
| 241 | if ($staged.gui_user_sid -ne $target.SID) { throw 'The staged bridge belongs to another user.' } |
| 242 | |
| 243 | Add-Type -AssemblyName System.IO.Compression.FileSystem |
| 244 | if (!$staged.network_pairing_file) { |
| 245 | $driver=Join-Path $scratch 'driver' |
| 246 | [IO.Compression.ZipFile]::ExtractToDirectory($files.wintun,$driver) |
| 247 | $null=& (Join-Path $bridgeScripts 'install-network.ps1') -ProfilePath $stageBinding -GuestAdministrator $GuestAdministrator -AgentPath (Join-Path $core 'Cage.GuestClipboard.exe') -WintunPath (Join-Path $driver 'wintun/bin/amd64/wintun.dll') -WintunLicense (Join-Path $driver 'wintun/LICENSE.txt') -HostEnrollment $HostEnrollment -Confirm:$false |
| 248 | } |
| 249 | $staged=Read-CageBinding $stageBinding |
| 250 | Restore-MissingHostEnrollmentKeys $staged |
| 251 | |
| 252 | $extras=Join-Path $scratch 'extras' |
| 253 | $null=New-Item -ItemType Directory $extras |
| 254 | foreach ($name in @('modules','split-extension','windows-browser.mjs','windows-browser-extensions.mjs','windows-phone-browser.mjs','install-windows-workbench-user-tools.ps1','install-cli.ps1','cli-dependencies.json')) { |
| 255 | Copy-Item -LiteralPath (Join-Path $payload $name) -Destination $extras -Recurse |
| 256 | } |
| 257 | if ($componentManifest) { |
| 258 | foreach ($entry in $componentManifest.files) { |
| 259 | if (!$entry.target -or !$entry.target.StartsWith('bridge/')) { continue } |
| 260 | $relative=$entry.target.Substring(7) |
| 261 | if ($relative -in @('Cage.GuestClipboard.exe','cage-guest-files.exe','cage-guest-boot.exe')) { continue } |
| 262 | if ($entry.source -cne ('payload/'+$relative) -or $relative -match '(^|/)\.\.?(/|$)|[:\\]') { throw '组件安装位置无效。' } |
| 263 | $targetFile=Join-Path $extras $relative |
| 264 | $null=New-Item -ItemType Directory -Path ([IO.Path]::GetDirectoryName($targetFile)) -Force |
| 265 | Copy-Item -LiteralPath (Join-Path $PSScriptRoot $entry.source) -Destination $targetFile -Force |
| 266 | if ((Get-FileHash -LiteralPath $targetFile).Hash -ne $entry.installed_sha256) { throw '复制后的组件摘要不匹配。' } |
| 267 | } |
| 268 | } |
| 269 | $nodeArchive=[IO.Compression.ZipFile]::OpenRead($files.node) |
| 270 | try { [IO.Compression.ZipFileExtensions]::ExtractToFile($nodeArchive.GetEntry('node-v24.22.2-win-x64/node.exe'),(Join-Path $extras 'node.exe')) } finally { $nodeArchive.Dispose() } |
| 271 | Expand-PinnedTar $files.playwright (Join-Path $extras 'playwright') |
| 272 | Expand-PinnedTar $files.playwrightCore (Join-Path $extras 'playwright/node_modules/playwright-core') |
| 273 | [IO.Compression.ZipFile]::ExtractToDirectory($files.editorCLI,(Join-Path $extras 'vscode-cli')) |
| 274 | Expand-PinnedTar $files.editorServer (Join-Path $extras 'vscode-server') |
| 275 | [IO.File]::WriteAllText((Join-Path $extras 'editor-runtime.json'),'{"commit":"261c84cb1eddf11235f9e2c921425e9663fbe556"}') |
| 276 | [IO.File]::WriteAllText((Join-Path $extras 'guest-config.json'),'{"network_mode":"packet"}') |
| 277 | # Transfer large trees in one archive over the authenticated VM session. |
| 278 | $zipPath=Join-Path $scratch 'extras.zip' |
| 279 | & (Join-Path $env:SystemRoot 'System32/tar.exe') -a -cf $zipPath -C $extras . |
| 280 | if ($LASTEXITCODE -ne 0) { throw 'Could not stage the guest application archive.' } |
| 281 | $guestStage=Invoke-Command -Session $session -ArgumentList $target.Program -ScriptBlock { |
| 282 | param($program) |
| 283 | $path=Join-Path $program 'setup-packages' |
| 284 | if (Test-Path -LiteralPath $path) { if ((Get-Item -LiteralPath $path -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Invalid protected staging directory.' } } |
| 285 | else { $null=New-Item -ItemType Directory $path } |
| 286 | $path |
| 287 | } |
| 288 | foreach ($file in @($zipPath,$files.desktop,$files.winfsp,$files.sshfs,$files.uv,$files.python,$files.claude,$files.git)) { |
| 289 | Copy-Item -LiteralPath $file -Destination $guestStage -ToSession $session -Force |
| 290 | } |
| 291 | $installer=Join-Path $PSScriptRoot 'install-windows-workbench-components.ps1' |
| 292 | $options=@($VMId,$target.SID,$target.Program,$guestStage,($packages | ConvertTo-Json -Depth 6 -Compress),($cli | ConvertTo-Json -Depth 6 -Compress),(Get-FileHash -LiteralPath $zipPath).Hash) |
| 293 | $null=Invoke-Command -Session $session -FilePath $installer -ArgumentList ($options+@('Prepare')) |
| 294 | if (!$target.AlreadySignedIn) { |
| 295 | # Only this named new VM is rebooted, once. A later manual lock is |
| 296 | # never treated as a request to restart or unlock Windows. |
| 297 | [IO.File]::WriteAllText($firstBoot,$target.BootID) |
| 298 | Remove-PSSession $session; $session=$null |
| 299 | Hyper-V\Stop-VM -VM $vm -ErrorAction Stop |
| 300 | Hyper-V\Start-VM -VM $vm -ErrorAction Stop |
| 301 | $deadline=[DateTime]::UtcNow.AddMinutes(4) |
| 302 | do { |
| 303 | try { |
| 304 | $session=New-PSSession -VMId $VMId -Credential $GuestAdministrator -ErrorAction Stop |
| 305 | $logged=Invoke-Command -Session $session -ArgumentList $VMId,$target.Name -ScriptBlock { |
| 306 | param($expected,$name) |
| 307 | if ([guid](Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters').VirtualMachineId -ne $expected) {throw 'wrong VM'} |
| 308 | (Get-CimInstance Win32_ComputerSystem).UserName -eq ($env:COMPUTERNAME+'\'+$name) |
| 309 | } |
| 310 | if ($logged) {break} |
| 311 | } catch { $logged=$false } |
| 312 | if ($session) { Remove-PSSession $session; $session=$null } |
| 313 | Start-Sleep -Seconds 2 |
| 314 | } while ([DateTime]::UtcNow -lt $deadline) |
| 315 | if (!$session -or !$logged) { throw 'Windows did not finish its first sign-in to the dedicated workbench account. Its account and disk are preserved.' } |
| 316 | } |
| 317 | $null=Invoke-Command -Session $session -FilePath $installer -ArgumentList ($options+@('UserTools')) |
| 318 | if (@(Hyper-V\Get-VMNetworkAdapter -VM (Hyper-V\Get-VM -Id $VMId)).Count -ne 0) { throw 'The Windows guest networking has changed.' } |
| 319 | if ($componentManifest) { |
| 320 | $null=Invoke-Command -Session $session -FilePath (Join-Path $PSScriptRoot 'publish-windows-component-manifest.ps1') -ArgumentList $VMId,$target.SID,($componentManifest|ConvertTo-Json -Depth 8 -Compress) |
| 321 | } |
| 322 | |
| 323 | [IO.File]::WriteAllText($completionMarker,$target.SID) |
| 324 | Write-Output 'CAGE_GUEST_STAGE windows-11 services' |
| 325 | Publish-ReadyBinding |
| 326 | } finally { |
| 327 | if ($session) { Remove-PSSession $session } |
| 328 | if ($scratch -and (Test-Path -LiteralPath $scratch)) { Remove-Item -LiteralPath $scratch -Recurse -Force } |
| 329 | $lock.Dispose() |
| 330 | } |