| 1 | # Used by complete-windows-guest.ps1 through an authenticated VM-only |
| 2 | # PowerShell Direct session, after the ordinary GUI SID has been pinned. |
| 3 | param([guid]$VMId,[string]$GUIUserSID,[string]$Bridge,[string]$Stage,[string]$PackagesJSON,[string]$CLIJSON,[string]$ExtrasSHA,[ValidateSet('Prepare','UserTools')][string]$Phase,[switch]$RuntimeInstalled) |
| 4 | $Packages=$PackagesJSON | ConvertFrom-Json |
| 5 | $CLI=$CLIJSON | ConvertFrom-Json |
| 6 | $ErrorActionPreference='Stop' |
| 7 | if ([guid](Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters').VirtualMachineId -ne $VMId -or |
| 8 | $Bridge -ne (Join-Path $env:ProgramFiles ("Cage Guest Bridge\"+$VMId)) -or $Stage -ne (Join-Path $Bridge 'setup-packages')) { |
| 9 | throw 'Incorrect guest installation target.' |
| 10 | } |
| 11 | foreach ($file in @($Packages.desktop,$Packages.winfsp,$Packages.sshfs,$CLI.uv,$CLI.python,$CLI.claude,$CLI.git)) { |
| 12 | if ((Get-FileHash -LiteralPath (Join-Path $Stage $file.filename)).Hash -ne $file.sha256) { throw ('Guest package digest mismatch: '+$file.filename) } |
| 13 | } |
| 14 | $extras=Join-Path $Stage 'extras.zip' |
| 15 | if ((Get-FileHash -LiteralPath $extras).Hash -ne $ExtrasSHA) { throw 'Guest components digest mismatch.' } |
| 16 | $taskName="Cage-GUI-Bridge-$VMId-$GUIUserSID" |
| 17 | $bridgeTask=Get-ScheduledTask -TaskName $taskName |
| 18 | if ($bridgeTask.Description -cne "Cage protected GUI bridge $VMId $GUIUserSID" -or $bridgeTask.Principal.RunLevel -ne 'Limited' -or |
| 19 | $bridgeTask.Actions[0].Execute -ne (Join-Path $Bridge 'Cage.GuestClipboard.exe')) { throw 'The registered bridge does not match this guest.' } |
| 20 | |
| 21 | # All paths below are inside the administrator-owned bridge. Extraction and |
| 22 | # package operations never take a filename supplied by an ordinary guest user. |
| 23 | function Install-GuestComponents { |
| 24 | # Windows PowerShell 5.1 ZIP APIs and Copy-Item truncate long editor |
| 25 | # paths on a fresh Windows install. The OS-supplied archive tool supports |
| 26 | # long paths. Only the verified, Cage-assembled application archive is |
| 27 | # extracted into the administrator-owned guest bridge. |
| 28 | if (!$RuntimeInstalled) { |
| 29 | & (Join-Path $env:SystemRoot 'System32/tar.exe') -xf $extras -C $Bridge |
| 30 | if ($LASTEXITCODE -ne 0) { throw 'Could not unpack the verified guest application components.' } |
| 31 | } |
| 32 | |
| 33 | foreach ($package in @($Packages.winfsp,$Packages.sshfs)) { |
| 34 | $file=Join-Path $Stage $package.filename |
| 35 | $proc=Start-Process -FilePath (Join-Path $env:SystemRoot 'System32/msiexec.exe') -ArgumentList ('/i "'+$file+'" /qn /norestart') -Wait -PassThru |
| 36 | if ($proc.ExitCode -notin @(0,3010)) { throw ('Windows file-system driver install failed: '+$package.filename+' ('+$proc.ExitCode+')') } |
| 37 | } |
| 38 | |
| 39 | $msix=Join-Path $Stage $Packages.desktop.filename |
| 40 | $signature=Get-AuthenticodeSignature -LiteralPath $msix |
| 41 | if ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.Subject -notmatch 'Anthropic,? PBC') { throw 'The official Claude Desktop package signature is invalid.' } |
| 42 | $provisioned=@(Get-AppxProvisionedPackage -Online | Where-Object DisplayName -ceq 'Claude') |
| 43 | if ($provisioned.Count -gt 1 -or ($provisioned.Count -eq 1 -and $provisioned[0].PackageName -notmatch '^Claude_[0-9.]+_x64__pzs8sxrjxfjjc$')) { throw 'An unexpected existing Claude registration was preserved.' } |
| 44 | if (!$provisioned.Count) { |
| 45 | $null=Add-AppxProvisionedPackage -Online -PackagePath $msix -SkipLicense -Regions 'all' |
| 46 | } |
| 47 | $name='Cage-Workbench-Boot-'+$VMId.ToString('D') |
| 48 | $image='"'+(Join-Path $Bridge 'cage-guest-boot.exe')+'" '+$VMId.ToString('D') |
| 49 | $service=Get-CimInstance Win32_Service -Filter "Name='$name'" |
| 50 | if (!$service) { |
| 51 | $service=New-Service -Name $name -BinaryPathName $image -StartupType Automatic -DisplayName 'Cage dedicated workbench boot sign-in' |
| 52 | } elseif ($service.PathName -cne $image -or $service.StartName -ne 'LocalSystem') { throw 'An unrelated boot service was preserved.' } |
| 53 | Start-Service -Name $name |
| 54 | } |
| 55 | if ($Phase -eq 'Prepare') { Install-GuestComponents; return } |
| 56 | |
| 57 | $receipt=Join-Path $Stage 'cli-receipt.in' |
| 58 | if (!(Test-Path -LiteralPath $receipt)) { $f=[IO.File]::Open($receipt,'CreateNew','Write','None'); $f.Dispose() } |
| 59 | $admin=[Security.Principal.SecurityIdentifier]::new('S-1-5-32-544') |
| 60 | function Set-ReceiptAccess([string]$Path,[string]$UserRights) { |
| 61 | $acl=[Security.AccessControl.FileSecurity]::new() |
| 62 | $acl.SetAccessRuleProtection($true,$false) |
| 63 | $acl.SetOwner($admin) |
| 64 | foreach ($sid in @('S-1-5-18','S-1-5-32-544')) { |
| 65 | $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($sid),'FullControl','Allow')) |
| 66 | } |
| 67 | $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($GUIUserSID),$UserRights,'Allow')) |
| 68 | Set-Acl -LiteralPath $Path -AclObject $acl |
| 69 | } |
| 70 | Set-ReceiptAccess $receipt 'Read,Write' |
| 71 | $cliTask="Cage-Workbench-CLI-Setup-$VMId" |
| 72 | $description="Cage guest workbench tool install $VMId $GUIUserSID" |
| 73 | if ($old=Get-ScheduledTask -TaskName $cliTask -ErrorAction SilentlyContinue) { |
| 74 | if ($old.Description -cne $description -or $old.State -eq 'Running') { throw 'A workbench installation is already active.' } |
| 75 | Unregister-ScheduledTask -TaskName $cliTask -Confirm:$false |
| 76 | } |
| 77 | $action=New-ScheduledTaskAction -Execute (Join-Path $env:SystemRoot 'System32/WindowsPowerShell/v1.0/powershell.exe') -Argument ('-NoProfile -NonInteractive -ExecutionPolicy RemoteSigned -File "'+(Join-Path $Bridge 'install-windows-workbench-user-tools.ps1')+'" -BundleDirectory "'+$Stage+'" -BridgeDirectory "'+$Bridge+'"') |
| 78 | $principal=New-ScheduledTaskPrincipal -UserId $GUIUserSID -LogonType Interactive -RunLevel Limited |
| 79 | $settings=New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Minutes 15) |
| 80 | $null=Register-ScheduledTask -TaskName $cliTask -Action $action -Principal $principal -Settings $settings -Description $description |
| 81 | try { |
| 82 | [IO.File]::WriteAllText($receipt,'') |
| 83 | Start-ScheduledTask -TaskName $cliTask |
| 84 | $deadline=[DateTime]::UtcNow.AddMinutes(15) |
| 85 | do { |
| 86 | Start-Sleep -Seconds 1 |
| 87 | $task=Get-ScheduledTask -TaskName $cliTask |
| 88 | $info=Get-ScheduledTaskInfo -TaskName $cliTask |
| 89 | $ran=$info.LastRunTime.Year -gt 2000 -and $info.LastTaskResult -notin @(267008,267009,267011) |
| 90 | } while ((!$ran -or $task.State -eq 'Running') -and [DateTime]::UtcNow -lt $deadline) |
| 91 | if (!$ran -or $task.State -eq 'Running' -or $info.LastTaskResult -ne 0) { throw 'Claude Code tools did not finish for the signed-in standard guest user.' } |
| 92 | # Copy only the bounded allowlisted JSON fields from the file opened |
| 93 | # without write sharing. Never execute a user-supplied receipt path here. |
| 94 | $handle=[IO.File]::Open($receipt,'Open','Read','Read') |
| 95 | try { |
| 96 | if ($handle.Length -lt 2 -or $handle.Length -gt 16384) { throw 'Invalid Claude Code tools receipt.' } |
| 97 | $reader=[IO.StreamReader]::new($handle) |
| 98 | $value=$reader.ReadToEnd() | ConvertFrom-Json |
| 99 | } finally { $handle.Dispose() } |
| 100 | if ($value.version -ne 1 -or $value.claude_sha256 -ne $CLI.claude.sha256) { throw 'Invalid Claude Code version or hash.' } |
| 101 | $result=[ordered]@{version=1} |
| 102 | foreach ($name in @('python','claude','git_bash')) { |
| 103 | $hash=$name+'_sha256' |
| 104 | if (![IO.Path]::IsPathRooted($value.$name) -or $value.$hash -notmatch '^[a-fA-F0-9]{64}$') { throw 'Invalid Claude tool record.' } |
| 105 | $result[$name]=$value.$name |
| 106 | $result[$hash]=$value.$hash.ToLowerInvariant() |
| 107 | } |
| 108 | $target=Join-Path $Bridge 'cli-tools.json' |
| 109 | [IO.File]::WriteAllText($target,($result | ConvertTo-Json -Compress),[Text.UTF8Encoding]::new($false)) |
| 110 | Set-ReceiptAccess $target 'Read' |
| 111 | } finally { |
| 112 | if ((Get-ScheduledTask -TaskName $cliTask).State -eq 'Running') { Stop-ScheduledTask -TaskName $cliTask } |
| 113 | Unregister-ScheduledTask -TaskName $cliTask -Confirm:$false |
| 114 | } |
| 115 | if ($bridgeTask.State -eq 'Running') { |
| 116 | Stop-ScheduledTask -TaskName $taskName |
| 117 | $deadline=[DateTime]::UtcNow.AddSeconds(15) |
| 118 | while ((Get-ScheduledTask -TaskName $taskName).State -eq 'Running' -and [DateTime]::UtcNow -lt $deadline) { Start-Sleep -Milliseconds 250 } |
| 119 | } |
| 120 | Start-ScheduledTask -TaskName $taskName |
| 121 | |
| 122 | # Packages have been verified and installed. The instance-scoped host cache |
| 123 | # permits repairs; the guest does not need a second copy of the installers. |
| 124 | foreach ($package in @($Packages.desktop,$Packages.winfsp,$Packages.sshfs,$CLI.uv,$CLI.python,$CLI.claude,$CLI.git)) { |
| 125 | [IO.File]::Delete((Join-Path $Stage $package.filename)) |
| 126 | } |
| 127 | [IO.File]::Delete($extras) |