| 1 | # Shared build helpers. PowerShell 7 runs these scripts on Windows, macOS and Linux. |
| 2 | Set-StrictMode -Version Latest |
| 3 | $ErrorActionPreference = 'Stop' |
| 4 | $PSNativeCommandUseErrorActionPreference = $true |
| 5 | |
| 6 | function Invoke-BuildTool { |
| 7 | param([string]$Tool, [string[]]$Arguments) |
| 8 | & $Tool @Arguments |
| 9 | if ($LASTEXITCODE -ne 0) { throw "$Tool failed with exit code $LASTEXITCODE" } |
| 10 | } |
| 11 | |
| 12 | function Get-WindowsWorkbenchTestBase { |
| 13 | if ($env:RUNNER_TEMP) { return [IO.Path]::GetFullPath($env:RUNNER_TEMP) } |
| 14 | return [IO.Path]::GetTempPath() |
| 15 | } |
| 16 | |
| 17 | function Invoke-InIsolatedTestTemp { |
| 18 | param([Parameter(Mandatory)][scriptblock]$Checks) |
| 19 | # Windows' default temp is inside AppData, which must remain protected |
| 20 | # against project sharing. Put test projects in the runner's own temp. |
| 21 | $directory = Join-Path (Get-WindowsWorkbenchTestBase) ('cage-go-tests-' + [guid]::NewGuid().ToString('N')) |
| 22 | New-Item -ItemType Directory -Path $directory | Out-Null |
| 23 | $savedTemp = $env:TEMP; $savedTmp = $env:TMP |
| 24 | try { |
| 25 | $env:TEMP = $directory; $env:TMP = $directory |
| 26 | & $Checks |
| 27 | } finally { |
| 28 | $env:TEMP = $savedTemp; $env:TMP = $savedTmp |
| 29 | Remove-Item -LiteralPath $directory -Recurse -Force -ErrorAction SilentlyContinue |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | function ConvertTo-SmokeSafeText { |
| 34 | param($Value) |
| 35 | if ($Value -isnot [string]) { return '' } |
| 36 | $text = [regex]::Replace($Value, 'https?://[^\s"''<>]+', { |
| 37 | param($match) |
| 38 | try { return ([Uri]$match.Value).GetLeftPart([UriPartial]::Path) } |
| 39 | catch { return '[URL omitted]' } |
| 40 | }) |
| 41 | $text = $text -replace '[?#][^\s"''<>)]*', '[redacted]' |
| 42 | return $text.Substring(0, [Math]::Min(768, $text.Length)) |
| 43 | } |
| 44 | |
| 45 | function Assert-WindowsWorkbenchReport { |
| 46 | param([int]$ExitCode, [string]$Report) |
| 47 | if (-not (Test-Path -LiteralPath $Report -PathType Leaf)) { throw "Cage workbench acceptance failed ($ExitCode). No smoke report: $Report" } |
| 48 | if ((Get-Item -LiteralPath $Report).Length -gt 65536) { throw 'Cage smoke report exceeds the bounded diagnostic size.' } |
| 49 | $result = Get-Content -LiteralPath $Report -Raw | ConvertFrom-Json -AsHashtable |
| 50 | $safe = @{ phase = ConvertTo-SmokeSafeText $result['phase']; nativeStatus = ConvertTo-SmokeSafeText $result['nativeStatus']; jsErrors = @() } |
| 51 | if ($result['prepareExit'] -is [int] -or $result['prepareExit'] -is [long]) { $safe.prepareExit = $result['prepareExit'] } |
| 52 | if ($result['prepareStatus'] -in @('prepared', 'stop_required', 'error', 'unexpected')) { $safe.prepareStatus = $result['prepareStatus'] } |
| 53 | if ($result['page'] -is [System.Collections.IDictionary] -and $result['page']['errors']) { |
| 54 | $safe.jsErrors = @($result['page']['errors'] | Select-Object -First 8 | ForEach-Object { |
| 55 | if ($_ -isnot [System.Collections.IDictionary]) { return } |
| 56 | @{ |
| 57 | type = ConvertTo-SmokeSafeText $_['type'] |
| 58 | source = if ($_['source'] -is [string] -and $_['source'].StartsWith('/')) { ConvertTo-SmokeSafeText $_['source'] } else { '' } |
| 59 | message = ConvertTo-SmokeSafeText $_['message'] |
| 60 | stack = @($_['stack'] | Select-Object -First 6 | ForEach-Object { ConvertTo-SmokeSafeText $_ }) |
| 61 | } |
| 62 | }) |
| 63 | } |
| 64 | # Log only these already-bounded fields, even when the process failed. Do |
| 65 | # not print launch entries, page URLs, account data or the raw report. |
| 66 | Write-Host ('Cage smoke diagnostic: ' + ($safe | ConvertTo-Json -Depth 6 -Compress)) |
| 67 | if ($ExitCode -ne 0 -or $result['success'] -ne $true -or $result['nativeBridgeReady'] -ne $true) { |
| 68 | throw "Cage workbench/bridge acceptance failed ($ExitCode), phase $($safe.phase): $($safe.nativeStatus). Diagnostics: $Report" |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | function Assert-WindowsWorkbench { |
| 73 | param([Parameter(Mandatory)][string]$AppDirectory) |
| 74 | if (-not $IsWindows) { throw 'Workbench acceptance requires Windows.' } |
| 75 | $testRoot = Join-Path (Get-WindowsWorkbenchTestBase) ('cage-build-ui-' + [guid]::NewGuid().ToString('N')) |
| 76 | New-Item -ItemType Directory -Path $testRoot -Force | Out-Null |
| 77 | $report = Join-Path $testRoot 'smoke.json' |
| 78 | $start = [Diagnostics.ProcessStartInfo]::new((Join-Path $AppDirectory 'Cage.exe')) |
| 79 | $start.UseShellExecute = $false |
| 80 | $start.WorkingDirectory = $AppDirectory |
| 81 | $start.Environment['CLAUDE_CAGE_CONFIG'] = Join-Path $testRoot 'profile/config.json' |
| 82 | $start.ArgumentList.Add('--smoke-test') |
| 83 | $start.ArgumentList.Add($report) |
| 84 | $window = [Diagnostics.Process]::Start($start) |
| 85 | $passed = $false |
| 86 | try { |
| 87 | if (-not $window.WaitForExit(180000)) { throw "Cage workbench acceptance timed out. Diagnostics retained at $testRoot" } |
| 88 | Assert-WindowsWorkbenchReport -ExitCode $window.ExitCode -Report $report |
| 89 | $passed = $true |
| 90 | } finally { |
| 91 | if (-not $window.HasExited) { $window.Kill($true); $window.WaitForExit() } |
| 92 | $window.Dispose() |
| 93 | if (-not $passed) { |
| 94 | # Close only this test's authenticated controller. Killing every |
| 95 | # cage.exe could terminate another installed application or VM. |
| 96 | try { |
| 97 | $cleanup = [Diagnostics.ProcessStartInfo]::new((Join-Path $AppDirectory 'resources/cage.exe')) |
| 98 | $cleanup.UseShellExecute = $false |
| 99 | $cleanup.CreateNoWindow = $true |
| 100 | $cleanup.RedirectStandardOutput = $true |
| 101 | $cleanup.RedirectStandardError = $true |
| 102 | $cleanup.Environment['CLAUDE_CAGE_CONFIG'] = Join-Path $testRoot 'profile/config.json' |
| 103 | $cleanup.ArgumentList.Add('prepare-update'); $cleanup.ArgumentList.Add('--json') |
| 104 | $controller = [Diagnostics.Process]::Start($cleanup) |
| 105 | try { |
| 106 | $stdout = $controller.StandardOutput.ReadToEndAsync() |
| 107 | $stderr = $controller.StandardError.ReadToEndAsync() |
| 108 | if (-not $controller.WaitForExit(20000)) { $controller.Kill($true); $controller.WaitForExit() } |
| 109 | if ($controller.ExitCode -ne 0) { Write-Warning 'The isolated smoke controller did not confirm shutdown; its profile is retained.' } |
| 110 | } finally { $controller.Dispose() } |
| 111 | } catch { Write-Warning "Isolated smoke cleanup failed: $($_.Exception.Message)" } |
| 112 | } |
| 113 | # A successful smoke report is written only after the isolated backend |
| 114 | # confirms shutdown. Failed profiles remain available for diagnosis. |
| 115 | if ($passed) { Remove-Item -LiteralPath $testRoot -Recurse -Force -ErrorAction SilentlyContinue } |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | function Get-CageVersion { |
| 120 | param([string]$Repository) |
| 121 | $value = (Get-Content -LiteralPath (Join-Path $Repository 'VERSION') -Raw).Trim() |
| 122 | if ($value -notmatch '^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$') { throw 'Invalid VERSION.' } |
| 123 | return $value |
| 124 | } |
| 125 | |
| 126 | function Get-BuildCommand { |
| 127 | param([string[]]$Names) |
| 128 | foreach ($name in $Names) { |
| 129 | $command = Get-Command $name -ErrorAction SilentlyContinue |
| 130 | if ($command) { return $command.Source } |
| 131 | } |
| 132 | throw "Missing build tool: $($Names -join ' or ')" |
| 133 | } |
| 134 | |
| 135 | function Get-VerifiedDependency { |
| 136 | param($Dependency, [string]$Cache) |
| 137 | if ($Dependency.url -notlike 'https://*') { throw 'Build dependencies must use HTTPS.' } |
| 138 | $path = Join-Path $Cache $Dependency.file |
| 139 | if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { |
| 140 | New-Item -ItemType Directory -Path $Cache -Force | Out-Null |
| 141 | $partial = "$path.partial" |
| 142 | try { |
| 143 | Invoke-WebRequest -Uri $Dependency.url -OutFile $partial -TimeoutSec 900 -MaximumRedirection 5 |
| 144 | Move-Item -LiteralPath $partial -Destination $path -Force |
| 145 | } finally { |
| 146 | if (Test-Path -LiteralPath $partial) { Remove-Item -LiteralPath $partial -Force } |
| 147 | } |
| 148 | } |
| 149 | $actual = (Get-FileHash -LiteralPath $path -Algorithm $Dependency.algorithm).Hash |
| 150 | if ($actual -ne $Dependency.hash) { throw "Dependency checksum mismatch: $($Dependency.file). Remove the cached file and retry." } |
| 151 | return $path |
| 152 | } |
| 153 | |
| 154 | function Expand-BuildArchive { |
| 155 | param([string]$Archive, [string]$Destination, [string]$SevenZip) |
| 156 | New-Item -ItemType Directory -Path $Destination -Force | Out-Null |
| 157 | Invoke-BuildTool $SevenZip @('x', '-y', '-bso0', '-bsp0', "-o$Destination", $Archive) |
| 158 | } |
| 159 | |
| 160 | function Get-VerifiedGitArchive { |
| 161 | param($Dependency, [string]$Cache) |
| 162 | $archive = Join-Path $Cache $Dependency.file |
| 163 | if (-not (Test-Path -LiteralPath $archive)) { |
| 164 | $git = Get-BuildCommand @('git.exe', 'git') |
| 165 | $checkout = Join-Path $Cache ('source-' + [guid]::NewGuid().ToString('N')) |
| 166 | $partial = "$archive.partial" |
| 167 | try { |
| 168 | Invoke-BuildTool $git @('init', '--bare', '--quiet', $checkout) |
| 169 | Invoke-BuildTool $git @('--git-dir', $checkout, 'fetch', '--depth=1', $Dependency.repository, $Dependency.commit) |
| 170 | $actualCommit = & $git '--git-dir' $checkout 'rev-parse' 'FETCH_HEAD' |
| 171 | if ($LASTEXITCODE -ne 0 -or $actualCommit -ne $Dependency.commit) { throw 'Fetched source commit does not match the pinned QEMU build.' } |
| 172 | # Git for Windows defaults can change archive bytes. Keep the |
| 173 | # pinned source identical to the reviewed POSIX-generated archive. |
| 174 | Invoke-BuildTool $git @('--git-dir', $checkout, '-c', 'core.autocrlf=false', '-c', 'tar.umask=0002', 'archive', '--format=tar', "--prefix=$($Dependency.prefix)", "--output=$partial", $Dependency.commit) |
| 175 | $actualHash = (Get-FileHash -LiteralPath $partial -Algorithm SHA256).Hash.ToLowerInvariant() |
| 176 | if ($actualHash -ne $Dependency.hash) { throw "Source archive checksum mismatch: $($Dependency.file); expected $($Dependency.hash), actual $actualHash" } |
| 177 | Move-Item -LiteralPath $partial -Destination $archive |
| 178 | } finally { |
| 179 | Remove-Item -LiteralPath $checkout -Recurse -Force -ErrorAction SilentlyContinue |
| 180 | Remove-Item -LiteralPath $partial -Force -ErrorAction SilentlyContinue |
| 181 | } |
| 182 | } |
| 183 | $actualHash = (Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash.ToLowerInvariant() |
| 184 | if ($actualHash -ne $Dependency.hash) { throw "Source archive checksum mismatch: $($Dependency.file); expected $($Dependency.hash), actual $actualHash. Remove the cached file and retry." } |
| 185 | return $archive |
| 186 | } |
| 187 | |
| 188 | function Get-SigningTool { |
| 189 | $command = Get-Command signtool.exe -ErrorAction SilentlyContinue |
| 190 | if ($command) { return $command.Source } |
| 191 | if ($IsWindows) { |
| 192 | $kits = Join-Path ${env:ProgramFiles(x86)} 'Windows Kits/10/bin' |
| 193 | $candidate = Get-ChildItem -LiteralPath $kits -Directory -ErrorAction SilentlyContinue | |
| 194 | Sort-Object Name -Descending | ForEach-Object { Join-Path $_.FullName 'x64/signtool.exe' } | |
| 195 | Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1 |
| 196 | if ($candidate) { return $candidate } |
| 197 | } |
| 198 | throw 'Release signing requires Windows SDK signtool.exe on Windows.' |
| 199 | } |
| 200 | |
| 201 | function Assert-WindowsSigningConfiguration { |
| 202 | if (-not $IsWindows) { throw 'Trusted Windows build verification requires Windows.' } |
| 203 | $null = Get-SigningTool |
| 204 | if ($env:CAGE_WINDOWS_SIGNING_PROVIDER -eq 'esigner') { |
| 205 | if ($env:CAGE_ESIGNER_CREDENTIAL_ID -notmatch '^[0-9A-Fa-f-]{36}$' -or |
| 206 | $env:CAGE_ESIGNER_CERTIFICATE_SERIAL -notmatch '^[0-9A-Fa-f]{32,40}$') { |
| 207 | throw 'eSigner requires CAGE_ESIGNER_CREDENTIAL_ID and the expected CAGE_ESIGNER_CERTIFICATE_SERIAL.' |
| 208 | } |
| 209 | } elseif ($env:CAGE_WINDOWS_SIGNING_PROVIDER -and $env:CAGE_WINDOWS_SIGNING_PROVIDER -ne 'certificate-store') { |
| 210 | throw 'Unknown CAGE_WINDOWS_SIGNING_PROVIDER; use esigner or certificate-store.' |
| 211 | } elseif ($env:CAGE_WINDOWS_CERT_SHA1 -notmatch '^[0-9A-Fa-f]{40}$') { |
| 212 | throw 'Certificate-store signing requires CAGE_WINDOWS_CERT_SHA1.' |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | function Sign-CageFile { |
| 217 | param([string]$Path, [string]$SignTool) |
| 218 | Assert-WindowsSigningConfiguration |
| 219 | if ($env:CAGE_WINDOWS_SIGNING_PROVIDER -eq 'esigner') { |
| 220 | $Path = [IO.Path]::GetFullPath($Path) |
| 221 | $stage = Join-Path ([IO.Path]::GetTempPath()) ('cage-signed-' + [guid]::NewGuid().ToString('N')) |
| 222 | try { |
| 223 | Invoke-BuildTool (Get-BuildCommand @('node.exe', 'node')) @((Join-Path $PSScriptRoot 'esigner.mjs'), 'sign', $Path, '--output-dir', $stage) |
| 224 | $signed = Join-Path $stage ([IO.Path]::GetFileName($Path)) |
| 225 | Invoke-BuildTool $SignTool @('verify', '/pa', '/all', '/tw', $signed) |
| 226 | $signature = Get-AuthenticodeSignature -LiteralPath $signed |
| 227 | if ($signature.Status -ne 'Valid' -or -not $signature.TimeStamperCertificate -or |
| 228 | $signature.SignerCertificate.SerialNumber -ne $env:CAGE_ESIGNER_CERTIFICATE_SERIAL -or |
| 229 | ($env:CAGE_WINDOWS_CERT_SHA1 -and $signature.SignerCertificate.Thumbprint -ne $env:CAGE_WINDOWS_CERT_SHA1)) { |
| 230 | throw 'eSigner output lacks the expected trusted publisher certificate or timestamp. Original file retained.' |
| 231 | } |
| 232 | $env:CAGE_WINDOWS_CERT_SHA1 = $signature.SignerCertificate.Thumbprint |
| 233 | Copy-Item -LiteralPath $signed -Destination $Path -Force |
| 234 | } finally { if (Test-Path -LiteralPath $stage) { Remove-Item -LiteralPath $stage -Recurse -Force } } |
| 235 | } else { |
| 236 | Invoke-BuildTool $SignTool @('sign', '/sha1', $env:CAGE_WINDOWS_CERT_SHA1, '/fd', 'SHA256', |
| 237 | '/tr', 'http://timestamp.digicert.com', '/td', 'SHA256', '/d', 'Cage', $Path) |
| 238 | Invoke-BuildTool $SignTool @('verify', '/pa', '/all', $Path) |
| 239 | } |
| 240 | } |