| 1 | # Run as the already paired ordinary GUI user. All packages are staged offline; |
| 2 | # this installer changes only Cage-owned tool files and the bridge receipt. |
| 3 | [CmdletBinding()] |
| 4 | param( |
| 5 | [Parameter(Mandatory)][string]$BundleDirectory, |
| 6 | [Parameter(Mandatory)][string]$BridgeDirectory, |
| 7 | [string]$ReceiptDirectory = (Join-Path $env:USERPROFILE 'Cage\CLI\install-receipts'), |
| 8 | [switch]$WorkbenchSetup |
| 9 | ) |
| 10 | $ErrorActionPreference = 'Stop' |
| 11 | Set-StrictMode -Version Latest |
| 12 | if (-not [System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform([System.Runtime.InteropServices.OSPlatform]::Windows)) { throw 'Native Windows is required.' } |
| 13 | $user = [Security.Principal.WindowsIdentity]::GetCurrent() |
| 14 | if ((New-Object Security.Principal.WindowsPrincipal($user)).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Use the paired ordinary GUI user.' } |
| 15 | $manifest = Get-Content (Join-Path $PSScriptRoot 'cli-dependencies.json') -Raw | ConvertFrom-Json |
| 16 | $bundle = [IO.Path]::GetFullPath($BundleDirectory) |
| 17 | $bridge = [IO.Path]::GetFullPath($BridgeDirectory) |
| 18 | if (-not (Test-Path (Join-Path $bridge 'Cage.GuestClipboard.exe') -PathType Leaf)) { throw 'The paired GUI bridge must be installed first.' } |
| 19 | function Assert-NoReparse([string]$Path) { |
| 20 | $item = Get-Item -LiteralPath $Path -Force |
| 21 | while ($null -ne $item) { |
| 22 | if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'A Cage tool path is a reparse point.' } |
| 23 | if ($item -is [IO.FileInfo]) { $item = $item.Directory } else { $item = $item.Parent } |
| 24 | } |
| 25 | } |
| 26 | function Protect-Path([string]$Path, [bool]$Directory) { |
| 27 | $ownerSection = [Security.AccessControl.AccessControlSections]::Owner |
| 28 | $accessSection = [Security.AccessControl.AccessControlSections]::Access |
| 29 | if ($Directory) { |
| 30 | $existing = [Security.AccessControl.DirectorySecurity]::new($Path, $ownerSection) |
| 31 | $acl = New-Object Security.AccessControl.DirectorySecurity |
| 32 | } else { |
| 33 | $existing = [Security.AccessControl.FileSecurity]::new($Path, $ownerSection) |
| 34 | $acl = New-Object Security.AccessControl.FileSecurity |
| 35 | } |
| 36 | if ($existing.GetOwner([Security.Principal.SecurityIdentifier]) -ne $user.User) { throw 'The Cage tool path must already belong to the current GUI user.' } |
| 37 | $acl.SetAccessRuleProtection($true, $false) |
| 38 | foreach ($sid in @($user.User, [Security.Principal.SecurityIdentifier]'S-1-5-18', [Security.Principal.SecurityIdentifier]'S-1-5-32-544')) { |
| 39 | if ($Directory) { $rule = New-Object Security.AccessControl.FileSystemAccessRule($sid,'FullControl','ContainerInherit,ObjectInherit','None','Allow') } |
| 40 | else { $rule = New-Object Security.AccessControl.FileSystemAccessRule($sid,'FullControl','Allow') } |
| 41 | $acl.AddAccessRule($rule) |
| 42 | } |
| 43 | # Change only Access on a descriptor loaded without Audit. Set-Acl can |
| 44 | # request SeSecurityPrivilege when persisting a newly built descriptor. |
| 45 | $existing.SetSecurityDescriptorSddlForm($acl.GetSecurityDescriptorSddlForm($accessSection), $accessSection) |
| 46 | $item = Get-Item -LiteralPath $Path -Force |
| 47 | if ($PSVersionTable.PSEdition -eq 'Desktop') { $item.SetAccessControl($existing) } |
| 48 | else { [IO.FileSystemAclExtensions]::SetAccessControl($item, $existing) } |
| 49 | } |
| 50 | function New-PrivateDirectory([string]$Path) { |
| 51 | $parent = [IO.DirectoryInfo]$Path |
| 52 | while (-not $parent.Exists) { $parent = $parent.Parent; if ($null -eq $parent) { throw 'A Cage tool parent is invalid.' } } |
| 53 | Assert-NoReparse $parent.FullName |
| 54 | if (-not (Test-Path -LiteralPath $Path)) { New-Item -ItemType Directory -Path $Path | Out-Null } |
| 55 | Assert-NoReparse $Path; Protect-Path $Path $true |
| 56 | } |
| 57 | function Check-Package($Entry) { |
| 58 | $path = Join-Path $bundle $Entry.filename |
| 59 | Assert-NoReparse $path |
| 60 | if ((Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant() -ne $Entry.sha256) { throw 'An offline native package failed its fixed checksum.' } |
| 61 | return $path |
| 62 | } |
| 63 | $packages = @{} |
| 64 | foreach ($name in @('uv','python','claude','git')) { $packages[$name] = Check-Package $manifest.$name } |
| 65 | foreach ($name in @('claude','git')) { |
| 66 | $signature = Get-AuthenticodeSignature -FilePath $packages[$name] |
| 67 | if ($signature.Status -ne 'Valid') { throw 'An official Windows executable has an invalid Authenticode signature.' } |
| 68 | if ($name -eq 'claude' -and $signature.SignerCertificate.Subject -notmatch 'Anthropic,? PBC') { throw 'The native Claude binary has the wrong signer.' } |
| 69 | } |
| 70 | $tools = Join-Path $env:USERPROFILE 'Cage\CLI\tools' |
| 71 | New-PrivateDirectory $tools |
| 72 | $uvDir = Join-Path $tools ('uv\' + $manifest.uv.version) |
| 73 | New-PrivateDirectory $uvDir |
| 74 | $uv = Join-Path $uvDir 'uv.exe' |
| 75 | if (-not (Test-Path -LiteralPath $uv)) { Expand-Archive -LiteralPath $packages.uv -DestinationPath $uvDir } |
| 76 | Assert-NoReparse $uv |
| 77 | Add-Type -AssemblyName System.IO.Compression.FileSystem |
| 78 | $zip = [IO.Compression.ZipFile]::OpenRead($packages.uv) |
| 79 | try { |
| 80 | $entry = $zip.Entries | Where-Object { $_.FullName -eq 'uv.exe' } | Select-Object -First 1 |
| 81 | if ($null -eq $entry) { throw 'The fixed uv archive has no native executable.' } |
| 82 | $reader = $entry.Open(); $hasher = [Security.Cryptography.SHA256]::Create() |
| 83 | try { $expected = ([BitConverter]::ToString($hasher.ComputeHash($reader))).Replace('-','').ToLowerInvariant() } finally { $reader.Dispose(); $hasher.Dispose() } |
| 84 | if ((Get-FileHash $uv -Algorithm SHA256).Hash.ToLowerInvariant() -ne $expected) { throw 'The Cage-owned uv executable changed.' } |
| 85 | } finally { $zip.Dispose() } |
| 86 | if ((& $uv --version) -notmatch ('^uv ' + [Regex]::Escape($manifest.uv.version) + '(?: |$)')) { throw 'The offline uv version does not match.' } |
| 87 | $pythonDir = Join-Path $tools 'python' |
| 88 | New-PrivateDirectory $pythonDir |
| 89 | $pythonMeta = Join-Path $tools ('python-' + $manifest.python.version + '.json') |
| 90 | $download = [ordered]@{name='cpython';arch=@{family='x86_64';variant=$null};os='windows';libc='none';major=3;minor=13;patch=18;prerelease='';url=([Uri]$packages.python).AbsoluteUri;sha256=$manifest.python.sha256;variant=$null;build='20261026'} |
| 91 | $metadata = @{}; $metadata[$manifest.python.key] = $download |
| 92 | [IO.File]::WriteAllText($pythonMeta, ($metadata | ConvertTo-Json -Depth 5), (New-Object Text.UTF8Encoding($false))) |
| 93 | Protect-Path $pythonMeta $false |
| 94 | $oldCache = [Environment]::GetEnvironmentVariable('UV_PYTHON_CACHE_DIR', 'Process') |
| 95 | try { |
| 96 | [Environment]::SetEnvironmentVariable('UV_PYTHON_CACHE_DIR', $null, 'Process') |
| 97 | & $uv python install $manifest.python.key --install-dir $pythonDir --no-bin --no-registry --no-config --offline --python-downloads-json-url $pythonMeta |
| 98 | if ($LASTEXITCODE -ne 0) { throw 'Offline uv Python installation failed.' } |
| 99 | } finally { [Environment]::SetEnvironmentVariable('UV_PYTHON_CACHE_DIR', $oldCache, 'Process') } |
| 100 | $python = Join-Path $pythonDir ($manifest.python.key + '\python.exe') |
| 101 | Assert-NoReparse $python |
| 102 | if ((& $python -X utf8 -I -c 'import platform; print(platform.python_version())') -ne $manifest.python.version) { throw 'The native Python version does not match.' } |
| 103 | $gitDir = Join-Path $tools ('git\' + $manifest.git.version) |
| 104 | if (-not (Test-Path (Join-Path $gitDir 'bin\bash.exe'))) { |
| 105 | New-PrivateDirectory $gitDir |
| 106 | $extract = Start-Process -FilePath $packages.git -ArgumentList @('-y', ('-o"' + $gitDir + '"')) -Wait -PassThru -NoNewWindow |
| 107 | if ($extract.ExitCode -ne 0) { throw 'Portable Git extraction failed.' } |
| 108 | } |
| 109 | $bash = Join-Path $gitDir 'bin\bash.exe'; Assert-NoReparse $bash |
| 110 | $claudeDir = Join-Path $tools ('claude\' + $manifest.claude.version) |
| 111 | New-PrivateDirectory $claudeDir |
| 112 | $claude = Join-Path $claudeDir 'claude.exe' |
| 113 | if (-not (Test-Path -LiteralPath $claude)) { [IO.File]::Copy($packages.claude, $claude, $false) } |
| 114 | if ((Get-FileHash -LiteralPath $claude -Algorithm SHA256).Hash.ToLowerInvariant() -ne $manifest.claude.sha256) { throw 'The Cage-owned native Claude binary changed.' } |
| 115 | # The official native binary is used as a versioned custom launcher. No default |
| 116 | # Claude account, existing installer, project, settings or history is replaced. |
| 117 | $receipt = [ordered]@{version=1;python=$python;python_version=$manifest.python.version;python_sha256=(Get-FileHash $python -Algorithm SHA256).Hash.ToLowerInvariant();claude=$claude;claude_version=$manifest.claude.version;claude_sha256=$manifest.claude.sha256;git_bash=$bash;git_bash_sha256=(Get-FileHash $bash -Algorithm SHA256).Hash.ToLowerInvariant();uv_version=$manifest.uv.version} |
| 118 | Assert-NoReparse $bridge |
| 119 | if ($WorkbenchSetup) { |
| 120 | # The provisioning process owns this file and its directory. The paired |
| 121 | # user can write the receipt, but cannot replace the file or change its ACL. |
| 122 | $staged = Join-Path $bridge 'setup-packages\cli-receipt.in' |
| 123 | Assert-NoReparse $staged |
| 124 | [IO.File]::WriteAllText($staged, ($receipt | ConvertTo-Json), (New-Object Text.UTF8Encoding($false))) |
| 125 | return |
| 126 | } |
| 127 | $receiptDir = [IO.Path]::GetFullPath($ReceiptDirectory) |
| 128 | $receiptRoot = [IO.Path]::GetFullPath((Join-Path $env:USERPROFILE 'Cage\CLI')) |
| 129 | if (-not $receiptDir.StartsWith($receiptRoot + '\', [StringComparison]::OrdinalIgnoreCase)) { throw 'The receipt staging directory must be inside the current user Cage CLI directory.' } |
| 130 | New-PrivateDirectory $receiptDir |
| 131 | $target = Join-Path $receiptDir 'cli-tools.json' |
| 132 | $temporary = Join-Path $receiptDir ('cli-tools.' + [Guid]::NewGuid().ToString('N') + '.json') |
| 133 | [IO.File]::WriteAllText($temporary, ($receipt | ConvertTo-Json), (New-Object Text.UTF8Encoding($false))) |
| 134 | Protect-Path $temporary $false |
| 135 | Move-Item -LiteralPath $temporary -Destination $target -Force |
| 136 | Write-Output 'Native Cage CLI tools installed. Management must copy the staged receipt into the readonly paired bridge, then restart only that bridge. Official account login remains user-controlled.' |